2 * Copyright (C) 2012, 2013, 2014
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
29 #define PARSER_HT_LOCALS 2
30 #define PARSER_HT_SIZE 512
31 #define TYPEDEF_HT_SIZE 512
33 static void parser_enterblock(parser_t *parser);
34 static bool parser_leaveblock(parser_t *parser);
35 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
36 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
37 static bool parse_typedef(parser_t *parser);
38 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);
39 static ast_block* parse_block(parser_t *parser);
40 static bool parse_block_into(parser_t *parser, ast_block *block);
41 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
42 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
43 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
44 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
45 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
46 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
47 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
49 static void parseerror(parser_t *parser, const char *fmt, ...)
53 vcompile_error(parser->lex->tok.ctx, fmt, ap);
57 /* returns true if it counts as an error */
58 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
63 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
68 /**********************************************************************
72 static bool parser_next(parser_t *parser)
74 /* lex_do kills the previous token */
75 parser->tok = lex_do(parser->lex);
76 if (parser->tok == TOKEN_EOF)
78 if (parser->tok >= TOKEN_ERROR) {
79 parseerror(parser, "lex error");
85 #define parser_tokval(p) ((p)->lex->tok.value)
86 #define parser_token(p) (&((p)->lex->tok))
88 char *parser_strdup(const char *str)
91 /* actually dup empty strings */
92 char *out = (char*)mem_a(1);
96 return util_strdup(str);
99 static ast_expression* parser_find_field(parser_t *parser, const char *name)
101 return ( ast_expression*)util_htget(parser->htfields, name);
104 static ast_expression* parser_find_label(parser_t *parser, const char *name)
107 for(i = 0; i < vec_size(parser->labels); i++)
108 if (!strcmp(parser->labels[i]->name, name))
109 return (ast_expression*)parser->labels[i];
113 ast_expression* parser_find_global(parser_t *parser, const char *name)
115 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
118 return (ast_expression*)util_htget(parser->htglobals, name);
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
125 if (!parser->function)
127 fun = parser->function->vtype;
128 for (i = 0; i < vec_size(fun->expression.params); ++i) {
129 if (!strcmp(fun->expression.params[i]->name, name))
130 return (ast_expression*)(fun->expression.params[i]);
135 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
140 hash = util_hthash(parser->htglobals, name);
143 for (i = vec_size(parser->variables); i > upto;) {
145 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
149 return parser_find_param(parser, name);
152 static ast_expression* parser_find_var(parser_t *parser, const char *name)
156 v = parser_find_local(parser, name, 0, &dummy);
157 if (!v) v = parser_find_global(parser, name);
161 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
165 hash = util_hthash(parser->typedefs[0], name);
167 for (i = vec_size(parser->typedefs); i > upto;) {
169 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
177 size_t etype; /* 0 = expression, others are operators */
181 ast_block *block; /* for commas and function calls */
200 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
211 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
215 e.out = (ast_expression*)v;
222 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
224 e.etype = 1 + (op - operators);
233 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
244 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
245 * so we need to rotate it to become ent.(foo[n]).
247 static bool rotate_entfield_array_index_nodes(ast_expression **out)
249 ast_array_index *index, *oldindex;
250 ast_entfield *entfield;
254 ast_expression *entity;
256 lex_ctx_t ctx = ast_ctx(*out);
258 if (!ast_istype(*out, ast_array_index))
260 index = (ast_array_index*)*out;
262 if (!ast_istype(index->array, ast_entfield))
264 entfield = (ast_entfield*)index->array;
266 if (!ast_istype(entfield->field, ast_value))
268 field = (ast_value*)entfield->field;
271 entity = entfield->entity;
275 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
276 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
277 *out = (ast_expression*)entfield;
279 oldindex->array = NULL;
280 oldindex->index = NULL;
281 ast_delete(oldindex);
286 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
288 if (ast_istype(expr, ast_value)) {
289 ast_value *val = (ast_value*)expr;
290 if (val->cvq == CV_CONST) {
291 if (val->name[0] == '#') {
292 compile_error(ctx, "invalid assignment to a literal constant");
296 * To work around quakeworld we must elide the error and make it
299 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
300 compile_error(ctx, "assignment to constant `%s`", val->name);
302 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
309 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
313 ast_expression *out = NULL;
314 ast_expression *exprs[3];
315 ast_block *blocks[3];
316 ast_binstore *asbinstore;
317 size_t i, assignop, addop, subop;
318 qcint_t generated_op = 0;
323 if (!vec_size(sy->ops)) {
324 parseerror(parser, "internal error: missing operator");
328 if (vec_last(sy->ops).isparen) {
329 parseerror(parser, "unmatched parenthesis");
333 op = &operators[vec_last(sy->ops).etype - 1];
334 ctx = vec_last(sy->ops).ctx;
336 if (vec_size(sy->out) < op->operands) {
337 if (op->flags & OP_PREFIX)
338 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
339 else /* this should have errored previously already */
340 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
344 vec_shrinkby(sy->ops, 1);
346 /* op(:?) has no input and no output */
350 vec_shrinkby(sy->out, op->operands);
351 for (i = 0; i < op->operands; ++i) {
352 exprs[i] = sy->out[vec_size(sy->out)+i].out;
353 blocks[i] = sy->out[vec_size(sy->out)+i].block;
355 if (exprs[i]->vtype == TYPE_NOEXPR &&
356 !(i != 0 && op->id == opid2('?',':')) &&
357 !(i == 1 && op->id == opid1('.')))
359 if (ast_istype(exprs[i], ast_label))
360 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
362 compile_error(ast_ctx(exprs[i]), "not an expression");
363 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
367 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
368 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
372 #define NotSameType(T) \
373 (exprs[0]->vtype != exprs[1]->vtype || \
374 exprs[0]->vtype != T)
379 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
383 if (exprs[0]->vtype == TYPE_VECTOR &&
384 exprs[1]->vtype == TYPE_NOEXPR)
386 if (exprs[1] == (ast_expression*)parser->const_vec[0])
387 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
388 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
389 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
390 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
391 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
393 compile_error(ctx, "access to invalid vector component");
397 else if (exprs[0]->vtype == TYPE_ENTITY) {
398 if (exprs[1]->vtype != TYPE_FIELD) {
399 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
402 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
404 else if (exprs[0]->vtype == TYPE_VECTOR) {
405 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
409 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
415 if (exprs[0]->vtype != TYPE_ARRAY &&
416 !(exprs[0]->vtype == TYPE_FIELD &&
417 exprs[0]->next->vtype == TYPE_ARRAY))
419 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
420 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
423 if (exprs[1]->vtype != TYPE_FLOAT) {
424 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
425 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
428 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
429 if (rotate_entfield_array_index_nodes(&out))
432 /* This is not broken in fteqcc anymore */
433 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
434 /* this error doesn't need to make us bail out */
435 (void)!parsewarning(parser, WARN_EXTENSIONS,
436 "accessing array-field members of an entity without parenthesis\n"
437 " -> this is an extension from -std=gmqcc");
444 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
445 vec_push(sy->out, syexp(ctx, exprs[0]));
446 vec_push(sy->out, syexp(ctx, exprs[1]));
447 vec_last(sy->argc)++;
451 if (!ast_block_add_expr(blocks[0], exprs[1]))
454 blocks[0] = ast_block_new(ctx);
455 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
456 !ast_block_add_expr(blocks[0], exprs[1]))
461 ast_block_set_type(blocks[0], exprs[1]);
463 vec_push(sy->out, syblock(ctx, blocks[0]));
470 if ((out = fold_op(parser->fold, op, exprs)))
473 if (exprs[0]->vtype != TYPE_FLOAT &&
474 exprs[0]->vtype != TYPE_VECTOR) {
475 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
476 type_name[exprs[0]->vtype]);
479 if (exprs[0]->vtype == TYPE_FLOAT)
480 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
482 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
486 if (!(out = fold_op(parser->fold, op, exprs))) {
487 switch (exprs[0]->vtype) {
489 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
495 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
496 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
498 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
500 /* we don't constant-fold NOT for these types */
502 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
505 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
508 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
509 type_name[exprs[0]->vtype]);
516 if (exprs[0]->vtype != exprs[1]->vtype ||
517 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
519 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
520 type_name[exprs[0]->vtype],
521 type_name[exprs[1]->vtype]);
524 if (!(out = fold_op(parser->fold, op, exprs))) {
525 switch (exprs[0]->vtype) {
527 out = fold_binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
530 out = fold_binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
533 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
534 type_name[exprs[0]->vtype],
535 type_name[exprs[1]->vtype]);
541 if (exprs[0]->vtype != exprs[1]->vtype ||
542 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
544 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
545 type_name[exprs[1]->vtype],
546 type_name[exprs[0]->vtype]);
549 if (!(out = fold_op(parser->fold, op, exprs))) {
550 switch (exprs[0]->vtype) {
552 out = fold_binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
555 out = fold_binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
558 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
559 type_name[exprs[1]->vtype],
560 type_name[exprs[0]->vtype]);
566 if (exprs[0]->vtype != exprs[1]->vtype &&
567 !(exprs[0]->vtype == TYPE_VECTOR &&
568 exprs[1]->vtype == TYPE_FLOAT) &&
569 !(exprs[1]->vtype == TYPE_VECTOR &&
570 exprs[0]->vtype == TYPE_FLOAT)
573 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
574 type_name[exprs[1]->vtype],
575 type_name[exprs[0]->vtype]);
578 if (!(out = fold_op(parser->fold, op, exprs))) {
579 switch (exprs[0]->vtype) {
581 if (exprs[1]->vtype == TYPE_VECTOR)
582 out = fold_binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
584 out = fold_binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
587 if (exprs[1]->vtype == TYPE_FLOAT)
588 out = fold_binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
590 out = fold_binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
593 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
594 type_name[exprs[1]->vtype],
595 type_name[exprs[0]->vtype]);
602 if (exprs[1]->vtype != TYPE_FLOAT) {
603 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
604 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
605 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
608 if (!(out = fold_op(parser->fold, op, exprs))) {
609 if (exprs[0]->vtype == TYPE_FLOAT)
610 out = fold_binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
612 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
613 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
614 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
621 if (NotSameType(TYPE_FLOAT)) {
622 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
623 type_name[exprs[0]->vtype],
624 type_name[exprs[1]->vtype]);
626 } else if (!(out = fold_op(parser->fold, op, exprs))) {
627 /* generate a call to __builtin_mod */
628 ast_expression *mod = intrin_func(parser->intrin, "mod");
629 ast_call *call = NULL;
630 if (!mod) return false; /* can return null for missing floor */
632 call = ast_call_new(parser_ctx(parser), mod);
633 vec_push(call->params, exprs[0]);
634 vec_push(call->params, exprs[1]);
636 out = (ast_expression*)call;
641 compile_error(ctx, "%= is unimplemented");
647 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
648 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
649 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
651 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
652 type_name[exprs[0]->vtype],
653 type_name[exprs[1]->vtype]);
657 if (!(out = fold_op(parser->fold, op, exprs))) {
659 * IF the first expression is float, the following will be too
660 * since scalar ^ vector is not allowed.
662 if (exprs[0]->vtype == TYPE_FLOAT) {
663 out = fold_binary(ctx,
664 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
668 * The first is a vector: vector is allowed to bitop with vector and
669 * with scalar, branch here for the second operand.
671 if (exprs[1]->vtype == TYPE_VECTOR) {
673 * Bitop all the values of the vector components against the
674 * vectors components in question.
676 out = fold_binary(ctx,
677 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
680 out = fold_binary(ctx,
681 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
690 if (NotSameType(TYPE_FLOAT)) {
691 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
692 type_name[exprs[0]->vtype],
693 type_name[exprs[1]->vtype]);
697 if (!(out = fold_op(parser->fold, op, exprs))) {
698 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
699 ast_call *call = ast_call_new(parser_ctx(parser), shift);
700 vec_push(call->params, exprs[0]);
701 vec_push(call->params, exprs[1]);
702 out = (ast_expression*)call;
706 case opid3('<','<','='):
707 case opid3('>','>','='):
708 if (NotSameType(TYPE_FLOAT)) {
709 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
710 type_name[exprs[0]->vtype],
711 type_name[exprs[1]->vtype]);
715 if(!(out = fold_op(parser->fold, op, exprs))) {
716 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
717 ast_call *call = ast_call_new(parser_ctx(parser), shift);
718 vec_push(call->params, exprs[0]);
719 vec_push(call->params, exprs[1]);
720 out = (ast_expression*)ast_store_new(
724 (ast_expression*)call
731 generated_op += 1; /* INSTR_OR */
733 generated_op += INSTR_AND;
734 if (!(out = fold_op(parser->fold, op, exprs))) {
735 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
736 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
737 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
738 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
741 for (i = 0; i < 2; ++i) {
742 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
743 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
745 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
747 exprs[i] = out; out = NULL;
748 if (OPTS_FLAG(PERL_LOGIC)) {
749 /* here we want to keep the right expressions' type */
753 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
754 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
756 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
758 exprs[i] = out; out = NULL;
759 if (OPTS_FLAG(PERL_LOGIC)) {
760 /* here we want to keep the right expressions' type */
765 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
770 if (vec_last(sy->paren) != PAREN_TERNARY2) {
771 compile_error(ctx, "mismatched parenthesis/ternary");
775 if (!ast_compare_type(exprs[1], exprs[2])) {
776 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
777 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
778 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
781 if (!(out = fold_op(parser->fold, op, exprs)))
782 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
785 case opid2('*', '*'):
786 if (NotSameType(TYPE_FLOAT)) {
787 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
788 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
789 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
794 if (!(out = fold_op(parser->fold, op, exprs))) {
795 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
796 vec_push(gencall->params, exprs[0]);
797 vec_push(gencall->params, exprs[1]);
798 out = (ast_expression*)gencall;
802 case opid2('>', '<'):
803 if (NotSameType(TYPE_VECTOR)) {
804 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
805 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
806 compile_error(ctx, "invalid types used in cross product: %s and %s",
811 if (!(out = fold_op(parser->fold, op, exprs))) {
822 case opid3('<','=','>'): /* -1, 0, or 1 */
823 if (NotSameType(TYPE_FLOAT)) {
824 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
825 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
826 compile_error(ctx, "invalid types used in comparision: %s and %s",
832 if (!(out = fold_op(parser->fold, op, exprs))) {
833 /* This whole block is NOT fold_binary safe */
834 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
836 eq->refs = AST_REF_NONE;
839 out = (ast_expression*)ast_ternary_new(ctx,
840 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
842 (ast_expression*)parser->fold->imm_float[2],
845 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
847 (ast_expression*)parser->fold->imm_float[0],
850 (ast_expression*)parser->fold->imm_float[1]
860 generated_op += 1; /* INSTR_GT */
862 generated_op += 1; /* INSTR_LT */
863 case opid2('>', '='):
864 generated_op += 1; /* INSTR_GE */
865 case opid2('<', '='):
866 generated_op += INSTR_LE;
867 if (NotSameType(TYPE_FLOAT)) {
868 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
869 type_name[exprs[0]->vtype],
870 type_name[exprs[1]->vtype]);
873 if (!(out = fold_op(parser->fold, op, exprs)))
874 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
876 case opid2('!', '='):
877 if (exprs[0]->vtype != exprs[1]->vtype) {
878 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
879 type_name[exprs[0]->vtype],
880 type_name[exprs[1]->vtype]);
883 if (!(out = fold_op(parser->fold, op, exprs)))
884 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
886 case opid2('=', '='):
887 if (exprs[0]->vtype != exprs[1]->vtype) {
888 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
889 type_name[exprs[0]->vtype],
890 type_name[exprs[1]->vtype]);
893 if (!(out = fold_op(parser->fold, op, exprs)))
894 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
898 if (ast_istype(exprs[0], ast_entfield)) {
899 ast_expression *field = ((ast_entfield*)exprs[0])->field;
900 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
901 exprs[0]->vtype == TYPE_FIELD &&
902 exprs[0]->next->vtype == TYPE_VECTOR)
904 assignop = type_storep_instr[TYPE_VECTOR];
907 assignop = type_storep_instr[exprs[0]->vtype];
908 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
910 ast_type_to_string(field->next, ty1, sizeof(ty1));
911 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
912 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
913 field->next->vtype == TYPE_FUNCTION &&
914 exprs[1]->vtype == TYPE_FUNCTION)
916 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
917 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
920 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
925 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
926 exprs[0]->vtype == TYPE_FIELD &&
927 exprs[0]->next->vtype == TYPE_VECTOR)
929 assignop = type_store_instr[TYPE_VECTOR];
932 assignop = type_store_instr[exprs[0]->vtype];
935 if (assignop == VINSTR_END) {
936 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
937 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
938 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
940 else if (!ast_compare_type(exprs[0], exprs[1]))
942 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
943 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
944 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
945 exprs[0]->vtype == TYPE_FUNCTION &&
946 exprs[1]->vtype == TYPE_FUNCTION)
948 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
949 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
952 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
955 (void)check_write_to(ctx, exprs[0]);
956 /* When we're a vector of part of an entity field we use STOREP */
957 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->owner, ast_entfield))
958 assignop = INSTR_STOREP_F;
959 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
961 case opid3('+','+','P'):
962 case opid3('-','-','P'):
964 if (exprs[0]->vtype != TYPE_FLOAT) {
965 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
966 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
969 if (op->id == opid3('+','+','P'))
973 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
974 if (ast_istype(exprs[0], ast_entfield)) {
975 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
977 (ast_expression*)parser->fold->imm_float[1]);
979 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
981 (ast_expression*)parser->fold->imm_float[1]);
984 case opid3('S','+','+'):
985 case opid3('S','-','-'):
987 if (exprs[0]->vtype != TYPE_FLOAT) {
988 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
989 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
992 if (op->id == opid3('S','+','+')) {
999 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
1000 if (ast_istype(exprs[0], ast_entfield)) {
1001 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1003 (ast_expression*)parser->fold->imm_float[1]);
1005 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1007 (ast_expression*)parser->fold->imm_float[1]);
1011 out = fold_binary(ctx, subop,
1013 (ast_expression*)parser->fold->imm_float[1]);
1016 case opid2('+','='):
1017 case opid2('-','='):
1018 if (exprs[0]->vtype != exprs[1]->vtype ||
1019 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1021 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1022 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1023 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1027 (void)check_write_to(ctx, exprs[0]);
1028 if (ast_istype(exprs[0], ast_entfield))
1029 assignop = type_storep_instr[exprs[0]->vtype];
1031 assignop = type_store_instr[exprs[0]->vtype];
1032 switch (exprs[0]->vtype) {
1034 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1035 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1036 exprs[0], exprs[1]);
1039 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1040 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1041 exprs[0], exprs[1]);
1044 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1045 type_name[exprs[0]->vtype],
1046 type_name[exprs[1]->vtype]);
1050 case opid2('*','='):
1051 case opid2('/','='):
1052 if (exprs[1]->vtype != TYPE_FLOAT ||
1053 !(exprs[0]->vtype == TYPE_FLOAT ||
1054 exprs[0]->vtype == TYPE_VECTOR))
1056 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1057 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1058 compile_error(ctx, "invalid types used in expression: %s and %s",
1062 (void)check_write_to(ctx, exprs[0]);
1063 if (ast_istype(exprs[0], ast_entfield))
1064 assignop = type_storep_instr[exprs[0]->vtype];
1066 assignop = type_store_instr[exprs[0]->vtype];
1067 switch (exprs[0]->vtype) {
1069 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1070 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1071 exprs[0], exprs[1]);
1074 if (op->id == opid2('*','=')) {
1075 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1076 exprs[0], exprs[1]);
1078 out = fold_binary(ctx, INSTR_DIV_F,
1079 (ast_expression*)parser->fold->imm_float[1],
1082 compile_error(ctx, "internal error: failed to generate division");
1085 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1090 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1091 type_name[exprs[0]->vtype],
1092 type_name[exprs[1]->vtype]);
1096 case opid2('&','='):
1097 case opid2('|','='):
1098 case opid2('^','='):
1099 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1100 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1101 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1102 compile_error(ctx, "invalid types used in expression: %s and %s",
1106 (void)check_write_to(ctx, exprs[0]);
1107 if (ast_istype(exprs[0], ast_entfield))
1108 assignop = type_storep_instr[exprs[0]->vtype];
1110 assignop = type_store_instr[exprs[0]->vtype];
1111 if (exprs[0]->vtype == TYPE_FLOAT)
1112 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1113 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1114 exprs[0], exprs[1]);
1116 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1117 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1118 exprs[0], exprs[1]);
1120 case opid3('&','~','='):
1121 /* This is like: a &= ~(b);
1122 * But QC has no bitwise-not, so we implement it as
1125 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1126 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128 compile_error(ctx, "invalid types used in expression: %s and %s",
1132 if (ast_istype(exprs[0], ast_entfield))
1133 assignop = type_storep_instr[exprs[0]->vtype];
1135 assignop = type_store_instr[exprs[0]->vtype];
1136 if (exprs[0]->vtype == TYPE_FLOAT)
1137 out = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1139 out = fold_binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1142 (void)check_write_to(ctx, exprs[0]);
1143 if (exprs[0]->vtype == TYPE_FLOAT)
1144 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1146 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1147 asbinstore->keep_dest = true;
1148 out = (ast_expression*)asbinstore;
1151 case opid3('l', 'e', 'n'):
1152 if (exprs[0]->vtype != TYPE_STRING && exprs[0]->vtype != TYPE_ARRAY) {
1153 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1154 compile_error(ast_ctx(exprs[0]), "invalid type for length operator: %s", ty1);
1157 /* strings must be const, arrays are statically sized */
1158 if (exprs[0]->vtype == TYPE_STRING &&
1159 !(((ast_value*)exprs[0])->hasvalue && ((ast_value*)exprs[0])->cvq == CV_CONST))
1161 compile_error(ast_ctx(exprs[0]), "operand of length operator not a valid constant expression");
1164 out = fold_op(parser->fold, op, exprs);
1167 case opid2('~', 'P'):
1168 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1169 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1170 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1173 if (!(out = fold_op(parser->fold, op, exprs))) {
1174 if (exprs[0]->vtype == TYPE_FLOAT) {
1175 out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1177 out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1184 compile_error(ctx, "failed to apply operator %s", op->op);
1188 vec_push(sy->out, syexp(ctx, out));
1192 static bool parser_close_call(parser_t *parser, shunt *sy)
1194 /* was a function call */
1195 ast_expression *fun;
1196 ast_value *funval = NULL;
1200 size_t paramcount, i;
1203 fid = vec_last(sy->ops).off;
1204 vec_shrinkby(sy->ops, 1);
1206 /* out[fid] is the function
1207 * everything above is parameters...
1209 if (!vec_size(sy->argc)) {
1210 parseerror(parser, "internal error: no argument counter available");
1214 paramcount = vec_last(sy->argc);
1217 if (vec_size(sy->out) < fid) {
1218 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1219 (unsigned long)vec_size(sy->out),
1221 (unsigned long)paramcount);
1226 * TODO handle this at the intrinsic level with an ast_intrinsic
1229 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1231 if (fid+2 != vec_size(sy->out) ||
1232 vec_last(sy->out).block)
1234 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1237 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1238 ast_unref(vec_last(sy->out).out);
1239 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1240 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1241 vec_shrinkby(sy->out, 1);
1246 * Now we need to determine if the function that is being called is
1247 * an intrinsic so we can evaluate if the arguments to it are constant
1248 * and than fruitfully fold them.
1250 #define fold_can_1(X) \
1251 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1252 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1254 if (fid + 1 < vec_size(sy->out))
1257 for (i = 0; i < paramcount; ++i) {
1258 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1265 * All is well which ends well, if we make it into here we can ignore the
1266 * intrinsic call and just evaluate it i.e constant fold it.
1268 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1269 ast_expression **exprs = NULL;
1270 ast_expression *foldval = NULL;
1272 for (i = 0; i < paramcount; i++)
1273 vec_push(exprs, sy->out[fid+1 + i].out);
1275 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1281 * Blub: what sorts of unreffing and resizing of
1282 * sy->out should I be doing here?
1284 sy->out[fid] = syexp(foldval->node.context, foldval);
1285 vec_shrinkby(sy->out, paramcount);
1292 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1297 if (fid+1 + paramcount != vec_size(sy->out)) {
1298 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1299 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1303 for (i = 0; i < paramcount; ++i)
1304 vec_push(call->params, sy->out[fid+1 + i].out);
1305 vec_shrinkby(sy->out, paramcount);
1306 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1307 if (parser->max_param_count < paramcount)
1308 parser->max_param_count = paramcount;
1310 if (ast_istype(fun, ast_value)) {
1311 funval = (ast_value*)fun;
1312 if ((fun->flags & AST_FLAG_VARIADIC) &&
1313 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1315 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount, false);
1319 /* overwrite fid, the function, with a call */
1320 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1322 if (fun->vtype != TYPE_FUNCTION) {
1323 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1328 parseerror(parser, "could not determine function return type");
1331 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1333 if (fun->flags & AST_FLAG_DEPRECATED) {
1335 return !parsewarning(parser, WARN_DEPRECATED,
1336 "call to function (which is marked deprecated)\n",
1337 "-> it has been declared here: %s:%i",
1338 ast_ctx(fun).file, ast_ctx(fun).line);
1341 return !parsewarning(parser, WARN_DEPRECATED,
1342 "call to `%s` (which is marked deprecated)\n"
1343 "-> `%s` declared here: %s:%i",
1344 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1346 return !parsewarning(parser, WARN_DEPRECATED,
1347 "call to `%s` (deprecated: %s)\n"
1348 "-> `%s` declared here: %s:%i",
1349 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1353 if (vec_size(fun->params) != paramcount &&
1354 !((fun->flags & AST_FLAG_VARIADIC) &&
1355 vec_size(fun->params) < paramcount))
1357 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1359 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1360 "too %s parameters for call to %s: expected %i, got %i\n"
1361 " -> `%s` has been declared here: %s:%i",
1362 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1363 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1365 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1366 "too %s parameters for function call: expected %i, got %i\n"
1367 " -> it has been declared here: %s:%i",
1368 fewmany, (int)vec_size(fun->params), (int)paramcount,
1369 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1376 static bool parser_close_paren(parser_t *parser, shunt *sy)
1378 if (!vec_size(sy->ops)) {
1379 parseerror(parser, "unmatched closing paren");
1383 while (vec_size(sy->ops)) {
1384 if (vec_last(sy->ops).isparen) {
1385 if (vec_last(sy->paren) == PAREN_FUNC) {
1387 if (!parser_close_call(parser, sy))
1391 if (vec_last(sy->paren) == PAREN_EXPR) {
1393 if (!vec_size(sy->out)) {
1394 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1395 vec_shrinkby(sy->ops, 1);
1398 vec_shrinkby(sy->ops, 1);
1401 if (vec_last(sy->paren) == PAREN_INDEX) {
1403 /* pop off the parenthesis */
1404 vec_shrinkby(sy->ops, 1);
1405 /* then apply the index operator */
1406 if (!parser_sy_apply_operator(parser, sy))
1410 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1411 vec_last(sy->paren) = PAREN_TERNARY2;
1412 /* pop off the parenthesis */
1413 vec_shrinkby(sy->ops, 1);
1416 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1419 if (!parser_sy_apply_operator(parser, sy))
1425 static void parser_reclassify_token(parser_t *parser)
1428 if (parser->tok >= TOKEN_START)
1430 for (i = 0; i < operator_count; ++i) {
1431 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1432 parser->tok = TOKEN_OPERATOR;
1438 static ast_expression* parse_vararg_do(parser_t *parser)
1440 ast_expression *idx, *out;
1442 ast_value *funtype = parser->function->vtype;
1443 lex_ctx_t ctx = parser_ctx(parser);
1445 if (!parser->function->varargs) {
1446 parseerror(parser, "function has no variable argument list");
1450 if (!parser_next(parser) || parser->tok != '(') {
1451 parseerror(parser, "expected parameter index and type in parenthesis");
1454 if (!parser_next(parser)) {
1455 parseerror(parser, "error parsing parameter index");
1459 idx = parse_expression_leave(parser, true, false, false);
1463 if (parser->tok != ',') {
1464 if (parser->tok != ')') {
1466 parseerror(parser, "expected comma after parameter index");
1469 /* vararg piping: ...(start) */
1470 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1474 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1476 parseerror(parser, "expected typename for vararg");
1480 typevar = parse_typename(parser, NULL, NULL, NULL);
1486 if (parser->tok != ')') {
1488 ast_delete(typevar);
1489 parseerror(parser, "expected closing paren");
1493 if (funtype->expression.varparam &&
1494 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1498 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1499 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1500 compile_error(ast_ctx(typevar),
1501 "function was declared to take varargs of type `%s`, requested type is: %s",
1505 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1506 ast_type_adopt(out, typevar);
1507 ast_delete(typevar);
1511 static ast_expression* parse_vararg(parser_t *parser)
1513 bool old_noops = parser->lex->flags.noops;
1515 ast_expression *out;
1517 parser->lex->flags.noops = true;
1518 out = parse_vararg_do(parser);
1520 parser->lex->flags.noops = old_noops;
1524 /* not to be exposed */
1525 bool ftepp_predef_exists(const char *name);
1526 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1528 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1529 parser->tok == TOKEN_IDENT &&
1530 !strcmp(parser_tokval(parser), "_"))
1532 /* a translatable string */
1535 parser->lex->flags.noops = true;
1536 if (!parser_next(parser) || parser->tok != '(') {
1537 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1540 parser->lex->flags.noops = false;
1541 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1542 parseerror(parser, "expected a constant string in translatable-string extension");
1545 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1548 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1550 if (!parser_next(parser) || parser->tok != ')') {
1551 parseerror(parser, "expected closing paren after translatable string");
1556 else if (parser->tok == TOKEN_DOTS)
1559 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1560 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1563 va = parse_vararg(parser);
1566 vec_push(sy->out, syexp(parser_ctx(parser), va));
1569 else if (parser->tok == TOKEN_FLOATCONST) {
1570 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f), false);
1573 vec_push(sy->out, syexp(parser_ctx(parser), val));
1576 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1577 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i), false);
1580 vec_push(sy->out, syexp(parser_ctx(parser), val));
1583 else if (parser->tok == TOKEN_STRINGCONST) {
1584 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1587 vec_push(sy->out, syexp(parser_ctx(parser), val));
1590 else if (parser->tok == TOKEN_VECTORCONST) {
1591 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1594 vec_push(sy->out, syexp(parser_ctx(parser), val));
1597 else if (parser->tok == TOKEN_IDENT)
1599 const char *ctoken = parser_tokval(parser);
1600 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1601 ast_expression *var;
1602 /* a_vector.{x,y,z} */
1603 if (!vec_size(sy->ops) ||
1604 !vec_last(sy->ops).etype ||
1605 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1607 /* When adding more intrinsics, fix the above condition */
1610 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1612 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1614 var = parser_find_var(parser, parser_tokval(parser));
1616 var = parser_find_field(parser, parser_tokval(parser));
1618 if (!var && with_labels) {
1619 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1621 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1622 var = (ast_expression*)lbl;
1623 vec_push(parser->labels, lbl);
1626 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1627 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1630 * now we try for the real intrinsic hashtable. If the string
1631 * begins with __builtin, we simply skip past it, otherwise we
1632 * use the identifier as is.
1634 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1635 var = intrin_func(parser->intrin, parser_tokval(parser));
1639 * Try it again, intrin_func deals with the alias method as well
1640 * the first one masks for __builtin though, we emit warning here.
1643 if ((var = intrin_func(parser->intrin, parser_tokval(parser)))) {
1644 (void)!compile_warning(
1647 "using implicitly defined builtin `__builtin_%s' for `%s'",
1648 parser_tokval(parser),
1649 parser_tokval(parser)
1656 char *correct = NULL;
1660 * sometimes people use preprocessing predefs without enabling them
1661 * i've done this thousands of times already myself. Lets check for
1662 * it in the predef table. And diagnose it better :)
1664 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1665 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1670 * TODO: determine the best score for the identifier: be it
1671 * a variable, a field.
1673 * We should also consider adding correction tables for
1674 * other things as well.
1676 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1678 correct_init(&corr);
1680 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1681 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1682 if (strcmp(correct, parser_tokval(parser))) {
1689 correct_free(&corr);
1692 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1697 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1703 if (ast_istype(var, ast_value)) {
1704 ((ast_value*)var)->uses++;
1706 else if (ast_istype(var, ast_member)) {
1707 ast_member *mem = (ast_member*)var;
1708 if (ast_istype(mem->owner, ast_value))
1709 ((ast_value*)(mem->owner))->uses++;
1712 vec_push(sy->out, syexp(parser_ctx(parser), var));
1715 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1719 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1721 ast_expression *expr = NULL;
1724 bool wantop = false;
1725 /* only warn once about an assignment in a truth value because the current code
1726 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1728 bool warn_parenthesis = true;
1730 /* count the parens because an if starts with one, so the
1731 * end of a condition is an unmatched closing paren
1735 memset(&sy, 0, sizeof(sy));
1737 parser->lex->flags.noops = false;
1739 parser_reclassify_token(parser);
1743 if (parser->tok == TOKEN_TYPENAME) {
1744 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1748 if (parser->tok == TOKEN_OPERATOR)
1750 /* classify the operator */
1751 const oper_info *op;
1752 const oper_info *olast = NULL;
1754 for (o = 0; o < operator_count; ++o) {
1755 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1756 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1757 !strcmp(parser_tokval(parser), operators[o].op))
1762 if (o == operator_count) {
1763 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1766 /* found an operator */
1769 /* when declaring variables, a comma starts a new variable */
1770 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1771 /* fixup the token */
1776 /* a colon without a pervious question mark cannot be a ternary */
1777 if (!ternaries && op->id == opid2(':','?')) {
1782 if (op->id == opid1(',')) {
1783 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1784 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1788 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1789 olast = &operators[vec_last(sy.ops).etype-1];
1791 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1792 while (olast && op->prec < olast->prec)
1794 if (!parser_sy_apply_operator(parser, &sy))
1796 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1797 olast = &operators[vec_last(sy.ops).etype-1];
1802 #define IsAssignOp(x) (\
1803 (x) == opid1('=') || \
1804 (x) == opid2('+','=') || \
1805 (x) == opid2('-','=') || \
1806 (x) == opid2('*','=') || \
1807 (x) == opid2('/','=') || \
1808 (x) == opid2('%','=') || \
1809 (x) == opid2('&','=') || \
1810 (x) == opid2('|','=') || \
1811 (x) == opid3('&','~','=') \
1813 if (warn_parenthesis) {
1814 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1815 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1816 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1819 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1820 warn_parenthesis = false;
1823 if (olast && olast->id != op->id) {
1824 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1825 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1827 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1828 warn_parenthesis = false;
1830 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1831 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1833 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1834 warn_parenthesis = false;
1840 (op->prec < olast->prec) ||
1841 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1843 if (!parser_sy_apply_operator(parser, &sy))
1845 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1846 olast = &operators[vec_last(sy.ops).etype-1];
1851 if (op->id == opid1('(')) {
1853 size_t sycount = vec_size(sy.out);
1854 /* we expected an operator, this is the function-call operator */
1855 vec_push(sy.paren, PAREN_FUNC);
1856 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1857 vec_push(sy.argc, 0);
1859 vec_push(sy.paren, PAREN_EXPR);
1860 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1863 } else if (op->id == opid1('[')) {
1865 parseerror(parser, "unexpected array subscript");
1868 vec_push(sy.paren, PAREN_INDEX);
1869 /* push both the operator and the paren, this makes life easier */
1870 vec_push(sy.ops, syop(parser_ctx(parser), op));
1871 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1873 } else if (op->id == opid2('?',':')) {
1874 vec_push(sy.ops, syop(parser_ctx(parser), op));
1875 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1878 vec_push(sy.paren, PAREN_TERNARY1);
1879 } else if (op->id == opid2(':','?')) {
1880 if (!vec_size(sy.paren)) {
1881 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1884 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1885 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1888 if (!parser_close_paren(parser, &sy))
1890 vec_push(sy.ops, syop(parser_ctx(parser), op));
1894 vec_push(sy.ops, syop(parser_ctx(parser), op));
1895 wantop = !!(op->flags & OP_SUFFIX);
1898 else if (parser->tok == ')') {
1899 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1900 if (!parser_sy_apply_operator(parser, &sy))
1903 if (!vec_size(sy.paren))
1906 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1907 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1910 if (!parser_close_paren(parser, &sy))
1913 /* must be a function call without parameters */
1914 if (vec_last(sy.paren) != PAREN_FUNC) {
1915 parseerror(parser, "closing paren in invalid position");
1918 if (!parser_close_paren(parser, &sy))
1923 else if (parser->tok == '(') {
1924 parseerror(parser, "internal error: '(' should be classified as operator");
1927 else if (parser->tok == '[') {
1928 parseerror(parser, "internal error: '[' should be classified as operator");
1931 else if (parser->tok == ']') {
1932 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1933 if (!parser_sy_apply_operator(parser, &sy))
1936 if (!vec_size(sy.paren))
1938 if (vec_last(sy.paren) != PAREN_INDEX) {
1939 parseerror(parser, "mismatched parentheses, unexpected ']'");
1942 if (!parser_close_paren(parser, &sy))
1947 if (!parse_sya_operand(parser, &sy, with_labels))
1950 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1951 vec_last(sy.argc)++;
1956 /* in this case we might want to allow constant string concatenation */
1957 bool concatenated = false;
1958 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1959 ast_expression *lexpr = vec_last(sy.out).out;
1960 if (ast_istype(lexpr, ast_value)) {
1961 ast_value *last = (ast_value*)lexpr;
1962 if (last->isimm == true && last->cvq == CV_CONST &&
1963 last->hasvalue && last->expression.vtype == TYPE_STRING)
1965 char *newstr = NULL;
1966 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1967 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1969 concatenated = true;
1973 if (!concatenated) {
1974 parseerror(parser, "expected operator or end of statement");
1979 if (!parser_next(parser)) {
1982 if (parser->tok == ';' ||
1983 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1984 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1990 while (vec_size(sy.ops)) {
1991 if (!parser_sy_apply_operator(parser, &sy))
1995 parser->lex->flags.noops = true;
1996 if (vec_size(sy.out) != 1) {
1997 parseerror(parser, "expression expected");
2000 expr = sy.out[0].out;
2003 if (vec_size(sy.paren)) {
2004 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2012 parser->lex->flags.noops = true;
2013 for (i = 0; i < vec_size(sy.out); ++i) {
2015 ast_unref(sy.out[i].out);
2024 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2026 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2029 if (parser->tok != ';') {
2030 parseerror(parser, "semicolon expected after expression");
2034 if (!parser_next(parser)) {
2041 static void parser_enterblock(parser_t *parser)
2043 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2044 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2045 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2046 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2047 vec_push(parser->_block_ctx, parser_ctx(parser));
2050 vec_push(parser->correct_variables, correct_trie_new());
2051 vec_push(parser->correct_variables_score, NULL);
2054 static bool parser_leaveblock(parser_t *parser)
2057 size_t locals, typedefs;
2059 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2060 parseerror(parser, "internal error: parser_leaveblock with no block");
2064 util_htdel(vec_last(parser->variables));
2065 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2067 vec_pop(parser->variables);
2068 vec_pop(parser->correct_variables);
2069 vec_pop(parser->correct_variables_score);
2070 if (!vec_size(parser->_blocklocals)) {
2071 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2075 locals = vec_last(parser->_blocklocals);
2076 vec_pop(parser->_blocklocals);
2077 while (vec_size(parser->_locals) != locals) {
2078 ast_expression *e = vec_last(parser->_locals);
2079 ast_value *v = (ast_value*)e;
2080 vec_pop(parser->_locals);
2081 if (ast_istype(e, ast_value) && !v->uses) {
2082 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2087 typedefs = vec_last(parser->_blocktypedefs);
2088 while (vec_size(parser->_typedefs) != typedefs) {
2089 ast_delete(vec_last(parser->_typedefs));
2090 vec_pop(parser->_typedefs);
2092 util_htdel(vec_last(parser->typedefs));
2093 vec_pop(parser->typedefs);
2095 vec_pop(parser->_block_ctx);
2100 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2102 vec_push(parser->_locals, e);
2103 util_htset(vec_last(parser->variables), name, (void*)e);
2107 vec_last(parser->correct_variables),
2108 &vec_last(parser->correct_variables_score),
2113 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2115 vec_push(parser->globals, e);
2116 util_htset(parser->htglobals, name, e);
2120 parser->correct_variables[0],
2121 &parser->correct_variables_score[0],
2126 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2130 ast_expression *prev;
2132 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2134 ast_type_to_string(cond, ty, sizeof(ty));
2135 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2138 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2141 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2144 parseerror(parser, "internal error: failed to process condition");
2149 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2151 /* vector types need to be cast to true booleans */
2152 ast_binary *bin = (ast_binary*)cond;
2153 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2155 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2157 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2160 parseerror(parser, "internal error: failed to process condition");
2167 unary = (ast_unary*)cond;
2168 /* ast_istype dereferences cond, should test here for safety */
2169 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2171 cond = unary->operand;
2172 unary->operand = NULL;
2175 unary = (ast_unary*)cond;
2179 parseerror(parser, "internal error: failed to process condition");
2181 if (ifnot) *_ifnot = !*_ifnot;
2185 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2188 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2191 lex_ctx_t ctx = parser_ctx(parser);
2193 (void)block; /* not touching */
2195 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2196 if (!parser_next(parser)) {
2197 parseerror(parser, "expected condition or 'not'");
2200 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2202 if (!parser_next(parser)) {
2203 parseerror(parser, "expected condition in parenthesis");
2207 if (parser->tok != '(') {
2208 parseerror(parser, "expected 'if' condition in parenthesis");
2211 /* parse into the expression */
2212 if (!parser_next(parser)) {
2213 parseerror(parser, "expected 'if' condition after opening paren");
2216 /* parse the condition */
2217 cond = parse_expression_leave(parser, false, true, false);
2221 if (parser->tok != ')') {
2222 parseerror(parser, "expected closing paren after 'if' condition");
2226 /* parse into the 'then' branch */
2227 if (!parser_next(parser)) {
2228 parseerror(parser, "expected statement for on-true branch of 'if'");
2232 if (!parse_statement_or_block(parser, &ontrue)) {
2237 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2238 /* check for an else */
2239 if (!strcmp(parser_tokval(parser), "else")) {
2240 /* parse into the 'else' branch */
2241 if (!parser_next(parser)) {
2242 parseerror(parser, "expected on-false branch after 'else'");
2247 if (!parse_statement_or_block(parser, &onfalse)) {
2254 cond = process_condition(parser, cond, &ifnot);
2256 if (ontrue) ast_delete(ontrue);
2257 if (onfalse) ast_delete(onfalse);
2262 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2264 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2265 *out = (ast_expression*)ifthen;
2269 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2270 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2275 /* skip the 'while' and get the body */
2276 if (!parser_next(parser)) {
2277 if (OPTS_FLAG(LOOP_LABELS))
2278 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2280 parseerror(parser, "expected 'while' condition in parenthesis");
2284 if (parser->tok == ':') {
2285 if (!OPTS_FLAG(LOOP_LABELS))
2286 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2287 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2288 parseerror(parser, "expected loop label");
2291 label = util_strdup(parser_tokval(parser));
2292 if (!parser_next(parser)) {
2294 parseerror(parser, "expected 'while' condition in parenthesis");
2299 if (parser->tok != '(') {
2300 parseerror(parser, "expected 'while' condition in parenthesis");
2304 vec_push(parser->breaks, label);
2305 vec_push(parser->continues, label);
2307 rv = parse_while_go(parser, block, out);
2310 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2311 parseerror(parser, "internal error: label stack corrupted");
2317 vec_pop(parser->breaks);
2318 vec_pop(parser->continues);
2323 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2326 ast_expression *cond, *ontrue;
2330 lex_ctx_t ctx = parser_ctx(parser);
2332 (void)block; /* not touching */
2334 /* parse into the expression */
2335 if (!parser_next(parser)) {
2336 parseerror(parser, "expected 'while' condition after opening paren");
2339 /* parse the condition */
2340 cond = parse_expression_leave(parser, false, true, false);
2344 if (parser->tok != ')') {
2345 parseerror(parser, "expected closing paren after 'while' condition");
2349 /* parse into the 'then' branch */
2350 if (!parser_next(parser)) {
2351 parseerror(parser, "expected while-loop body");
2355 if (!parse_statement_or_block(parser, &ontrue)) {
2360 cond = process_condition(parser, cond, &ifnot);
2365 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2366 *out = (ast_expression*)aloop;
2370 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2371 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2376 /* skip the 'do' and get the body */
2377 if (!parser_next(parser)) {
2378 if (OPTS_FLAG(LOOP_LABELS))
2379 parseerror(parser, "expected loop label or body");
2381 parseerror(parser, "expected loop body");
2385 if (parser->tok == ':') {
2386 if (!OPTS_FLAG(LOOP_LABELS))
2387 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2388 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2389 parseerror(parser, "expected loop label");
2392 label = util_strdup(parser_tokval(parser));
2393 if (!parser_next(parser)) {
2395 parseerror(parser, "expected loop body");
2400 vec_push(parser->breaks, label);
2401 vec_push(parser->continues, label);
2403 rv = parse_dowhile_go(parser, block, out);
2406 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2407 parseerror(parser, "internal error: label stack corrupted");
2410 * Test for NULL otherwise ast_delete dereferences null pointer
2418 vec_pop(parser->breaks);
2419 vec_pop(parser->continues);
2424 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2427 ast_expression *cond, *ontrue;
2431 lex_ctx_t ctx = parser_ctx(parser);
2433 (void)block; /* not touching */
2435 if (!parse_statement_or_block(parser, &ontrue))
2438 /* expect the "while" */
2439 if (parser->tok != TOKEN_KEYWORD ||
2440 strcmp(parser_tokval(parser), "while"))
2442 parseerror(parser, "expected 'while' and condition");
2447 /* skip the 'while' and check for opening paren */
2448 if (!parser_next(parser) || parser->tok != '(') {
2449 parseerror(parser, "expected 'while' condition in parenthesis");
2453 /* parse into the expression */
2454 if (!parser_next(parser)) {
2455 parseerror(parser, "expected 'while' condition after opening paren");
2459 /* parse the condition */
2460 cond = parse_expression_leave(parser, false, true, false);
2464 if (parser->tok != ')') {
2465 parseerror(parser, "expected closing paren after 'while' condition");
2471 if (!parser_next(parser) || parser->tok != ';') {
2472 parseerror(parser, "expected semicolon after condition");
2478 if (!parser_next(parser)) {
2479 parseerror(parser, "parse error");
2485 cond = process_condition(parser, cond, &ifnot);
2490 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2491 *out = (ast_expression*)aloop;
2495 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2496 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2501 /* skip the 'for' and check for opening paren */
2502 if (!parser_next(parser)) {
2503 if (OPTS_FLAG(LOOP_LABELS))
2504 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2506 parseerror(parser, "expected 'for' expressions in parenthesis");
2510 if (parser->tok == ':') {
2511 if (!OPTS_FLAG(LOOP_LABELS))
2512 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2513 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2514 parseerror(parser, "expected loop label");
2517 label = util_strdup(parser_tokval(parser));
2518 if (!parser_next(parser)) {
2520 parseerror(parser, "expected 'for' expressions in parenthesis");
2525 if (parser->tok != '(') {
2526 parseerror(parser, "expected 'for' expressions in parenthesis");
2530 vec_push(parser->breaks, label);
2531 vec_push(parser->continues, label);
2533 rv = parse_for_go(parser, block, out);
2536 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2537 parseerror(parser, "internal error: label stack corrupted");
2543 vec_pop(parser->breaks);
2544 vec_pop(parser->continues);
2548 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2551 ast_expression *initexpr, *cond, *increment, *ontrue;
2556 lex_ctx_t ctx = parser_ctx(parser);
2558 parser_enterblock(parser);
2565 /* parse into the expression */
2566 if (!parser_next(parser)) {
2567 parseerror(parser, "expected 'for' initializer after opening paren");
2572 if (parser->tok == TOKEN_IDENT)
2573 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2575 if (typevar || parser->tok == TOKEN_TYPENAME) {
2577 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2578 if (parsewarning(parser, WARN_EXTENSIONS,
2579 "current standard does not allow variable declarations in for-loop initializers"))
2583 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2586 else if (parser->tok != ';')
2588 initexpr = parse_expression_leave(parser, false, false, false);
2593 /* move on to condition */
2594 if (parser->tok != ';') {
2595 parseerror(parser, "expected semicolon after for-loop initializer");
2598 if (!parser_next(parser)) {
2599 parseerror(parser, "expected for-loop condition");
2603 /* parse the condition */
2604 if (parser->tok != ';') {
2605 cond = parse_expression_leave(parser, false, true, false);
2610 /* move on to incrementor */
2611 if (parser->tok != ';') {
2612 parseerror(parser, "expected semicolon after for-loop initializer");
2615 if (!parser_next(parser)) {
2616 parseerror(parser, "expected for-loop condition");
2620 /* parse the incrementor */
2621 if (parser->tok != ')') {
2622 lex_ctx_t condctx = parser_ctx(parser);
2623 increment = parse_expression_leave(parser, false, false, false);
2626 if (!ast_side_effects(increment)) {
2627 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2633 if (parser->tok != ')') {
2634 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2637 /* parse into the 'then' branch */
2638 if (!parser_next(parser)) {
2639 parseerror(parser, "expected for-loop body");
2642 if (!parse_statement_or_block(parser, &ontrue))
2646 cond = process_condition(parser, cond, &ifnot);
2650 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2651 *out = (ast_expression*)aloop;
2653 if (!parser_leaveblock(parser)) {
2659 if (initexpr) ast_unref(initexpr);
2660 if (cond) ast_unref(cond);
2661 if (increment) ast_unref(increment);
2662 (void)!parser_leaveblock(parser);
2666 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2668 ast_expression *exp = NULL;
2669 ast_expression *var = NULL;
2670 ast_return *ret = NULL;
2671 ast_value *retval = parser->function->return_value;
2672 ast_value *expected = parser->function->vtype;
2674 lex_ctx_t ctx = parser_ctx(parser);
2676 (void)block; /* not touching */
2678 if (!parser_next(parser)) {
2679 parseerror(parser, "expected return expression");
2683 /* return assignments */
2684 if (parser->tok == '=') {
2685 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2686 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2690 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2692 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2693 parseerror(parser, "invalid return type: `%s'", ty1);
2697 if (!parser_next(parser)) {
2698 parseerror(parser, "expected return assignment expression");
2702 if (!(exp = parse_expression_leave(parser, false, false, false)))
2705 /* prepare the return value */
2707 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2708 ast_type_adopt(retval, expected->expression.next);
2709 parser->function->return_value = retval;
2712 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2713 char ty1[1024], ty2[1024];
2714 ast_type_to_string(exp, ty1, sizeof(ty1));
2715 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2716 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2719 /* store to 'return' local variable */
2720 var = (ast_expression*)ast_store_new(
2722 type_store_instr[expected->expression.next->vtype],
2723 (ast_expression*)retval, exp);
2730 if (parser->tok != ';')
2731 parseerror(parser, "missing semicolon after return assignment");
2732 else if (!parser_next(parser))
2733 parseerror(parser, "parse error after return assignment");
2739 if (parser->tok != ';') {
2740 exp = parse_expression(parser, false, false);
2744 if (exp->vtype != TYPE_NIL &&
2745 exp->vtype != ((ast_expression*)expected)->next->vtype)
2747 parseerror(parser, "return with invalid expression");
2750 ret = ast_return_new(ctx, exp);
2756 if (!parser_next(parser))
2757 parseerror(parser, "parse error");
2759 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2761 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2763 ret = ast_return_new(ctx, (ast_expression*)retval);
2765 *out = (ast_expression*)ret;
2769 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2772 unsigned int levels = 0;
2773 lex_ctx_t ctx = parser_ctx(parser);
2774 const char **loops = (is_continue ? parser->continues : parser->breaks);
2776 (void)block; /* not touching */
2777 if (!parser_next(parser)) {
2778 parseerror(parser, "expected semicolon or loop label");
2782 if (!vec_size(loops)) {
2784 parseerror(parser, "`continue` can only be used inside loops");
2786 parseerror(parser, "`break` can only be used inside loops or switches");
2789 if (parser->tok == TOKEN_IDENT) {
2790 if (!OPTS_FLAG(LOOP_LABELS))
2791 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2792 i = vec_size(loops);
2794 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2797 parseerror(parser, "no such loop to %s: `%s`",
2798 (is_continue ? "continue" : "break out of"),
2799 parser_tokval(parser));
2804 if (!parser_next(parser)) {
2805 parseerror(parser, "expected semicolon");
2810 if (parser->tok != ';') {
2811 parseerror(parser, "expected semicolon");
2815 if (!parser_next(parser))
2816 parseerror(parser, "parse error");
2818 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2822 /* returns true when it was a variable qualifier, false otherwise!
2823 * on error, cvq is set to CV_WRONG
2830 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2832 bool had_const = false;
2833 bool had_var = false;
2834 bool had_noref = false;
2835 bool had_attrib = false;
2836 bool had_static = false;
2839 static attribute_t attributes[] = {
2840 { "noreturn", AST_FLAG_NORETURN },
2841 { "inline", AST_FLAG_INLINE },
2842 { "eraseable", AST_FLAG_ERASEABLE },
2843 { "accumulate", AST_FLAG_ACCUMULATE },
2844 { "last", AST_FLAG_FINAL_DECL }
2851 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2853 /* parse an attribute */
2854 if (!parser_next(parser)) {
2855 parseerror(parser, "expected attribute after `[[`");
2860 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2861 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2862 flags |= attributes[i].flag;
2863 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2864 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2865 attributes[i].name);
2873 if (i != GMQCC_ARRAY_COUNT(attributes))
2877 if (!strcmp(parser_tokval(parser), "noref")) {
2879 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2880 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2885 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2886 flags |= AST_FLAG_ALIAS;
2889 if (!parser_next(parser)) {
2890 parseerror(parser, "parse error in attribute");
2894 if (parser->tok == '(') {
2895 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2896 parseerror(parser, "`alias` attribute missing parameter");
2900 *message = util_strdup(parser_tokval(parser));
2902 if (!parser_next(parser)) {
2903 parseerror(parser, "parse error in attribute");
2907 if (parser->tok != ')') {
2908 parseerror(parser, "`alias` attribute expected `)` after parameter");
2912 if (!parser_next(parser)) {
2913 parseerror(parser, "parse error in attribute");
2918 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2919 parseerror(parser, "`alias` attribute expected `]]`");
2923 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2924 flags |= AST_FLAG_DEPRECATED;
2927 if (!parser_next(parser)) {
2928 parseerror(parser, "parse error in attribute");
2932 if (parser->tok == '(') {
2933 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2934 parseerror(parser, "`deprecated` attribute missing parameter");
2938 *message = util_strdup(parser_tokval(parser));
2940 if (!parser_next(parser)) {
2941 parseerror(parser, "parse error in attribute");
2945 if(parser->tok != ')') {
2946 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2950 if (!parser_next(parser)) {
2951 parseerror(parser, "parse error in attribute");
2956 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2957 parseerror(parser, "`deprecated` attribute expected `]]`");
2960 if (*message) mem_d(*message);
2966 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2967 flags |= AST_FLAG_COVERAGE;
2968 if (!parser_next(parser)) {
2970 parseerror(parser, "parse error in coverage attribute");
2974 if (parser->tok == '(') {
2975 if (!parser_next(parser)) {
2977 parseerror(parser, "invalid parameter for coverage() attribute\n"
2978 "valid are: block");
2982 if (parser->tok != ')') {
2984 if (parser->tok != TOKEN_IDENT)
2985 goto bad_coverage_arg;
2986 if (!strcmp(parser_tokval(parser), "block"))
2987 flags |= AST_FLAG_BLOCK_COVERAGE;
2988 else if (!strcmp(parser_tokval(parser), "none"))
2989 flags &= ~(AST_FLAG_COVERAGE_MASK);
2991 goto bad_coverage_arg;
2992 if (!parser_next(parser))
2993 goto error_in_coverage;
2994 if (parser->tok == ',') {
2995 if (!parser_next(parser))
2996 goto error_in_coverage;
2998 } while (parser->tok != ')');
3000 if (parser->tok != ')' || !parser_next(parser))
3001 goto error_in_coverage;
3003 /* without parameter [[coverage]] equals [[coverage(block)]] */
3004 flags |= AST_FLAG_BLOCK_COVERAGE;
3009 /* Skip tokens until we hit a ]] */
3010 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3011 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3012 if (!parser_next(parser)) {
3013 parseerror(parser, "error inside attribute");
3020 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3022 else if (!strcmp(parser_tokval(parser), "const"))
3024 else if (!strcmp(parser_tokval(parser), "var"))
3026 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3028 else if (!strcmp(parser_tokval(parser), "noref"))
3030 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3037 if (!parser_next(parser))
3047 *is_static = had_static;
3051 parseerror(parser, "parse error after variable qualifier");
3056 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3057 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3062 /* skip the 'while' and get the body */
3063 if (!parser_next(parser)) {
3064 if (OPTS_FLAG(LOOP_LABELS))
3065 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3067 parseerror(parser, "expected 'switch' operand in parenthesis");
3071 if (parser->tok == ':') {
3072 if (!OPTS_FLAG(LOOP_LABELS))
3073 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3074 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3075 parseerror(parser, "expected loop label");
3078 label = util_strdup(parser_tokval(parser));
3079 if (!parser_next(parser)) {
3081 parseerror(parser, "expected 'switch' operand in parenthesis");
3086 if (parser->tok != '(') {
3087 parseerror(parser, "expected 'switch' operand in parenthesis");
3091 vec_push(parser->breaks, label);
3093 rv = parse_switch_go(parser, block, out);
3096 if (vec_last(parser->breaks) != label) {
3097 parseerror(parser, "internal error: label stack corrupted");
3103 vec_pop(parser->breaks);
3108 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3110 ast_expression *operand;
3113 ast_switch *switchnode;
3114 ast_switch_case swcase;
3117 bool noref, is_static;
3118 uint32_t qflags = 0;
3120 lex_ctx_t ctx = parser_ctx(parser);
3122 (void)block; /* not touching */
3125 /* parse into the expression */
3126 if (!parser_next(parser)) {
3127 parseerror(parser, "expected switch operand");
3130 /* parse the operand */
3131 operand = parse_expression_leave(parser, false, false, false);
3135 switchnode = ast_switch_new(ctx, operand);
3138 if (parser->tok != ')') {
3139 ast_delete(switchnode);
3140 parseerror(parser, "expected closing paren after 'switch' operand");
3144 /* parse over the opening paren */
3145 if (!parser_next(parser) || parser->tok != '{') {
3146 ast_delete(switchnode);
3147 parseerror(parser, "expected list of cases");
3151 if (!parser_next(parser)) {
3152 ast_delete(switchnode);
3153 parseerror(parser, "expected 'case' or 'default'");
3157 /* new block; allow some variables to be declared here */
3158 parser_enterblock(parser);
3161 if (parser->tok == TOKEN_IDENT)
3162 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3163 if (typevar || parser->tok == TOKEN_TYPENAME) {
3164 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, NULL)) {
3165 ast_delete(switchnode);
3170 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3172 if (cvq == CV_WRONG) {
3173 ast_delete(switchnode);
3176 if (!parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, NULL)) {
3177 ast_delete(switchnode);
3186 while (parser->tok != '}') {
3187 ast_block *caseblock;
3189 if (!strcmp(parser_tokval(parser), "case")) {
3190 if (!parser_next(parser)) {
3191 ast_delete(switchnode);
3192 parseerror(parser, "expected expression for case");
3195 swcase.value = parse_expression_leave(parser, false, false, false);
3196 if (!swcase.value) {
3197 ast_delete(switchnode);
3198 parseerror(parser, "expected expression for case");
3201 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3202 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3203 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3209 else if (!strcmp(parser_tokval(parser), "default")) {
3210 swcase.value = NULL;
3211 if (!parser_next(parser)) {
3212 ast_delete(switchnode);
3213 parseerror(parser, "expected colon");
3218 ast_delete(switchnode);
3219 parseerror(parser, "expected 'case' or 'default'");
3223 /* Now the colon and body */
3224 if (parser->tok != ':') {
3225 if (swcase.value) ast_unref(swcase.value);
3226 ast_delete(switchnode);
3227 parseerror(parser, "expected colon");
3231 if (!parser_next(parser)) {
3232 if (swcase.value) ast_unref(swcase.value);
3233 ast_delete(switchnode);
3234 parseerror(parser, "expected statements or case");
3237 caseblock = ast_block_new(parser_ctx(parser));
3239 if (swcase.value) ast_unref(swcase.value);
3240 ast_delete(switchnode);
3243 swcase.code = (ast_expression*)caseblock;
3244 vec_push(switchnode->cases, swcase);
3246 ast_expression *expr;
3247 if (parser->tok == '}')
3249 if (parser->tok == TOKEN_KEYWORD) {
3250 if (!strcmp(parser_tokval(parser), "case") ||
3251 !strcmp(parser_tokval(parser), "default"))
3256 if (!parse_statement(parser, caseblock, &expr, true)) {
3257 ast_delete(switchnode);
3262 if (!ast_block_add_expr(caseblock, expr)) {
3263 ast_delete(switchnode);
3269 parser_leaveblock(parser);
3272 if (parser->tok != '}') {
3273 ast_delete(switchnode);
3274 parseerror(parser, "expected closing paren of case list");
3277 if (!parser_next(parser)) {
3278 ast_delete(switchnode);
3279 parseerror(parser, "parse error after switch");
3282 *out = (ast_expression*)switchnode;
3286 /* parse computed goto sides */
3287 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3288 ast_expression *on_true;
3289 ast_expression *on_false;
3290 ast_expression *cond;
3295 if (ast_istype(*side, ast_ternary)) {
3296 ast_ternary *tern = (ast_ternary*)*side;
3297 on_true = parse_goto_computed(parser, &tern->on_true);
3298 on_false = parse_goto_computed(parser, &tern->on_false);
3300 if (!on_true || !on_false) {
3301 parseerror(parser, "expected label or expression in ternary");
3302 if (on_true) ast_unref(on_true);
3303 if (on_false) ast_unref(on_false);
3311 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3312 } else if (ast_istype(*side, ast_label)) {
3313 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3314 ast_goto_set_label(gt, ((ast_label*)*side));
3316 return (ast_expression*)gt;
3321 static bool parse_goto(parser_t *parser, ast_expression **out)
3323 ast_goto *gt = NULL;
3324 ast_expression *lbl;
3326 if (!parser_next(parser))
3329 if (parser->tok != TOKEN_IDENT) {
3330 ast_expression *expression;
3332 /* could be an expression i.e computed goto :-) */
3333 if (parser->tok != '(') {
3334 parseerror(parser, "expected label name after `goto`");
3338 /* failed to parse expression for goto */
3339 if (!(expression = parse_expression(parser, false, true)) ||
3340 !(*out = parse_goto_computed(parser, &expression))) {
3341 parseerror(parser, "invalid goto expression");
3343 ast_unref(expression);
3350 /* not computed goto */
3351 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3352 lbl = parser_find_label(parser, gt->name);
3354 if (!ast_istype(lbl, ast_label)) {
3355 parseerror(parser, "internal error: label is not an ast_label");
3359 ast_goto_set_label(gt, (ast_label*)lbl);
3362 vec_push(parser->gotos, gt);
3364 if (!parser_next(parser) || parser->tok != ';') {
3365 parseerror(parser, "semicolon expected after goto label");
3368 if (!parser_next(parser)) {
3369 parseerror(parser, "parse error after goto");
3373 *out = (ast_expression*)gt;
3377 static bool parse_skipwhite(parser_t *parser)
3380 if (!parser_next(parser))
3382 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3383 return parser->tok < TOKEN_ERROR;
3386 static bool parse_eol(parser_t *parser)
3388 if (!parse_skipwhite(parser))
3390 return parser->tok == TOKEN_EOL;
3393 static bool parse_pragma_do(parser_t *parser)
3395 if (!parser_next(parser) ||
3396 parser->tok != TOKEN_IDENT ||
3397 strcmp(parser_tokval(parser), "pragma"))
3399 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3402 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3403 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3407 if (!strcmp(parser_tokval(parser), "noref")) {
3408 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3409 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3412 parser->noref = !!parser_token(parser)->constval.i;
3413 if (!parse_eol(parser)) {
3414 parseerror(parser, "parse error after `noref` pragma");
3420 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3423 while (!parse_eol(parser)) {
3424 parser_next(parser);
3433 static bool parse_pragma(parser_t *parser)
3436 parser->lex->flags.preprocessing = true;
3437 parser->lex->flags.mergelines = true;
3438 rv = parse_pragma_do(parser);
3439 if (parser->tok != TOKEN_EOL) {
3440 parseerror(parser, "junk after pragma");
3443 parser->lex->flags.preprocessing = false;
3444 parser->lex->flags.mergelines = false;
3445 if (!parser_next(parser)) {
3446 parseerror(parser, "parse error after pragma");
3452 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3454 bool noref, is_static;
3456 uint32_t qflags = 0;
3457 ast_value *typevar = NULL;
3458 char *vstring = NULL;
3462 if (parser->tok == TOKEN_IDENT)
3463 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3465 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3467 /* local variable */
3469 parseerror(parser, "cannot declare a variable from here");
3472 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3473 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3476 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3480 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3482 if (cvq == CV_WRONG)
3484 return parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, vstring);
3486 else if (parser->tok == TOKEN_KEYWORD)
3488 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3493 if (!parser_next(parser)) {
3494 parseerror(parser, "parse error after __builtin_debug_printtype");
3498 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3500 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3501 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3502 if (!parser_next(parser)) {
3503 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3509 if (!parse_statement(parser, block, out, allow_cases))
3512 con_out("__builtin_debug_printtype: got no output node\n");
3515 ast_type_to_string(*out, ty, sizeof(ty));
3516 con_out("__builtin_debug_printtype: `%s`\n", ty);
3521 else if (!strcmp(parser_tokval(parser), "return"))
3523 return parse_return(parser, block, out);
3525 else if (!strcmp(parser_tokval(parser), "if"))
3527 return parse_if(parser, block, out);
3529 else if (!strcmp(parser_tokval(parser), "while"))
3531 return parse_while(parser, block, out);
3533 else if (!strcmp(parser_tokval(parser), "do"))
3535 return parse_dowhile(parser, block, out);
3537 else if (!strcmp(parser_tokval(parser), "for"))
3539 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3540 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3543 return parse_for(parser, block, out);
3545 else if (!strcmp(parser_tokval(parser), "break"))
3547 return parse_break_continue(parser, block, out, false);
3549 else if (!strcmp(parser_tokval(parser), "continue"))
3551 return parse_break_continue(parser, block, out, true);
3553 else if (!strcmp(parser_tokval(parser), "switch"))
3555 return parse_switch(parser, block, out);
3557 else if (!strcmp(parser_tokval(parser), "case") ||
3558 !strcmp(parser_tokval(parser), "default"))
3561 parseerror(parser, "unexpected 'case' label");
3566 else if (!strcmp(parser_tokval(parser), "goto"))
3568 return parse_goto(parser, out);
3570 else if (!strcmp(parser_tokval(parser), "typedef"))
3572 if (!parser_next(parser)) {
3573 parseerror(parser, "expected type definition after 'typedef'");
3576 return parse_typedef(parser);
3578 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3581 else if (parser->tok == '{')
3584 inner = parse_block(parser);
3587 *out = (ast_expression*)inner;
3590 else if (parser->tok == ':')
3594 if (!parser_next(parser)) {
3595 parseerror(parser, "expected label name");
3598 if (parser->tok != TOKEN_IDENT) {
3599 parseerror(parser, "label must be an identifier");
3602 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3604 if (!label->undefined) {
3605 parseerror(parser, "label `%s` already defined", label->name);
3608 label->undefined = false;
3611 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3612 vec_push(parser->labels, label);
3614 *out = (ast_expression*)label;
3615 if (!parser_next(parser)) {
3616 parseerror(parser, "parse error after label");
3619 for (i = 0; i < vec_size(parser->gotos); ++i) {
3620 if (!strcmp(parser->gotos[i]->name, label->name)) {
3621 ast_goto_set_label(parser->gotos[i], label);
3622 vec_remove(parser->gotos, i, 1);
3628 else if (parser->tok == ';')
3630 if (!parser_next(parser)) {
3631 parseerror(parser, "parse error after empty statement");
3638 lex_ctx_t ctx = parser_ctx(parser);
3639 ast_expression *exp = parse_expression(parser, false, false);
3643 if (!ast_side_effects(exp)) {
3644 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3651 static bool parse_enum(parser_t *parser)
3654 bool reverse = false;
3656 ast_value **values = NULL;
3657 ast_value *var = NULL;
3660 ast_expression *old;
3662 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3663 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3667 /* enumeration attributes (can add more later) */
3668 if (parser->tok == ':') {
3669 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3670 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3675 if (!strcmp(parser_tokval(parser), "flag")) {
3679 else if (!strcmp(parser_tokval(parser), "reverse")) {
3683 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3687 if (!parser_next(parser) || parser->tok != '{') {
3688 parseerror(parser, "expected `{` after enum attribute ");
3694 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3695 if (parser->tok == '}') {
3696 /* allow an empty enum */
3699 parseerror(parser, "expected identifier or `}`");
3703 old = parser_find_field(parser, parser_tokval(parser));
3705 old = parser_find_global(parser, parser_tokval(parser));
3707 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3708 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3712 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3713 vec_push(values, var);
3714 var->cvq = CV_CONST;
3715 var->hasvalue = true;
3717 /* for flagged enumerations increment in POTs of TWO */
3718 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3719 parser_addglobal(parser, var->name, (ast_expression*)var);
3721 if (!parser_next(parser)) {
3722 parseerror(parser, "expected `=`, `}` or comma after identifier");
3726 if (parser->tok == ',')
3728 if (parser->tok == '}')
3730 if (parser->tok != '=') {
3731 parseerror(parser, "expected `=`, `}` or comma after identifier");
3735 if (!parser_next(parser)) {
3736 parseerror(parser, "expected expression after `=`");
3740 /* We got a value! */
3741 old = parse_expression_leave(parser, true, false, false);
3742 asvalue = (ast_value*)old;
3743 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3744 compile_error(ast_ctx(var), "constant value or expression expected");
3747 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3749 if (parser->tok == '}')
3751 if (parser->tok != ',') {
3752 parseerror(parser, "expected `}` or comma after expression");
3757 /* patch them all (for reversed attribute) */
3760 for (i = 0; i < vec_size(values); i++)
3761 values[i]->constval.vfloat = vec_size(values) - i - 1;
3764 if (parser->tok != '}') {
3765 parseerror(parser, "internal error: breaking without `}`");
3769 if (!parser_next(parser) || parser->tok != ';') {
3770 parseerror(parser, "expected semicolon after enumeration");
3774 if (!parser_next(parser)) {
3775 parseerror(parser, "parse error after enumeration");
3787 static bool parse_block_into(parser_t *parser, ast_block *block)
3791 parser_enterblock(parser);
3793 if (!parser_next(parser)) { /* skip the '{' */
3794 parseerror(parser, "expected function body");
3798 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3800 ast_expression *expr = NULL;
3801 if (parser->tok == '}')
3804 if (!parse_statement(parser, block, &expr, false)) {
3805 /* parseerror(parser, "parse error"); */
3811 if (!ast_block_add_expr(block, expr)) {
3818 if (parser->tok != '}') {
3821 (void)parser_next(parser);
3825 if (!parser_leaveblock(parser))
3827 return retval && !!block;
3830 static ast_block* parse_block(parser_t *parser)
3833 block = ast_block_new(parser_ctx(parser));
3836 if (!parse_block_into(parser, block)) {
3837 ast_block_delete(block);
3843 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3845 if (parser->tok == '{') {
3846 *out = (ast_expression*)parse_block(parser);
3849 return parse_statement(parser, NULL, out, false);
3852 static bool create_vector_members(ast_value *var, ast_member **me)
3855 size_t len = strlen(var->name);
3857 for (i = 0; i < 3; ++i) {
3858 char *name = (char*)mem_a(len+3);
3859 memcpy(name, var->name, len);
3861 name[len+1] = 'x'+i;
3863 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3872 do { ast_member_delete(me[--i]); } while(i);
3876 static bool parse_function_body(parser_t *parser, ast_value *var)
3878 ast_block *block = NULL;
3883 ast_expression *framenum = NULL;
3884 ast_expression *nextthink = NULL;
3885 /* None of the following have to be deleted */
3886 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3887 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3888 bool has_frame_think;
3892 has_frame_think = false;
3893 old = parser->function;
3895 if (var->expression.flags & AST_FLAG_ALIAS) {
3896 parseerror(parser, "function aliases cannot have bodies");
3900 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3901 parseerror(parser, "gotos/labels leaking");
3905 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3906 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3907 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3913 if (parser->tok == '[') {
3914 /* got a frame definition: [ framenum, nextthink ]
3915 * this translates to:
3916 * self.frame = framenum;
3917 * self.nextthink = time + 0.1;
3918 * self.think = nextthink;
3922 fld_think = parser_find_field(parser, "think");
3923 fld_nextthink = parser_find_field(parser, "nextthink");
3924 fld_frame = parser_find_field(parser, "frame");
3925 if (!fld_think || !fld_nextthink || !fld_frame) {
3926 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3927 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3930 gbl_time = parser_find_global(parser, "time");
3931 gbl_self = parser_find_global(parser, "self");
3932 if (!gbl_time || !gbl_self) {
3933 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3934 parseerror(parser, "please declare the following globals: `time`, `self`");
3938 if (!parser_next(parser))
3941 framenum = parse_expression_leave(parser, true, false, false);
3943 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3946 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3947 ast_unref(framenum);
3948 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3952 if (parser->tok != ',') {
3953 ast_unref(framenum);
3954 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3955 parseerror(parser, "Got a %i\n", parser->tok);
3959 if (!parser_next(parser)) {
3960 ast_unref(framenum);
3964 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3966 /* qc allows the use of not-yet-declared functions here
3967 * - this automatically creates a prototype */
3968 ast_value *thinkfunc;
3969 ast_expression *functype = fld_think->next;
3971 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3972 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3973 ast_unref(framenum);
3974 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3977 ast_type_adopt(thinkfunc, functype);
3979 if (!parser_next(parser)) {
3980 ast_unref(framenum);
3981 ast_delete(thinkfunc);
3985 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3987 nextthink = (ast_expression*)thinkfunc;
3990 nextthink = parse_expression_leave(parser, true, false, false);
3992 ast_unref(framenum);
3993 parseerror(parser, "expected a think-function in [frame,think] notation");
3998 if (!ast_istype(nextthink, ast_value)) {
3999 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4003 if (retval && parser->tok != ']') {
4004 parseerror(parser, "expected closing `]` for [frame,think] notation");
4008 if (retval && !parser_next(parser)) {
4012 if (retval && parser->tok != '{') {
4013 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4018 ast_unref(nextthink);
4019 ast_unref(framenum);
4023 has_frame_think = true;
4026 block = ast_block_new(parser_ctx(parser));
4028 parseerror(parser, "failed to allocate block");
4029 if (has_frame_think) {
4030 ast_unref(nextthink);
4031 ast_unref(framenum);
4036 if (has_frame_think) {
4037 if (!OPTS_FLAG(EMULATE_STATE)) {
4038 ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
4039 if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
4040 parseerror(parser, "failed to generate state op for [frame,think]");
4041 ast_unref(nextthink);
4042 ast_unref(framenum);
4047 /* emulate OP_STATE in code: */
4049 ast_expression *self_frame;
4050 ast_expression *self_nextthink;
4051 ast_expression *self_think;
4052 ast_expression *time_plus_1;
4053 ast_store *store_frame;
4054 ast_store *store_nextthink;
4055 ast_store *store_think;
4057 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4059 ctx = parser_ctx(parser);
4060 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4061 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4062 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4064 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4065 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, frame_delta, false));
4067 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4068 if (self_frame) ast_delete(self_frame);
4069 if (self_nextthink) ast_delete(self_nextthink);
4070 if (self_think) ast_delete(self_think);
4071 if (time_plus_1) ast_delete(time_plus_1);
4077 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4078 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4079 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4082 ast_delete(self_frame);
4085 if (!store_nextthink) {
4086 ast_delete(self_nextthink);
4090 ast_delete(self_think);
4094 if (store_frame) ast_delete(store_frame);
4095 if (store_nextthink) ast_delete(store_nextthink);
4096 if (store_think) ast_delete(store_think);
4099 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4100 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4101 !ast_block_add_expr(block, (ast_expression*)store_think))
4108 parseerror(parser, "failed to generate code for [frame,think]");
4109 ast_unref(nextthink);
4110 ast_unref(framenum);
4117 if (var->hasvalue) {
4118 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4119 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4120 ast_block_delete(block);
4123 func = var->constval.vfunc;
4126 parseerror(parser, "internal error: NULL function: `%s`", var->name);
4127 ast_block_delete(block);
4131 func = ast_function_new(ast_ctx(var), var->name, var);
4134 parseerror(parser, "failed to allocate function for `%s`", var->name);
4135 ast_block_delete(block);
4138 vec_push(parser->functions, func);
4141 parser_enterblock(parser);
4143 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4145 ast_value *param = var->expression.params[parami];
4148 if (param->expression.vtype != TYPE_VECTOR &&
4149 (param->expression.vtype != TYPE_FIELD ||
4150 param->expression.next->vtype != TYPE_VECTOR))
4155 if (!create_vector_members(param, me)) {
4156 ast_block_delete(block);
4160 for (e = 0; e < 3; ++e) {
4161 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4162 ast_block_collect(block, (ast_expression*)me[e]);
4166 if (var->argcounter && !func->argc) {
4167 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4168 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4172 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4174 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4175 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4176 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4177 varargs->expression.count = 0;
4178 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4179 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4180 ast_delete(varargs);
4181 ast_block_delete(block);
4184 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4185 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4186 ast_delete(varargs);
4187 ast_block_delete(block);
4190 func->varargs = varargs;
4191 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params), false);
4194 parser->function = func;
4195 if (!parse_block_into(parser, block)) {
4196 ast_block_delete(block);
4200 vec_push(func->blocks, block);
4202 parser->function = old;
4203 if (!parser_leaveblock(parser))
4205 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4206 parseerror(parser, "internal error: local scopes left");
4210 if (parser->tok == ';')
4211 return parser_next(parser);
4212 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4213 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4217 (void)!parser_leaveblock(parser);
4218 vec_pop(parser->functions);
4219 ast_function_delete(func);
4220 var->constval.vfunc = NULL;
4223 parser->function = old;
4227 static ast_expression *array_accessor_split(
4232 ast_expression *left,
4233 ast_expression *right
4239 lex_ctx_t ctx = ast_ctx(array);
4241 if (!left || !right) {
4242 if (left) ast_delete(left);
4243 if (right) ast_delete(right);
4247 cmp = ast_binary_new(ctx, INSTR_LT,
4248 (ast_expression*)index,
4249 (ast_expression*)fold_constgen_float(parser->fold, middle, false));
4253 parseerror(parser, "internal error: failed to create comparison for array setter");
4257 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4259 ast_delete(cmp); /* will delete left and right */
4260 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4264 return (ast_expression*)ifthen;
4267 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4269 lex_ctx_t ctx = ast_ctx(array);
4271 if (from+1 == afterend) {
4272 /* set this value */
4275 ast_array_index *subscript;
4277 int assignop = type_store_instr[value->expression.vtype];
4279 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4280 assignop = INSTR_STORE_V;
4282 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4286 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4288 ast_delete(subscript);
4292 block = ast_block_new(ctx);
4298 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4303 ret = ast_return_new(ctx, NULL);
4309 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4314 return (ast_expression*)block;
4316 ast_expression *left, *right;
4317 size_t diff = afterend - from;
4318 size_t middle = from + diff/2;
4319 left = array_setter_node(parser, array, index, value, from, middle);
4320 right = array_setter_node(parser, array, index, value, middle, afterend);
4321 return array_accessor_split(parser, array, index, middle, left, right);
4325 static ast_expression *array_field_setter_node(
4334 lex_ctx_t ctx = ast_ctx(array);
4336 if (from+1 == afterend) {
4337 /* set this value */
4340 ast_entfield *entfield;
4341 ast_array_index *subscript;
4343 int assignop = type_storep_instr[value->expression.vtype];
4345 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4346 assignop = INSTR_STOREP_V;
4348 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4352 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4353 subscript->expression.vtype = TYPE_FIELD;
4355 entfield = ast_entfield_new_force(ctx,
4356 (ast_expression*)entity,
4357 (ast_expression*)subscript,
4358 (ast_expression*)subscript);
4360 ast_delete(subscript);
4364 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4366 ast_delete(entfield);
4370 block = ast_block_new(ctx);
4376 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4381 ret = ast_return_new(ctx, NULL);
4387 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4392 return (ast_expression*)block;
4394 ast_expression *left, *right;
4395 size_t diff = afterend - from;
4396 size_t middle = from + diff/2;
4397 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4398 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4399 return array_accessor_split(parser, array, index, middle, left, right);
4403 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4405 lex_ctx_t ctx = ast_ctx(array);
4407 if (from+1 == afterend) {
4409 ast_array_index *subscript;
4411 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4415 ret = ast_return_new(ctx, (ast_expression*)subscript);
4417 ast_delete(subscript);
4421 return (ast_expression*)ret;
4423 ast_expression *left, *right;
4424 size_t diff = afterend - from;
4425 size_t middle = from + diff/2;
4426 left = array_getter_node(parser, array, index, from, middle);
4427 right = array_getter_node(parser, array, index, middle, afterend);
4428 return array_accessor_split(parser, array, index, middle, left, right);
4432 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4434 ast_function *func = NULL;
4435 ast_value *fval = NULL;
4436 ast_block *body = NULL;
4438 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4440 parseerror(parser, "failed to create accessor function value");
4443 fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4445 func = ast_function_new(ast_ctx(array), funcname, fval);
4448 parseerror(parser, "failed to create accessor function node");
4452 body = ast_block_new(ast_ctx(array));
4454 parseerror(parser, "failed to create block for array accessor");
4460 vec_push(func->blocks, body);
4463 vec_push(parser->accessors, fval);
4468 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4470 ast_value *index = NULL;
4471 ast_value *value = NULL;
4475 if (!ast_istype(array->expression.next, ast_value)) {
4476 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4480 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4482 func = fval->constval.vfunc;
4483 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4485 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4486 value = ast_value_copy((ast_value*)array->expression.next);
4488 if (!index || !value) {
4489 parseerror(parser, "failed to create locals for array accessor");
4492 (void)!ast_value_set_name(value, "value"); /* not important */
4493 vec_push(fval->expression.params, index);
4494 vec_push(fval->expression.params, value);
4496 array->setter = fval;
4499 if (index) ast_delete(index);
4500 if (value) ast_delete(value);
4506 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4508 ast_expression *root = NULL;
4509 root = array_setter_node(parser, array,
4510 array->setter->expression.params[0],
4511 array->setter->expression.params[1],
4512 0, array->expression.count);
4514 parseerror(parser, "failed to build accessor search tree");
4517 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4524 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4526 if (!parser_create_array_setter_proto(parser, array, funcname))
4528 return parser_create_array_setter_impl(parser, array);
4531 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4533 ast_expression *root = NULL;
4534 ast_value *entity = NULL;
4535 ast_value *index = NULL;
4536 ast_value *value = NULL;
4540 if (!ast_istype(array->expression.next, ast_value)) {
4541 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4545 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4547 func = fval->constval.vfunc;
4548 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4550 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4551 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4552 value = ast_value_copy((ast_value*)array->expression.next);
4553 if (!entity || !index || !value) {
4554 parseerror(parser, "failed to create locals for array accessor");
4557 (void)!ast_value_set_name(value, "value"); /* not important */
4558 vec_push(fval->expression.params, entity);
4559 vec_push(fval->expression.params, index);
4560 vec_push(fval->expression.params, value);
4562 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4564 parseerror(parser, "failed to build accessor search tree");
4568 array->setter = fval;
4569 return ast_block_add_expr(func->blocks[0], root);
4571 if (entity) ast_delete(entity);
4572 if (index) ast_delete(index);
4573 if (value) ast_delete(value);
4574 if (root) ast_delete(root);
4580 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4582 ast_value *index = NULL;
4586 /* NOTE: checking array->expression.next rather than elemtype since
4587 * for fields elemtype is a temporary fieldtype.
4589 if (!ast_istype(array->expression.next, ast_value)) {
4590 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4594 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4596 func = fval->constval.vfunc;
4597 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4599 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4602 parseerror(parser, "failed to create locals for array accessor");
4605 vec_push(fval->expression.params, index);
4607 array->getter = fval;
4610 if (index) ast_delete(index);
4616 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4618 ast_expression *root = NULL;
4620 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4622 parseerror(parser, "failed to build accessor search tree");
4625 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4632 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4634 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4636 return parser_create_array_getter_impl(parser, array);
4639 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4647 bool variadic = false;
4648 ast_value *varparam = NULL;
4649 char *argcounter = NULL;
4651 ctx = parser_ctx(parser);
4653 /* for the sake of less code we parse-in in this function */
4654 if (!parser_next(parser)) {
4656 parseerror(parser, "expected parameter list");
4662 /* parse variables until we hit a closing paren */
4663 while (parser->tok != ')') {
4664 bool is_varargs = false;
4667 /* there must be commas between them */
4668 if (parser->tok != ',') {
4669 parseerror(parser, "expected comma or end of parameter list");
4672 if (!parser_next(parser)) {
4673 parseerror(parser, "expected parameter");
4679 param = parse_typename(parser, NULL, NULL, &is_varargs);
4680 if (!param && !is_varargs)
4683 /* '...' indicates a varargs function */
4685 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4686 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4689 if (parser->tok == TOKEN_IDENT) {
4690 argcounter = util_strdup(parser_tokval(parser));
4691 if (!parser_next(parser) || parser->tok != ')') {
4692 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4697 vec_push(params, param);
4698 if (param->expression.vtype >= TYPE_VARIANT) {
4699 char tname[1024]; /* typename is reserved in C++ */
4700 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4701 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4704 /* type-restricted varargs */
4705 if (parser->tok == TOKEN_DOTS) {
4707 varparam = vec_last(params);
4709 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4710 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4713 if (parser->tok == TOKEN_IDENT) {
4714 argcounter = util_strdup(parser_tokval(parser));
4715 ast_value_set_name(param, argcounter);
4716 if (!parser_next(parser) || parser->tok != ')') {
4717 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4722 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->name[0] == '<') {
4723 parseerror(parser, "parameter name omitted");
4729 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4733 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4734 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4737 if (!parser_next(parser)) {
4738 parseerror(parser, "parse error after typename");
4742 /* now turn 'var' into a function type */
4743 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4744 fval->expression.next = (ast_expression*)var;
4746 fval->expression.flags |= AST_FLAG_VARIADIC;
4749 var->expression.params = params;
4750 var->expression.varparam = (ast_expression*)varparam;
4751 var->argcounter = argcounter;
4760 ast_delete(varparam);
4762 for (i = 0; i < vec_size(params); ++i)
4763 ast_delete(params[i]);
4768 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4770 ast_expression *cexp;
4771 ast_value *cval, *tmp;
4774 ctx = parser_ctx(parser);
4776 if (!parser_next(parser)) {
4778 parseerror(parser, "expected array-size");
4782 if (parser->tok != ']') {
4783 cexp = parse_expression_leave(parser, true, false, false);
4785 if (!cexp || !ast_istype(cexp, ast_value)) {
4789 parseerror(parser, "expected array-size as constant positive integer");
4792 cval = (ast_value*)cexp;
4799 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4800 tmp->expression.next = (ast_expression*)var;
4804 if (cval->expression.vtype == TYPE_INTEGER)
4805 tmp->expression.count = cval->constval.vint;
4806 else if (cval->expression.vtype == TYPE_FLOAT)
4807 tmp->expression.count = cval->constval.vfloat;
4811 parseerror(parser, "array-size must be a positive integer constant");
4817 var->expression.count = -1;
4818 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4821 if (parser->tok != ']') {
4823 parseerror(parser, "expected ']' after array-size");
4826 if (!parser_next(parser)) {
4828 parseerror(parser, "error after parsing array size");
4834 /* Parse a complete typename.
4835 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4836 * but when parsing variables separated by comma
4837 * 'storebase' should point to where the base-type should be kept.
4838 * The base type makes up every bit of type information which comes *before* the
4841 * NOTE: The value must either be named, have a NULL name, or a name starting
4842 * with '<'. In the first case, this will be the actual variable or type
4843 * name, in the other cases it is assumed that the name will appear
4844 * later, and an error is generated otherwise.
4846 * The following will be parsed in its entirety:
4848 * The 'basetype' in this case is 'void()'
4849 * and if there's a comma after it, say:
4851 * then the type-information 'void()' can be stored in 'storebase'
4853 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4855 ast_value *var, *tmp;
4858 const char *name = NULL;
4859 bool isfield = false;
4860 bool wasarray = false;
4861 size_t morefields = 0;
4863 bool vararg = (parser->tok == TOKEN_DOTS);
4865 ctx = parser_ctx(parser);
4867 /* types may start with a dot */
4868 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4870 if (parser->tok == TOKEN_DOTS)
4872 /* if we parsed a dot we need a typename now */
4873 if (!parser_next(parser)) {
4874 parseerror(parser, "expected typename for field definition");
4878 /* Further dots are handled seperately because they won't be part of the
4882 if (parser->tok == '.')
4884 else if (parser->tok == TOKEN_DOTS)
4889 if (!parser_next(parser)) {
4890 parseerror(parser, "expected typename for field definition");
4895 if (parser->tok == TOKEN_IDENT)
4896 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4897 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4898 if (vararg && is_vararg) {
4902 parseerror(parser, "expected typename");
4906 /* generate the basic type value */
4907 if (cached_typedef) {
4908 var = ast_value_copy(cached_typedef);
4909 ast_value_set_name(var, "<type(from_def)>");
4911 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4913 for (; morefields; --morefields) {
4914 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4915 tmp->expression.next = (ast_expression*)var;
4919 /* do not yet turn into a field - remember:
4920 * .void() foo; is a field too
4921 * .void()() foo; is a function
4925 if (!parser_next(parser)) {
4927 parseerror(parser, "parse error after typename");
4931 /* an opening paren now starts the parameter-list of a function
4932 * this is where original-QC has parameter lists.
4933 * We allow a single parameter list here.
4934 * Much like fteqcc we don't allow `float()() x`
4936 if (parser->tok == '(') {
4937 var = parse_parameter_list(parser, var);
4942 /* store the base if requested */
4944 *storebase = ast_value_copy(var);
4946 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4947 tmp->expression.next = (ast_expression*)*storebase;
4952 /* there may be a name now */
4953 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4954 if (!strcmp(parser_tokval(parser), "break"))
4955 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4956 else if (parser->tok == TOKEN_KEYWORD)
4959 name = util_strdup(parser_tokval(parser));
4962 if (!parser_next(parser)) {
4965 parseerror(parser, "error after variable or field declaration");
4971 /* now this may be an array */
4972 if (parser->tok == '[') {
4974 var = parse_arraysize(parser, var);
4976 if (name) mem_d(name);
4981 /* This is the point where we can turn it into a field */
4983 /* turn it into a field if desired */
4984 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4985 tmp->expression.next = (ast_expression*)var;
4989 /* now there may be function parens again */
4990 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4991 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4992 if (parser->tok == '(' && wasarray)
4993 parseerror(parser, "arrays as part of a return type is not supported");
4994 while (parser->tok == '(') {
4995 var = parse_parameter_list(parser, var);
4997 if (name) mem_d(name);
5002 /* finally name it */
5004 if (!ast_value_set_name(var, name)) {
5007 parseerror(parser, "internal error: failed to set name");
5010 /* free the name, ast_value_set_name duplicates */
5017 static bool parse_typedef(parser_t *parser)
5019 ast_value *typevar, *oldtype;
5020 ast_expression *old;
5022 typevar = parse_typename(parser, NULL, NULL, NULL);
5027 /* while parsing types, the ast_value's get named '<something>' */
5028 if (!typevar->name || typevar->name[0] == '<') {
5029 parseerror(parser, "missing name in typedef");
5030 ast_delete(typevar);
5034 if ( (old = parser_find_var(parser, typevar->name)) ) {
5035 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5036 " -> `%s` has been declared here: %s:%i",
5037 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5038 ast_delete(typevar);
5042 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5043 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5044 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5045 ast_delete(typevar);
5049 vec_push(parser->_typedefs, typevar);
5050 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5052 if (parser->tok != ';') {
5053 parseerror(parser, "expected semicolon after typedef");
5056 if (!parser_next(parser)) {
5057 parseerror(parser, "parse error after typedef");
5064 static const char *cvq_to_str(int cvq) {
5066 case CV_NONE: return "none";
5067 case CV_VAR: return "`var`";
5068 case CV_CONST: return "`const`";
5069 default: return "<INVALID>";
5073 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5076 if (proto->cvq != var->cvq) {
5077 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5078 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5079 parser->tok == '='))
5081 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5082 "`%s` declared with different qualifiers: %s\n"
5083 " -> previous declaration here: %s:%i uses %s",
5084 var->name, cvq_to_str(var->cvq),
5085 ast_ctx(proto).file, ast_ctx(proto).line,
5086 cvq_to_str(proto->cvq));
5089 av = (var ->expression.flags & AST_FLAG_NORETURN);
5090 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5092 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5093 "`%s` declared with different attributes%s\n"
5094 " -> previous declaration here: %s:%i",
5095 var->name, (av ? ": noreturn" : ""),
5096 ast_ctx(proto).file, ast_ctx(proto).line,
5097 (ao ? ": noreturn" : ""));
5102 static bool create_array_accessors(parser_t *parser, ast_value *var)
5105 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5106 if (!parser_create_array_setter(parser, var, name))
5108 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5109 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5114 static bool parse_array(parser_t *parser, ast_value *array)
5117 if (array->initlist) {
5118 parseerror(parser, "array already initialized elsewhere");
5121 if (!parser_next(parser)) {
5122 parseerror(parser, "parse error in array initializer");
5126 while (parser->tok != '}') {
5127 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5130 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5132 parseerror(parser, "initializing element must be a compile time constant");
5135 vec_push(array->initlist, v->constval);
5136 if (v->expression.vtype == TYPE_STRING) {
5137 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5141 if (parser->tok == '}')
5143 if (parser->tok != ',' || !parser_next(parser)) {
5144 parseerror(parser, "expected comma or '}' in element list");
5148 if (!parser_next(parser) || parser->tok != ';') {
5149 parseerror(parser, "expected semicolon after initializer, got %s");
5153 if (!parser_next(parser)) {
5154 parseerror(parser, "parse error after initializer");
5159 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5160 if (array->expression.count != (size_t)-1) {
5161 parseerror(parser, "array `%s' has already been initialized with %u elements",
5162 array->name, (unsigned)array->expression.count);
5164 array->expression.count = vec_size(array->initlist);
5165 if (!create_array_accessors(parser, array))
5171 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)
5175 ast_expression *old;
5179 ast_value *basetype = NULL;
5181 bool isparam = false;
5182 bool isvector = false;
5183 bool cleanvar = true;
5184 bool wasarray = false;
5186 ast_member *me[3] = { NULL, NULL, NULL };
5187 ast_member *last_me[3] = { NULL, NULL, NULL };
5189 if (!localblock && is_static)
5190 parseerror(parser, "`static` qualifier is not supported in global scope");
5192 /* get the first complete variable */
5193 var = parse_typename(parser, &basetype, cached_typedef, NULL);
5196 ast_delete(basetype);
5200 /* while parsing types, the ast_value's get named '<something>' */
5201 if (!var->name || var->name[0] == '<') {
5202 parseerror(parser, "declaration does not declare anything");
5204 ast_delete(basetype);
5212 /* Part 0: finish the type */
5213 if (parser->tok == '(') {
5214 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5215 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5216 var = parse_parameter_list(parser, var);
5222 /* we only allow 1-dimensional arrays */
5223 if (parser->tok == '[') {
5225 var = parse_arraysize(parser, var);
5231 if (parser->tok == '(' && wasarray) {
5232 parseerror(parser, "arrays as part of a return type is not supported");
5233 /* we'll still parse the type completely for now */
5235 /* for functions returning functions */
5236 while (parser->tok == '(') {
5237 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5238 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5239 var = parse_parameter_list(parser, var);
5246 var->cvq = qualifier;
5247 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5248 var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5249 var->expression.flags |= qflags;
5252 * store the vstring back to var for alias and
5253 * deprecation messages.
5255 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5256 var->expression.flags & AST_FLAG_ALIAS)
5257 var->desc = vstring;
5259 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5260 parseerror(parser, "function aliases cannot be forward declared");
5267 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5268 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5269 * is then filled with the previous definition and the parameter-names replaced.
5271 if (!strcmp(var->name, "nil")) {
5272 if (OPTS_FLAG(UNTYPED_NIL)) {
5273 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5274 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5276 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5279 /* Deal with end_sys_ vars */
5281 if (!strcmp(var->name, "end_sys_globals")) {
5283 parser->crc_globals = vec_size(parser->globals);
5286 else if (!strcmp(var->name, "end_sys_fields")) {
5288 parser->crc_fields = vec_size(parser->fields);
5291 if (was_end && var->expression.vtype == TYPE_FIELD) {
5292 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5293 "global '%s' hint should not be a field",
5294 parser_tokval(parser)))
5301 if (!nofields && var->expression.vtype == TYPE_FIELD)
5303 /* deal with field declarations */
5304 old = parser_find_field(parser, var->name);
5306 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5307 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5316 parseerror(parser, "field `%s` already declared here: %s:%i",
5317 var->name, ast_ctx(old).file, ast_ctx(old).line);
5322 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5323 (old = parser_find_global(parser, var->name)))
5325 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5326 parseerror(parser, "field `%s` already declared here: %s:%i",
5327 var->name, ast_ctx(old).file, ast_ctx(old).line);
5334 /* deal with other globals */
5335 old = parser_find_global(parser, var->name);
5336 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5338 /* This is a function which had a prototype */
5339 if (!ast_istype(old, ast_value)) {
5340 parseerror(parser, "internal error: prototype is not an ast_value");
5344 proto = (ast_value*)old;
5345 proto->desc = var->desc;
5346 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5347 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5349 ast_ctx(proto).file, ast_ctx(proto).line);
5353 /* we need the new parameter-names */
5354 for (i = 0; i < vec_size(proto->expression.params); ++i)
5355 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5356 if (!parser_check_qualifiers(parser, var, proto)) {
5363 proto->expression.flags |= var->expression.flags;
5371 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5372 "global `%s` already declared here: %s:%i",
5373 var->name, ast_ctx(old).file, ast_ctx(old).line))
5378 if (old->flags & AST_FLAG_FINAL_DECL) {
5379 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5380 var->name, ast_ctx(old).file, ast_ctx(old).line);
5384 proto = (ast_value*)old;
5385 if (!ast_istype(old, ast_value)) {
5386 parseerror(parser, "internal error: not an ast_value");
5391 if (!parser_check_qualifiers(parser, var, proto)) {
5396 proto->expression.flags |= var->expression.flags;
5397 /* copy the context for finals,
5398 * so the error can show where it was actually made 'final'
5400 if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5401 ast_ctx(old) = ast_ctx(var);
5405 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5406 (old = parser_find_field(parser, var->name)))
5408 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5409 parseerror(parser, "global `%s` already declared here: %s:%i",
5410 var->name, ast_ctx(old).file, ast_ctx(old).line);
5417 else /* it's not a global */
5419 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5420 if (old && !isparam) {
5421 parseerror(parser, "local `%s` already declared here: %s:%i",
5422 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5426 /* doing this here as the above is just for a single scope */
5427 old = parser_find_local(parser, var->name, 0, &isparam);
5428 if (old && isparam) {
5429 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5430 "local `%s` is shadowing a parameter", var->name))
5432 parseerror(parser, "local `%s` already declared here: %s:%i",
5433 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5437 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5439 if (ast_istype(old, ast_value))
5440 var = proto = (ast_value*)old;
5449 /* in a noref section we simply bump the usecount */
5450 if (noref || parser->noref)
5454 * Create the global/local, and deal with vector types.
5457 if (var->expression.vtype == TYPE_VECTOR)
5459 else if (var->expression.vtype == TYPE_FIELD &&
5460 var->expression.next->vtype == TYPE_VECTOR)
5464 if (!create_vector_members(var, me)) {
5471 /* deal with global variables, fields, functions */
5472 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5473 var->isfield = true;
5474 vec_push(parser->fields, (ast_expression*)var);
5475 util_htset(parser->htfields, var->name, var);
5477 for (i = 0; i < 3; ++i) {
5478 vec_push(parser->fields, (ast_expression*)me[i]);
5479 util_htset(parser->htfields, me[i]->name, me[i]);
5484 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5485 parser_addglobal(parser, var->name, (ast_expression*)var);
5487 for (i = 0; i < 3; ++i) {
5488 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5492 ast_expression *find = parser_find_global(parser, var->desc);
5495 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5499 if (!ast_compare_type((ast_expression*)var, find)) {
5503 ast_type_to_string(find, ty1, sizeof(ty1));
5504 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5506 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5513 * add alias to aliases table and to corrector
5514 * so corrections can apply for aliases as well.
5516 util_htset(parser->aliases, var->name, find);
5519 * add to corrector so corrections can work
5520 * even for aliases too.
5523 vec_last(parser->correct_variables),
5524 &vec_last(parser->correct_variables_score),
5528 /* generate aliases for vector components */
5532 util_asprintf(&buffer[0], "%s_x", var->desc);
5533 util_asprintf(&buffer[1], "%s_y", var->desc);
5534 util_asprintf(&buffer[2], "%s_z", var->desc);
5536 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5537 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5538 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5545 * add to corrector so corrections can work
5546 * even for aliases too.
5549 vec_last(parser->correct_variables),
5550 &vec_last(parser->correct_variables_score),
5554 vec_last(parser->correct_variables),
5555 &vec_last(parser->correct_variables_score),
5559 vec_last(parser->correct_variables),
5560 &vec_last(parser->correct_variables_score),
5568 /* a static adds itself to be generated like any other global
5569 * but is added to the local namespace instead
5571 char *defname = NULL;
5572 size_t prefix_len, ln;
5575 ln = strlen(parser->function->name);
5576 vec_append(defname, ln, parser->function->name);
5578 vec_append(defname, 2, "::");
5579 /* remember the length up to here */
5580 prefix_len = vec_size(defname);
5582 /* Add it to the local scope */
5583 util_htset(vec_last(parser->variables), var->name, (void*)var);
5587 vec_last(parser->correct_variables),
5588 &vec_last(parser->correct_variables_score),
5592 /* now rename the global */
5593 ln = strlen(var->name);
5594 vec_append(defname, ln, var->name);
5595 /* if a variable of that name already existed, add the
5597 * The counter is incremented either way.
5599 sn_size = vec_size(parser->function->static_names);
5600 for (sn = 0; sn != sn_size; ++sn) {
5601 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5604 if (sn != sn_size) {
5606 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5607 vec_append(defname, len, num);
5611 vec_push(parser->function->static_names, util_strdup(var->name));
5612 parser->function->static_count++;
5613 ast_value_set_name(var, defname);
5615 /* push it to the to-be-generated globals */
5616 vec_push(parser->globals, (ast_expression*)var);
5618 /* same game for the vector members */
5620 for (i = 0; i < 3; ++i) {
5621 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5625 vec_last(parser->correct_variables),
5626 &vec_last(parser->correct_variables_score),
5630 vec_shrinkto(defname, prefix_len);
5631 ln = strlen(me[i]->name);
5632 vec_append(defname, ln, me[i]->name);
5633 ast_member_set_name(me[i], defname);
5635 vec_push(parser->globals, (ast_expression*)me[i]);
5640 vec_push(localblock->locals, var);
5641 parser_addlocal(parser, var->name, (ast_expression*)var);
5643 for (i = 0; i < 3; ++i) {
5644 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5645 ast_block_collect(localblock, (ast_expression*)me[i]);
5651 memcpy(last_me, me, sizeof(me));
5652 me[0] = me[1] = me[2] = NULL;
5657 if (var->expression.vtype == TYPE_ARRAY) {
5658 if (var->expression.count != (size_t)-1) {
5659 if (!create_array_accessors(parser, var))
5663 else if (!localblock && !nofields &&
5664 var->expression.vtype == TYPE_FIELD &&
5665 var->expression.next->vtype == TYPE_ARRAY)
5668 ast_expression *telem;
5670 ast_value *array = (ast_value*)var->expression.next;
5672 if (!ast_istype(var->expression.next, ast_value)) {
5673 parseerror(parser, "internal error: field element type must be an ast_value");
5677 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5678 if (!parser_create_array_field_setter(parser, array, name))
5681 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5682 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5683 tfield->expression.next = telem;
5684 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5685 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5693 if (parser->tok == ';') {
5694 ast_delete(basetype);
5695 if (!parser_next(parser)) {
5696 parseerror(parser, "error after variable declaration");
5702 if (parser->tok == ',')
5706 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5709 parseerror(parser, "missing comma or semicolon while parsing variables");
5713 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5714 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5715 "initializing expression turns variable `%s` into a constant in this standard",
5722 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5723 if (parser->tok != '=') {
5724 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5728 if (!parser_next(parser)) {
5729 parseerror(parser, "error parsing initializer");
5733 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5734 parseerror(parser, "expected '=' before function body in this standard");
5737 if (parser->tok == '#') {
5738 ast_function *func = NULL;
5739 ast_value *number = NULL;
5745 parseerror(parser, "cannot declare builtins within functions");
5748 if (var->expression.vtype != TYPE_FUNCTION) {
5749 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5752 if (!parser_next(parser)) {
5753 parseerror(parser, "expected builtin number");
5757 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5758 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5760 parseerror(parser, "builtin number expected");
5763 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5766 parseerror(parser, "builtin number must be a compile time constant");
5769 if (number->expression.vtype == TYPE_INTEGER)
5770 builtin_num = number->constval.vint;
5771 else if (number->expression.vtype == TYPE_FLOAT)
5772 builtin_num = number->constval.vfloat;
5775 parseerror(parser, "builtin number must be an integer constant");
5780 fractional = modff(builtin_num, &integral);
5781 if (builtin_num < 0 || fractional != 0) {
5782 parseerror(parser, "builtin number must be an integer greater than zero");
5786 /* we only want the integral part anyways */
5787 builtin_num = integral;
5788 } else if (parser->tok == TOKEN_INTCONST) {
5789 builtin_num = parser_token(parser)->constval.i;
5791 parseerror(parser, "builtin number must be a compile time constant");
5795 if (var->hasvalue) {
5796 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5797 "builtin `%s` has already been defined\n"
5798 " -> previous declaration here: %s:%i",
5799 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5803 func = ast_function_new(ast_ctx(var), var->name, var);
5805 parseerror(parser, "failed to allocate function for `%s`", var->name);
5808 vec_push(parser->functions, func);
5810 func->builtin = -builtin_num-1;
5813 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5814 ? (parser->tok != ',' && parser->tok != ';')
5815 : (!parser_next(parser)))
5817 parseerror(parser, "expected comma or semicolon");
5819 ast_function_delete(func);
5820 var->constval.vfunc = NULL;
5824 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5827 /* Note that fteqcc and most others don't even *have*
5828 * local arrays, so this is not a high priority.
5830 parseerror(parser, "TODO: initializers for local arrays");
5834 var->hasvalue = true;
5835 if (!parse_array(parser, var))
5838 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5841 parseerror(parser, "cannot declare functions within functions");
5846 ast_ctx(proto) = parser_ctx(parser);
5848 if (!parse_function_body(parser, var))
5850 ast_delete(basetype);
5851 for (i = 0; i < vec_size(parser->gotos); ++i)
5852 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5853 vec_free(parser->gotos);
5854 vec_free(parser->labels);
5857 ast_expression *cexp;
5859 bool folded_const = false;
5861 cexp = parse_expression_leave(parser, true, false, false);
5864 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : NULL;
5866 /* deal with foldable constants: */
5868 var->cvq == CV_CONST && cval && cval->hasvalue && cval->cvq == CV_CONST && !cval->isfield)
5870 /* remove it from the current locals */
5872 for (i = 0; i < 3; ++i) {
5873 vec_pop(parser->_locals);
5874 vec_pop(localblock->collect);
5877 /* do sanity checking, this function really needs refactoring */
5878 if (vec_last(parser->_locals) != (ast_expression*)var)
5879 parseerror(parser, "internal error: unexpected change in local variable handling");
5881 vec_pop(parser->_locals);
5882 if (vec_last(localblock->locals) != var)
5883 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5885 vec_pop(localblock->locals);
5886 /* push it to the to-be-generated globals */
5887 vec_push(parser->globals, (ast_expression*)var);
5889 for (i = 0; i < 3; ++i)
5890 vec_push(parser->globals, (ast_expression*)last_me[i]);
5891 folded_const = true;
5894 if (folded_const || !localblock || is_static) {
5895 if (cval != parser->nil &&
5896 (!cval || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5899 parseerror(parser, "initializer is non constant");
5904 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5905 qualifier != CV_VAR)
5907 var->cvq = CV_CONST;
5909 if (cval == parser->nil)
5910 var->expression.flags |= AST_FLAG_INITIALIZED;
5913 var->hasvalue = true;
5914 if (cval->expression.vtype == TYPE_STRING)
5915 var->constval.vstring = parser_strdup(cval->constval.vstring);
5916 else if (cval->expression.vtype == TYPE_FIELD)
5917 var->constval.vfield = cval;
5919 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5925 shunt sy = { NULL, NULL, NULL, NULL };
5928 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5929 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5930 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5931 if (!parser_sy_apply_operator(parser, &sy))
5934 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5935 parseerror(parser, "internal error: leaked operands");
5936 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5944 /* a constant initialized to an inexact value should be marked inexact:
5945 * const float x = <inexact>; should propagate the inexact flag
5947 if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5948 if (cval && cval->hasvalue && cval->cvq == CV_CONST)
5949 var->inexact = cval->inexact;
5954 if (parser->tok == ',') {
5955 if (!parser_next(parser)) {
5956 parseerror(parser, "expected another variable");
5960 if (parser->tok != TOKEN_IDENT) {
5961 parseerror(parser, "expected another variable");
5964 var = ast_value_copy(basetype);
5966 ast_value_set_name(var, parser_tokval(parser));
5967 if (!parser_next(parser)) {
5968 parseerror(parser, "error parsing variable declaration");
5974 if (parser->tok != ';') {
5975 parseerror(parser, "missing semicolon after variables");
5979 if (!parser_next(parser)) {
5980 parseerror(parser, "parse error after variable declaration");
5984 ast_delete(basetype);
5988 if (cleanvar && var)
5990 ast_delete(basetype);
5994 ast_delete(basetype);
5995 if (cleanvar && var)
5997 if (me[0]) ast_member_delete(me[0]);
5998 if (me[1]) ast_member_delete(me[1]);
5999 if (me[2]) ast_member_delete(me[2]);
6003 static bool parser_global_statement(parser_t *parser)
6007 bool is_static = false;
6008 uint32_t qflags = 0;
6009 ast_value *istype = NULL;
6010 char *vstring = NULL;
6012 if (parser->tok == TOKEN_IDENT)
6013 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6015 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
6017 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6019 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6021 if (cvq == CV_WRONG)
6023 return parse_variable(parser, NULL, false, cvq, NULL, noref, is_static, qflags, vstring);
6025 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6027 return parse_enum(parser);
6029 else if (parser->tok == TOKEN_KEYWORD)
6031 if (!strcmp(parser_tokval(parser), "typedef")) {
6032 if (!parser_next(parser)) {
6033 parseerror(parser, "expected type definition after 'typedef'");
6036 return parse_typedef(parser);
6038 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6041 else if (parser->tok == '#')
6043 return parse_pragma(parser);
6045 else if (parser->tok == '$')
6047 if (!parser_next(parser)) {
6048 parseerror(parser, "parse error");
6054 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6060 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6062 return util_crc16(old, str, strlen(str));
6065 static void progdefs_crc_file(const char *str)
6067 /* write to progdefs.h here */
6071 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6073 old = progdefs_crc_sum(old, str);
6074 progdefs_crc_file(str);
6078 static void generate_checksum(parser_t *parser, ir_builder *ir)
6080 uint16_t crc = 0xFFFF;
6084 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6085 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6087 progdefs_crc_file("\tint\tpad;\n");
6088 progdefs_crc_file("\tint\tofs_return[3];\n");
6089 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6090 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6091 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6092 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6093 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6094 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6095 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6096 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6098 for (i = 0; i < parser->crc_globals; ++i) {
6099 if (!ast_istype(parser->globals[i], ast_value))
6101 value = (ast_value*)(parser->globals[i]);
6102 switch (value->expression.vtype) {
6103 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6104 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6105 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6106 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6108 crc = progdefs_crc_both(crc, "\tint\t");
6111 crc = progdefs_crc_both(crc, value->name);
6112 crc = progdefs_crc_both(crc, ";\n");
6114 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6115 for (i = 0; i < parser->crc_fields; ++i) {
6116 if (!ast_istype(parser->fields[i], ast_value))
6118 value = (ast_value*)(parser->fields[i]);
6119 switch (value->expression.next->vtype) {
6120 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6121 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6122 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6123 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6125 crc = progdefs_crc_both(crc, "\tint\t");
6128 crc = progdefs_crc_both(crc, value->name);
6129 crc = progdefs_crc_both(crc, ";\n");
6131 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6132 ir->code->crc = crc;
6135 parser_t *parser_create()
6138 lex_ctx_t empty_ctx;
6141 parser = (parser_t*)mem_a(sizeof(parser_t));
6145 memset(parser, 0, sizeof(*parser));
6147 for (i = 0; i < operator_count; ++i) {
6148 if (operators[i].id == opid1('=')) {
6149 parser->assign_op = operators+i;
6153 if (!parser->assign_op) {
6154 con_err("internal error: initializing parser: failed to find assign operator\n");
6159 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6160 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6161 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6162 vec_push(parser->_blocktypedefs, 0);
6164 parser->aliases = util_htnew(PARSER_HT_SIZE);
6167 vec_push(parser->correct_variables, correct_trie_new());
6168 vec_push(parser->correct_variables_score, NULL);
6170 empty_ctx.file = "<internal>";
6172 empty_ctx.column = 0;
6173 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6174 parser->nil->cvq = CV_CONST;
6175 if (OPTS_FLAG(UNTYPED_NIL))
6176 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6178 parser->max_param_count = 1;
6180 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6181 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6182 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6184 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6185 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6186 parser->reserved_version->cvq = CV_CONST;
6187 parser->reserved_version->hasvalue = true;
6188 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6189 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6191 parser->reserved_version = NULL;
6194 parser->fold = fold_init (parser);
6195 parser->intrin = intrin_init(parser);
6199 static bool parser_compile(parser_t *parser)
6201 /* initial lexer/parser state */
6202 parser->lex->flags.noops = true;
6204 if (parser_next(parser))
6206 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6208 if (!parser_global_statement(parser)) {
6209 if (parser->tok == TOKEN_EOF)
6210 parseerror(parser, "unexpected end of file");
6211 else if (compile_errors)
6212 parseerror(parser, "there have been errors, bailing out");
6213 lex_close(parser->lex);
6219 parseerror(parser, "parse error");
6220 lex_close(parser->lex);
6225 lex_close(parser->lex);
6228 return !compile_errors;
6231 bool parser_compile_file(parser_t *parser, const char *filename)
6233 parser->lex = lex_open(filename);
6235 con_err("failed to open file \"%s\"\n", filename);
6238 return parser_compile(parser);
6241 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6243 parser->lex = lex_open_string(str, len, name);
6245 con_err("failed to create lexer for string \"%s\"\n", name);
6248 return parser_compile(parser);
6251 static void parser_remove_ast(parser_t *parser)
6254 if (parser->ast_cleaned)
6256 parser->ast_cleaned = true;
6257 for (i = 0; i < vec_size(parser->accessors); ++i) {
6258 ast_delete(parser->accessors[i]->constval.vfunc);
6259 parser->accessors[i]->constval.vfunc = NULL;
6260 ast_delete(parser->accessors[i]);
6262 for (i = 0; i < vec_size(parser->functions); ++i) {
6263 ast_delete(parser->functions[i]);
6265 for (i = 0; i < vec_size(parser->fields); ++i) {
6266 ast_delete(parser->fields[i]);
6268 for (i = 0; i < vec_size(parser->globals); ++i) {
6269 ast_delete(parser->globals[i]);
6271 vec_free(parser->accessors);
6272 vec_free(parser->functions);
6273 vec_free(parser->globals);
6274 vec_free(parser->fields);
6276 for (i = 0; i < vec_size(parser->variables); ++i)
6277 util_htdel(parser->variables[i]);
6278 vec_free(parser->variables);
6279 vec_free(parser->_blocklocals);
6280 vec_free(parser->_locals);
6283 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6284 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6286 vec_free(parser->correct_variables);
6287 vec_free(parser->correct_variables_score);
6289 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6290 ast_delete(parser->_typedefs[i]);
6291 vec_free(parser->_typedefs);
6292 for (i = 0; i < vec_size(parser->typedefs); ++i)
6293 util_htdel(parser->typedefs[i]);
6294 vec_free(parser->typedefs);
6295 vec_free(parser->_blocktypedefs);
6297 vec_free(parser->_block_ctx);
6299 vec_free(parser->labels);
6300 vec_free(parser->gotos);
6301 vec_free(parser->breaks);
6302 vec_free(parser->continues);
6304 ast_value_delete(parser->nil);
6306 ast_value_delete(parser->const_vec[0]);
6307 ast_value_delete(parser->const_vec[1]);
6308 ast_value_delete(parser->const_vec[2]);
6310 if (parser->reserved_version)
6311 ast_value_delete(parser->reserved_version);
6313 util_htdel(parser->aliases);
6314 fold_cleanup(parser->fold);
6315 intrin_cleanup(parser->intrin);
6318 void parser_cleanup(parser_t *parser)
6320 parser_remove_ast(parser);
6324 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6326 ast_expression *expr;
6330 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6334 for (i = 0; i != vec_size(parser->functions); ++i) {
6335 if (!strcmp(parser->functions[i]->name, "coverage")) {
6336 func = parser->functions[i];
6341 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6342 con_out("coverage support requested but no coverage() builtin declared\n");
6343 ir_builder_delete(ir);
6350 expr = (ast_expression*)cov;
6352 if (expr->vtype != TYPE_FUNCTION || vec_size(expr->params) != 0) {
6354 ast_type_to_string(expr, ty, sizeof(ty));
6355 con_out("invalid type for coverage(): %s\n", ty);
6356 ir_builder_delete(ir);
6360 ir->coverage_func = func->ir_func->value;
6364 bool parser_finish(parser_t *parser, const char *output)
6370 if (compile_errors) {
6371 con_out("*** there were compile errors\n");
6375 ir = ir_builder_new("gmqcc_out");
6377 con_out("failed to allocate builder\n");
6381 for (i = 0; i < vec_size(parser->fields); ++i) {
6384 if (!ast_istype(parser->fields[i], ast_value))
6386 field = (ast_value*)parser->fields[i];
6387 hasvalue = field->hasvalue;
6388 field->hasvalue = false;
6389 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6390 con_out("failed to generate field %s\n", field->name);
6391 ir_builder_delete(ir);
6396 ast_expression *subtype;
6397 field->hasvalue = true;
6398 subtype = field->expression.next;
6399 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6400 if (subtype->vtype == TYPE_FIELD)
6401 ifld->fieldtype = subtype->next->vtype;
6402 else if (subtype->vtype == TYPE_FUNCTION)
6403 ifld->outtype = subtype->next->vtype;
6404 (void)!ir_value_set_field(field->ir_v, ifld);
6407 for (i = 0; i < vec_size(parser->globals); ++i) {
6409 if (!ast_istype(parser->globals[i], ast_value))
6411 asvalue = (ast_value*)(parser->globals[i]);
6412 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6413 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6414 "unused global: `%s`", asvalue->name);
6416 if (!ast_global_codegen(asvalue, ir, false)) {
6417 con_out("failed to generate global %s\n", asvalue->name);
6418 ir_builder_delete(ir);
6422 /* Build function vararg accessor ast tree now before generating
6423 * immediates, because the accessors may add new immediates
6425 for (i = 0; i < vec_size(parser->functions); ++i) {
6426 ast_function *f = parser->functions[i];
6428 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6429 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6430 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6431 con_out("failed to generate vararg setter for %s\n", f->name);
6432 ir_builder_delete(ir);
6435 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6436 con_out("failed to generate vararg getter for %s\n", f->name);
6437 ir_builder_delete(ir);
6441 ast_delete(f->varargs);
6446 /* Now we can generate immediates */
6447 if (!fold_generate(parser->fold, ir))
6450 /* before generating any functions we need to set the coverage_func */
6451 if (!parser_set_coverage_func(parser, ir))
6454 for (i = 0; i < vec_size(parser->globals); ++i) {
6456 if (!ast_istype(parser->globals[i], ast_value))
6458 asvalue = (ast_value*)(parser->globals[i]);
6459 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6461 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6462 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6463 "uninitialized constant: `%s`",
6465 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6466 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6467 "uninitialized global: `%s`",
6470 if (!ast_generate_accessors(asvalue, ir)) {
6471 ir_builder_delete(ir);
6475 for (i = 0; i < vec_size(parser->fields); ++i) {
6477 asvalue = (ast_value*)(parser->fields[i]->next);
6479 if (!ast_istype((ast_expression*)asvalue, ast_value))
6481 if (asvalue->expression.vtype != TYPE_ARRAY)
6483 if (!ast_generate_accessors(asvalue, ir)) {
6484 ir_builder_delete(ir);
6488 if (parser->reserved_version &&
6489 !ast_global_codegen(parser->reserved_version, ir, false))
6491 con_out("failed to generate reserved::version");
6492 ir_builder_delete(ir);
6495 for (i = 0; i < vec_size(parser->functions); ++i) {
6496 ast_function *f = parser->functions[i];
6497 if (!ast_function_codegen(f, ir)) {
6498 con_out("failed to generate function %s\n", f->name);
6499 ir_builder_delete(ir);
6504 generate_checksum(parser, ir);
6506 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6507 ir_builder_dump(ir, con_out);
6508 for (i = 0; i < vec_size(parser->functions); ++i) {
6509 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6510 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6511 ir_builder_delete(ir);
6515 parser_remove_ast(parser);
6517 if (compile_Werrors) {
6518 con_out("*** there were warnings treated as errors\n");
6519 compile_show_werrors();
6524 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6525 ir_builder_dump(ir, con_out);
6527 if (!ir_builder_generate(ir, output)) {
6528 con_out("*** failed to generate output file\n");
6529 ir_builder_delete(ir);
6533 ir_builder_delete(ir);