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 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
958 case opid3('+','+','P'):
959 case opid3('-','-','P'):
961 if (exprs[0]->vtype != TYPE_FLOAT) {
962 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
963 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
966 if (op->id == opid3('+','+','P'))
970 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
971 if (ast_istype(exprs[0], ast_entfield)) {
972 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
974 (ast_expression*)parser->fold->imm_float[1]);
976 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
978 (ast_expression*)parser->fold->imm_float[1]);
981 case opid3('S','+','+'):
982 case opid3('S','-','-'):
984 if (exprs[0]->vtype != TYPE_FLOAT) {
985 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
986 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
989 if (op->id == opid3('S','+','+')) {
996 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
997 if (ast_istype(exprs[0], ast_entfield)) {
998 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1000 (ast_expression*)parser->fold->imm_float[1]);
1002 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1004 (ast_expression*)parser->fold->imm_float[1]);
1008 out = fold_binary(ctx, subop,
1010 (ast_expression*)parser->fold->imm_float[1]);
1013 case opid2('+','='):
1014 case opid2('-','='):
1015 if (exprs[0]->vtype != exprs[1]->vtype ||
1016 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1018 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1019 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1020 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1024 (void)check_write_to(ctx, exprs[0]);
1025 if (ast_istype(exprs[0], ast_entfield))
1026 assignop = type_storep_instr[exprs[0]->vtype];
1028 assignop = type_store_instr[exprs[0]->vtype];
1029 switch (exprs[0]->vtype) {
1031 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1032 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1033 exprs[0], exprs[1]);
1036 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1037 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1038 exprs[0], exprs[1]);
1041 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1042 type_name[exprs[0]->vtype],
1043 type_name[exprs[1]->vtype]);
1047 case opid2('*','='):
1048 case opid2('/','='):
1049 if (exprs[1]->vtype != TYPE_FLOAT ||
1050 !(exprs[0]->vtype == TYPE_FLOAT ||
1051 exprs[0]->vtype == TYPE_VECTOR))
1053 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1054 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1055 compile_error(ctx, "invalid types used in expression: %s and %s",
1059 (void)check_write_to(ctx, exprs[0]);
1060 if (ast_istype(exprs[0], ast_entfield))
1061 assignop = type_storep_instr[exprs[0]->vtype];
1063 assignop = type_store_instr[exprs[0]->vtype];
1064 switch (exprs[0]->vtype) {
1066 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1067 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1068 exprs[0], exprs[1]);
1071 if (op->id == opid2('*','=')) {
1072 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1073 exprs[0], exprs[1]);
1075 out = fold_binary(ctx, INSTR_DIV_F,
1076 (ast_expression*)parser->fold->imm_float[1],
1079 compile_error(ctx, "internal error: failed to generate division");
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1087 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1088 type_name[exprs[0]->vtype],
1089 type_name[exprs[1]->vtype]);
1093 case opid2('&','='):
1094 case opid2('|','='):
1095 case opid2('^','='):
1096 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1097 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1098 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1099 compile_error(ctx, "invalid types used in expression: %s and %s",
1103 (void)check_write_to(ctx, exprs[0]);
1104 if (ast_istype(exprs[0], ast_entfield))
1105 assignop = type_storep_instr[exprs[0]->vtype];
1107 assignop = type_store_instr[exprs[0]->vtype];
1108 if (exprs[0]->vtype == TYPE_FLOAT)
1109 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1110 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1111 exprs[0], exprs[1]);
1113 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1114 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1115 exprs[0], exprs[1]);
1117 case opid3('&','~','='):
1118 /* This is like: a &= ~(b);
1119 * But QC has no bitwise-not, so we implement it as
1122 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1123 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1124 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1125 compile_error(ctx, "invalid types used in expression: %s and %s",
1129 if (ast_istype(exprs[0], ast_entfield))
1130 assignop = type_storep_instr[exprs[0]->vtype];
1132 assignop = type_store_instr[exprs[0]->vtype];
1133 if (exprs[0]->vtype == TYPE_FLOAT)
1134 out = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1136 out = fold_binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1139 (void)check_write_to(ctx, exprs[0]);
1140 if (exprs[0]->vtype == TYPE_FLOAT)
1141 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1143 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1144 asbinstore->keep_dest = true;
1145 out = (ast_expression*)asbinstore;
1148 case opid2('~', 'P'):
1149 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1150 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1151 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1154 if (!(out = fold_op(parser->fold, op, exprs))) {
1155 if (exprs[0]->vtype == TYPE_FLOAT) {
1156 out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1158 out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1165 compile_error(ctx, "failed to apply operator %s", op->op);
1169 vec_push(sy->out, syexp(ctx, out));
1173 static bool parser_close_call(parser_t *parser, shunt *sy)
1175 /* was a function call */
1176 ast_expression *fun;
1177 ast_value *funval = NULL;
1181 size_t paramcount, i;
1184 fid = vec_last(sy->ops).off;
1185 vec_shrinkby(sy->ops, 1);
1187 /* out[fid] is the function
1188 * everything above is parameters...
1190 if (!vec_size(sy->argc)) {
1191 parseerror(parser, "internal error: no argument counter available");
1195 paramcount = vec_last(sy->argc);
1198 if (vec_size(sy->out) < fid) {
1199 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1200 (unsigned long)vec_size(sy->out),
1202 (unsigned long)paramcount);
1207 * TODO handle this at the intrinsic level with an ast_intrinsic
1210 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1212 if (fid+2 != vec_size(sy->out) ||
1213 vec_last(sy->out).block)
1215 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1218 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1219 ast_unref(vec_last(sy->out).out);
1220 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1221 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1222 vec_shrinkby(sy->out, 1);
1227 * Now we need to determine if the function that is being called is
1228 * an intrinsic so we can evaluate if the arguments to it are constant
1229 * and than fruitfully fold them.
1231 #define fold_can_1(X) \
1232 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1233 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1235 if (fid + 1 < vec_size(sy->out))
1238 for (i = 0; i < paramcount; ++i) {
1239 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1246 * All is well which ends well, if we make it into here we can ignore the
1247 * intrinsic call and just evaluate it i.e constant fold it.
1249 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1250 ast_expression **exprs = NULL;
1251 ast_expression *foldval = NULL;
1253 for (i = 0; i < paramcount; i++)
1254 vec_push(exprs, sy->out[fid+1 + i].out);
1256 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1262 * Blub: what sorts of unreffing and resizing of
1263 * sy->out should I be doing here?
1265 sy->out[fid] = syexp(foldval->node.context, foldval);
1266 vec_shrinkby(sy->out, paramcount);
1273 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1278 if (fid+1 + paramcount != vec_size(sy->out)) {
1279 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1280 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1284 for (i = 0; i < paramcount; ++i)
1285 vec_push(call->params, sy->out[fid+1 + i].out);
1286 vec_shrinkby(sy->out, paramcount);
1287 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1288 if (parser->max_param_count < paramcount)
1289 parser->max_param_count = paramcount;
1291 if (ast_istype(fun, ast_value)) {
1292 funval = (ast_value*)fun;
1293 if ((fun->flags & AST_FLAG_VARIADIC) &&
1294 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1296 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount, false);
1300 /* overwrite fid, the function, with a call */
1301 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1303 if (fun->vtype != TYPE_FUNCTION) {
1304 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1309 parseerror(parser, "could not determine function return type");
1312 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1314 if (fun->flags & AST_FLAG_DEPRECATED) {
1316 return !parsewarning(parser, WARN_DEPRECATED,
1317 "call to function (which is marked deprecated)\n",
1318 "-> it has been declared here: %s:%i",
1319 ast_ctx(fun).file, ast_ctx(fun).line);
1322 return !parsewarning(parser, WARN_DEPRECATED,
1323 "call to `%s` (which is marked deprecated)\n"
1324 "-> `%s` declared here: %s:%i",
1325 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1327 return !parsewarning(parser, WARN_DEPRECATED,
1328 "call to `%s` (deprecated: %s)\n"
1329 "-> `%s` declared here: %s:%i",
1330 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1334 if (vec_size(fun->params) != paramcount &&
1335 !((fun->flags & AST_FLAG_VARIADIC) &&
1336 vec_size(fun->params) < paramcount))
1338 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1340 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1341 "too %s parameters for call to %s: expected %i, got %i\n"
1342 " -> `%s` has been declared here: %s:%i",
1343 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1344 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1346 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1347 "too %s parameters for function call: expected %i, got %i\n"
1348 " -> it has been declared here: %s:%i",
1349 fewmany, (int)vec_size(fun->params), (int)paramcount,
1350 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1357 static bool parser_close_paren(parser_t *parser, shunt *sy)
1359 if (!vec_size(sy->ops)) {
1360 parseerror(parser, "unmatched closing paren");
1364 while (vec_size(sy->ops)) {
1365 if (vec_last(sy->ops).isparen) {
1366 if (vec_last(sy->paren) == PAREN_FUNC) {
1368 if (!parser_close_call(parser, sy))
1372 if (vec_last(sy->paren) == PAREN_EXPR) {
1374 if (!vec_size(sy->out)) {
1375 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1376 vec_shrinkby(sy->ops, 1);
1379 vec_shrinkby(sy->ops, 1);
1382 if (vec_last(sy->paren) == PAREN_INDEX) {
1384 /* pop off the parenthesis */
1385 vec_shrinkby(sy->ops, 1);
1386 /* then apply the index operator */
1387 if (!parser_sy_apply_operator(parser, sy))
1391 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1392 vec_last(sy->paren) = PAREN_TERNARY2;
1393 /* pop off the parenthesis */
1394 vec_shrinkby(sy->ops, 1);
1397 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1400 if (!parser_sy_apply_operator(parser, sy))
1406 static void parser_reclassify_token(parser_t *parser)
1409 if (parser->tok >= TOKEN_START)
1411 for (i = 0; i < operator_count; ++i) {
1412 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1413 parser->tok = TOKEN_OPERATOR;
1419 static ast_expression* parse_vararg_do(parser_t *parser)
1421 ast_expression *idx, *out;
1423 ast_value *funtype = parser->function->vtype;
1424 lex_ctx_t ctx = parser_ctx(parser);
1426 if (!parser->function->varargs) {
1427 parseerror(parser, "function has no variable argument list");
1431 if (!parser_next(parser) || parser->tok != '(') {
1432 parseerror(parser, "expected parameter index and type in parenthesis");
1435 if (!parser_next(parser)) {
1436 parseerror(parser, "error parsing parameter index");
1440 idx = parse_expression_leave(parser, true, false, false);
1444 if (parser->tok != ',') {
1445 if (parser->tok != ')') {
1447 parseerror(parser, "expected comma after parameter index");
1450 /* vararg piping: ...(start) */
1451 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1455 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1457 parseerror(parser, "expected typename for vararg");
1461 typevar = parse_typename(parser, NULL, NULL, NULL);
1467 if (parser->tok != ')') {
1469 ast_delete(typevar);
1470 parseerror(parser, "expected closing paren");
1474 if (funtype->expression.varparam &&
1475 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1479 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1480 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1481 compile_error(ast_ctx(typevar),
1482 "function was declared to take varargs of type `%s`, requested type is: %s",
1486 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1487 ast_type_adopt(out, typevar);
1488 ast_delete(typevar);
1492 static ast_expression* parse_vararg(parser_t *parser)
1494 bool old_noops = parser->lex->flags.noops;
1496 ast_expression *out;
1498 parser->lex->flags.noops = true;
1499 out = parse_vararg_do(parser);
1501 parser->lex->flags.noops = old_noops;
1505 /* not to be exposed */
1506 bool ftepp_predef_exists(const char *name);
1507 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1509 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1510 parser->tok == TOKEN_IDENT &&
1511 !strcmp(parser_tokval(parser), "_"))
1513 /* a translatable string */
1516 parser->lex->flags.noops = true;
1517 if (!parser_next(parser) || parser->tok != '(') {
1518 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1521 parser->lex->flags.noops = false;
1522 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1523 parseerror(parser, "expected a constant string in translatable-string extension");
1526 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1529 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1531 if (!parser_next(parser) || parser->tok != ')') {
1532 parseerror(parser, "expected closing paren after translatable string");
1537 else if (parser->tok == TOKEN_DOTS)
1540 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1541 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1544 va = parse_vararg(parser);
1547 vec_push(sy->out, syexp(parser_ctx(parser), va));
1550 else if (parser->tok == TOKEN_FLOATCONST) {
1551 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f), false);
1554 vec_push(sy->out, syexp(parser_ctx(parser), val));
1557 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1558 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i), false);
1561 vec_push(sy->out, syexp(parser_ctx(parser), val));
1564 else if (parser->tok == TOKEN_STRINGCONST) {
1565 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1568 vec_push(sy->out, syexp(parser_ctx(parser), val));
1571 else if (parser->tok == TOKEN_VECTORCONST) {
1572 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1575 vec_push(sy->out, syexp(parser_ctx(parser), val));
1578 else if (parser->tok == TOKEN_IDENT)
1580 const char *ctoken = parser_tokval(parser);
1581 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1582 ast_expression *var;
1583 /* a_vector.{x,y,z} */
1584 if (!vec_size(sy->ops) ||
1585 !vec_last(sy->ops).etype ||
1586 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1588 /* When adding more intrinsics, fix the above condition */
1591 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1593 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1595 var = parser_find_var(parser, parser_tokval(parser));
1597 var = parser_find_field(parser, parser_tokval(parser));
1599 if (!var && with_labels) {
1600 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1602 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1603 var = (ast_expression*)lbl;
1604 vec_push(parser->labels, lbl);
1607 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1608 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1611 * now we try for the real intrinsic hashtable. If the string
1612 * begins with __builtin, we simply skip past it, otherwise we
1613 * use the identifier as is.
1615 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1616 var = intrin_func(parser->intrin, parser_tokval(parser));
1620 * Try it again, intrin_func deals with the alias method as well
1621 * the first one masks for __builtin though, we emit warning here.
1624 if ((var = intrin_func(parser->intrin, parser_tokval(parser)))) {
1625 (void)!compile_warning(
1628 "using implicitly defined builtin `__builtin_%s' for `%s'",
1629 parser_tokval(parser),
1630 parser_tokval(parser)
1637 char *correct = NULL;
1641 * sometimes people use preprocessing predefs without enabling them
1642 * i've done this thousands of times already myself. Lets check for
1643 * it in the predef table. And diagnose it better :)
1645 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1646 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1651 * TODO: determine the best score for the identifier: be it
1652 * a variable, a field.
1654 * We should also consider adding correction tables for
1655 * other things as well.
1657 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1659 correct_init(&corr);
1661 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1662 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1663 if (strcmp(correct, parser_tokval(parser))) {
1670 correct_free(&corr);
1673 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1678 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1684 if (ast_istype(var, ast_value)) {
1685 ((ast_value*)var)->uses++;
1687 else if (ast_istype(var, ast_member)) {
1688 ast_member *mem = (ast_member*)var;
1689 if (ast_istype(mem->owner, ast_value))
1690 ((ast_value*)(mem->owner))->uses++;
1693 vec_push(sy->out, syexp(parser_ctx(parser), var));
1696 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1700 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1702 ast_expression *expr = NULL;
1705 bool wantop = false;
1706 /* only warn once about an assignment in a truth value because the current code
1707 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1709 bool warn_parenthesis = true;
1711 /* count the parens because an if starts with one, so the
1712 * end of a condition is an unmatched closing paren
1716 memset(&sy, 0, sizeof(sy));
1718 parser->lex->flags.noops = false;
1720 parser_reclassify_token(parser);
1724 if (parser->tok == TOKEN_TYPENAME) {
1725 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1729 if (parser->tok == TOKEN_OPERATOR)
1731 /* classify the operator */
1732 const oper_info *op;
1733 const oper_info *olast = NULL;
1735 for (o = 0; o < operator_count; ++o) {
1736 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1737 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1738 !strcmp(parser_tokval(parser), operators[o].op))
1743 if (o == operator_count) {
1744 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1747 /* found an operator */
1750 /* when declaring variables, a comma starts a new variable */
1751 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1752 /* fixup the token */
1757 /* a colon without a pervious question mark cannot be a ternary */
1758 if (!ternaries && op->id == opid2(':','?')) {
1763 if (op->id == opid1(',')) {
1764 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1765 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1769 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1770 olast = &operators[vec_last(sy.ops).etype-1];
1772 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1773 while (olast && op->prec < olast->prec)
1775 if (!parser_sy_apply_operator(parser, &sy))
1777 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1778 olast = &operators[vec_last(sy.ops).etype-1];
1783 #define IsAssignOp(x) (\
1784 (x) == opid1('=') || \
1785 (x) == opid2('+','=') || \
1786 (x) == opid2('-','=') || \
1787 (x) == opid2('*','=') || \
1788 (x) == opid2('/','=') || \
1789 (x) == opid2('%','=') || \
1790 (x) == opid2('&','=') || \
1791 (x) == opid2('|','=') || \
1792 (x) == opid3('&','~','=') \
1794 if (warn_parenthesis) {
1795 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1796 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1797 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1800 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1801 warn_parenthesis = false;
1804 if (olast && olast->id != op->id) {
1805 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1806 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1808 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1809 warn_parenthesis = false;
1811 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1812 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1814 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1815 warn_parenthesis = false;
1821 (op->prec < olast->prec) ||
1822 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1824 if (!parser_sy_apply_operator(parser, &sy))
1826 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1827 olast = &operators[vec_last(sy.ops).etype-1];
1832 if (op->id == opid1('(')) {
1834 size_t sycount = vec_size(sy.out);
1835 /* we expected an operator, this is the function-call operator */
1836 vec_push(sy.paren, PAREN_FUNC);
1837 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1838 vec_push(sy.argc, 0);
1840 vec_push(sy.paren, PAREN_EXPR);
1841 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1844 } else if (op->id == opid1('[')) {
1846 parseerror(parser, "unexpected array subscript");
1849 vec_push(sy.paren, PAREN_INDEX);
1850 /* push both the operator and the paren, this makes life easier */
1851 vec_push(sy.ops, syop(parser_ctx(parser), op));
1852 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1854 } else if (op->id == opid2('?',':')) {
1855 vec_push(sy.ops, syop(parser_ctx(parser), op));
1856 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1859 vec_push(sy.paren, PAREN_TERNARY1);
1860 } else if (op->id == opid2(':','?')) {
1861 if (!vec_size(sy.paren)) {
1862 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1865 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1866 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1869 if (!parser_close_paren(parser, &sy))
1871 vec_push(sy.ops, syop(parser_ctx(parser), op));
1875 vec_push(sy.ops, syop(parser_ctx(parser), op));
1876 wantop = !!(op->flags & OP_SUFFIX);
1879 else if (parser->tok == ')') {
1880 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1881 if (!parser_sy_apply_operator(parser, &sy))
1884 if (!vec_size(sy.paren))
1887 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1888 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1891 if (!parser_close_paren(parser, &sy))
1894 /* must be a function call without parameters */
1895 if (vec_last(sy.paren) != PAREN_FUNC) {
1896 parseerror(parser, "closing paren in invalid position");
1899 if (!parser_close_paren(parser, &sy))
1904 else if (parser->tok == '(') {
1905 parseerror(parser, "internal error: '(' should be classified as operator");
1908 else if (parser->tok == '[') {
1909 parseerror(parser, "internal error: '[' should be classified as operator");
1912 else if (parser->tok == ']') {
1913 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1914 if (!parser_sy_apply_operator(parser, &sy))
1917 if (!vec_size(sy.paren))
1919 if (vec_last(sy.paren) != PAREN_INDEX) {
1920 parseerror(parser, "mismatched parentheses, unexpected ']'");
1923 if (!parser_close_paren(parser, &sy))
1928 if (!parse_sya_operand(parser, &sy, with_labels))
1931 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1932 vec_last(sy.argc)++;
1937 /* in this case we might want to allow constant string concatenation */
1938 bool concatenated = false;
1939 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1940 ast_expression *lexpr = vec_last(sy.out).out;
1941 if (ast_istype(lexpr, ast_value)) {
1942 ast_value *last = (ast_value*)lexpr;
1943 if (last->isimm == true && last->cvq == CV_CONST &&
1944 last->hasvalue && last->expression.vtype == TYPE_STRING)
1946 char *newstr = NULL;
1947 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1948 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1950 concatenated = true;
1954 if (!concatenated) {
1955 parseerror(parser, "expected operator or end of statement");
1960 if (!parser_next(parser)) {
1963 if (parser->tok == ';' ||
1964 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1965 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1971 while (vec_size(sy.ops)) {
1972 if (!parser_sy_apply_operator(parser, &sy))
1976 parser->lex->flags.noops = true;
1977 if (vec_size(sy.out) != 1) {
1978 parseerror(parser, "expression expected");
1981 expr = sy.out[0].out;
1984 if (vec_size(sy.paren)) {
1985 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1993 parser->lex->flags.noops = true;
1994 for (i = 0; i < vec_size(sy.out); ++i) {
1996 ast_unref(sy.out[i].out);
2005 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2007 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2010 if (parser->tok != ';') {
2011 parseerror(parser, "semicolon expected after expression");
2015 if (!parser_next(parser)) {
2022 static void parser_enterblock(parser_t *parser)
2024 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2025 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2026 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2027 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2028 vec_push(parser->_block_ctx, parser_ctx(parser));
2031 vec_push(parser->correct_variables, correct_trie_new());
2032 vec_push(parser->correct_variables_score, NULL);
2035 static bool parser_leaveblock(parser_t *parser)
2038 size_t locals, typedefs;
2040 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2041 parseerror(parser, "internal error: parser_leaveblock with no block");
2045 util_htdel(vec_last(parser->variables));
2046 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2048 vec_pop(parser->variables);
2049 vec_pop(parser->correct_variables);
2050 vec_pop(parser->correct_variables_score);
2051 if (!vec_size(parser->_blocklocals)) {
2052 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2056 locals = vec_last(parser->_blocklocals);
2057 vec_pop(parser->_blocklocals);
2058 while (vec_size(parser->_locals) != locals) {
2059 ast_expression *e = vec_last(parser->_locals);
2060 ast_value *v = (ast_value*)e;
2061 vec_pop(parser->_locals);
2062 if (ast_istype(e, ast_value) && !v->uses) {
2063 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2068 typedefs = vec_last(parser->_blocktypedefs);
2069 while (vec_size(parser->_typedefs) != typedefs) {
2070 ast_delete(vec_last(parser->_typedefs));
2071 vec_pop(parser->_typedefs);
2073 util_htdel(vec_last(parser->typedefs));
2074 vec_pop(parser->typedefs);
2076 vec_pop(parser->_block_ctx);
2081 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2083 vec_push(parser->_locals, e);
2084 util_htset(vec_last(parser->variables), name, (void*)e);
2088 vec_last(parser->correct_variables),
2089 &vec_last(parser->correct_variables_score),
2094 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2096 vec_push(parser->globals, e);
2097 util_htset(parser->htglobals, name, e);
2101 parser->correct_variables[0],
2102 &parser->correct_variables_score[0],
2107 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2111 ast_expression *prev;
2113 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2115 ast_type_to_string(cond, ty, sizeof(ty));
2116 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2119 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2122 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2125 parseerror(parser, "internal error: failed to process condition");
2130 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2132 /* vector types need to be cast to true booleans */
2133 ast_binary *bin = (ast_binary*)cond;
2134 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2136 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2138 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2141 parseerror(parser, "internal error: failed to process condition");
2148 unary = (ast_unary*)cond;
2149 /* ast_istype dereferences cond, should test here for safety */
2150 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2152 cond = unary->operand;
2153 unary->operand = NULL;
2156 unary = (ast_unary*)cond;
2160 parseerror(parser, "internal error: failed to process condition");
2162 if (ifnot) *_ifnot = !*_ifnot;
2166 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2169 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2172 lex_ctx_t ctx = parser_ctx(parser);
2174 (void)block; /* not touching */
2176 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2177 if (!parser_next(parser)) {
2178 parseerror(parser, "expected condition or 'not'");
2181 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2183 if (!parser_next(parser)) {
2184 parseerror(parser, "expected condition in parenthesis");
2188 if (parser->tok != '(') {
2189 parseerror(parser, "expected 'if' condition in parenthesis");
2192 /* parse into the expression */
2193 if (!parser_next(parser)) {
2194 parseerror(parser, "expected 'if' condition after opening paren");
2197 /* parse the condition */
2198 cond = parse_expression_leave(parser, false, true, false);
2202 if (parser->tok != ')') {
2203 parseerror(parser, "expected closing paren after 'if' condition");
2207 /* parse into the 'then' branch */
2208 if (!parser_next(parser)) {
2209 parseerror(parser, "expected statement for on-true branch of 'if'");
2213 if (!parse_statement_or_block(parser, &ontrue)) {
2218 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2219 /* check for an else */
2220 if (!strcmp(parser_tokval(parser), "else")) {
2221 /* parse into the 'else' branch */
2222 if (!parser_next(parser)) {
2223 parseerror(parser, "expected on-false branch after 'else'");
2228 if (!parse_statement_or_block(parser, &onfalse)) {
2235 cond = process_condition(parser, cond, &ifnot);
2237 if (ontrue) ast_delete(ontrue);
2238 if (onfalse) ast_delete(onfalse);
2243 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2245 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2246 *out = (ast_expression*)ifthen;
2250 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2251 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2256 /* skip the 'while' and get the body */
2257 if (!parser_next(parser)) {
2258 if (OPTS_FLAG(LOOP_LABELS))
2259 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2261 parseerror(parser, "expected 'while' condition in parenthesis");
2265 if (parser->tok == ':') {
2266 if (!OPTS_FLAG(LOOP_LABELS))
2267 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2268 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2269 parseerror(parser, "expected loop label");
2272 label = util_strdup(parser_tokval(parser));
2273 if (!parser_next(parser)) {
2275 parseerror(parser, "expected 'while' condition in parenthesis");
2280 if (parser->tok != '(') {
2281 parseerror(parser, "expected 'while' condition in parenthesis");
2285 vec_push(parser->breaks, label);
2286 vec_push(parser->continues, label);
2288 rv = parse_while_go(parser, block, out);
2291 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2292 parseerror(parser, "internal error: label stack corrupted");
2298 vec_pop(parser->breaks);
2299 vec_pop(parser->continues);
2304 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2307 ast_expression *cond, *ontrue;
2311 lex_ctx_t ctx = parser_ctx(parser);
2313 (void)block; /* not touching */
2315 /* parse into the expression */
2316 if (!parser_next(parser)) {
2317 parseerror(parser, "expected 'while' condition after opening paren");
2320 /* parse the condition */
2321 cond = parse_expression_leave(parser, false, true, false);
2325 if (parser->tok != ')') {
2326 parseerror(parser, "expected closing paren after 'while' condition");
2330 /* parse into the 'then' branch */
2331 if (!parser_next(parser)) {
2332 parseerror(parser, "expected while-loop body");
2336 if (!parse_statement_or_block(parser, &ontrue)) {
2341 cond = process_condition(parser, cond, &ifnot);
2346 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2347 *out = (ast_expression*)aloop;
2351 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2352 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2357 /* skip the 'do' and get the body */
2358 if (!parser_next(parser)) {
2359 if (OPTS_FLAG(LOOP_LABELS))
2360 parseerror(parser, "expected loop label or body");
2362 parseerror(parser, "expected loop body");
2366 if (parser->tok == ':') {
2367 if (!OPTS_FLAG(LOOP_LABELS))
2368 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2369 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2370 parseerror(parser, "expected loop label");
2373 label = util_strdup(parser_tokval(parser));
2374 if (!parser_next(parser)) {
2376 parseerror(parser, "expected loop body");
2381 vec_push(parser->breaks, label);
2382 vec_push(parser->continues, label);
2384 rv = parse_dowhile_go(parser, block, out);
2387 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2388 parseerror(parser, "internal error: label stack corrupted");
2391 * Test for NULL otherwise ast_delete dereferences null pointer
2399 vec_pop(parser->breaks);
2400 vec_pop(parser->continues);
2405 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2408 ast_expression *cond, *ontrue;
2412 lex_ctx_t ctx = parser_ctx(parser);
2414 (void)block; /* not touching */
2416 if (!parse_statement_or_block(parser, &ontrue))
2419 /* expect the "while" */
2420 if (parser->tok != TOKEN_KEYWORD ||
2421 strcmp(parser_tokval(parser), "while"))
2423 parseerror(parser, "expected 'while' and condition");
2428 /* skip the 'while' and check for opening paren */
2429 if (!parser_next(parser) || parser->tok != '(') {
2430 parseerror(parser, "expected 'while' condition in parenthesis");
2434 /* parse into the expression */
2435 if (!parser_next(parser)) {
2436 parseerror(parser, "expected 'while' condition after opening paren");
2440 /* parse the condition */
2441 cond = parse_expression_leave(parser, false, true, false);
2445 if (parser->tok != ')') {
2446 parseerror(parser, "expected closing paren after 'while' condition");
2452 if (!parser_next(parser) || parser->tok != ';') {
2453 parseerror(parser, "expected semicolon after condition");
2459 if (!parser_next(parser)) {
2460 parseerror(parser, "parse error");
2466 cond = process_condition(parser, cond, &ifnot);
2471 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2472 *out = (ast_expression*)aloop;
2476 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2477 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2482 /* skip the 'for' and check for opening paren */
2483 if (!parser_next(parser)) {
2484 if (OPTS_FLAG(LOOP_LABELS))
2485 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2487 parseerror(parser, "expected 'for' expressions in parenthesis");
2491 if (parser->tok == ':') {
2492 if (!OPTS_FLAG(LOOP_LABELS))
2493 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2494 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2495 parseerror(parser, "expected loop label");
2498 label = util_strdup(parser_tokval(parser));
2499 if (!parser_next(parser)) {
2501 parseerror(parser, "expected 'for' expressions in parenthesis");
2506 if (parser->tok != '(') {
2507 parseerror(parser, "expected 'for' expressions in parenthesis");
2511 vec_push(parser->breaks, label);
2512 vec_push(parser->continues, label);
2514 rv = parse_for_go(parser, block, out);
2517 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2518 parseerror(parser, "internal error: label stack corrupted");
2524 vec_pop(parser->breaks);
2525 vec_pop(parser->continues);
2529 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2532 ast_expression *initexpr, *cond, *increment, *ontrue;
2537 lex_ctx_t ctx = parser_ctx(parser);
2539 parser_enterblock(parser);
2546 /* parse into the expression */
2547 if (!parser_next(parser)) {
2548 parseerror(parser, "expected 'for' initializer after opening paren");
2553 if (parser->tok == TOKEN_IDENT)
2554 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2556 if (typevar || parser->tok == TOKEN_TYPENAME) {
2558 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2559 if (parsewarning(parser, WARN_EXTENSIONS,
2560 "current standard does not allow variable declarations in for-loop initializers"))
2564 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2567 else if (parser->tok != ';')
2569 initexpr = parse_expression_leave(parser, false, false, false);
2574 /* move on to condition */
2575 if (parser->tok != ';') {
2576 parseerror(parser, "expected semicolon after for-loop initializer");
2579 if (!parser_next(parser)) {
2580 parseerror(parser, "expected for-loop condition");
2584 /* parse the condition */
2585 if (parser->tok != ';') {
2586 cond = parse_expression_leave(parser, false, true, false);
2591 /* move on to incrementor */
2592 if (parser->tok != ';') {
2593 parseerror(parser, "expected semicolon after for-loop initializer");
2596 if (!parser_next(parser)) {
2597 parseerror(parser, "expected for-loop condition");
2601 /* parse the incrementor */
2602 if (parser->tok != ')') {
2603 lex_ctx_t condctx = parser_ctx(parser);
2604 increment = parse_expression_leave(parser, false, false, false);
2607 if (!ast_side_effects(increment)) {
2608 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2614 if (parser->tok != ')') {
2615 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2618 /* parse into the 'then' branch */
2619 if (!parser_next(parser)) {
2620 parseerror(parser, "expected for-loop body");
2623 if (!parse_statement_or_block(parser, &ontrue))
2627 cond = process_condition(parser, cond, &ifnot);
2631 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2632 *out = (ast_expression*)aloop;
2634 if (!parser_leaveblock(parser)) {
2640 if (initexpr) ast_unref(initexpr);
2641 if (cond) ast_unref(cond);
2642 if (increment) ast_unref(increment);
2643 (void)!parser_leaveblock(parser);
2647 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2649 ast_expression *exp = NULL;
2650 ast_expression *var = NULL;
2651 ast_return *ret = NULL;
2652 ast_value *retval = parser->function->return_value;
2653 ast_value *expected = parser->function->vtype;
2655 lex_ctx_t ctx = parser_ctx(parser);
2657 (void)block; /* not touching */
2659 if (!parser_next(parser)) {
2660 parseerror(parser, "expected return expression");
2664 /* return assignments */
2665 if (parser->tok == '=') {
2666 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2667 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2671 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2673 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2674 parseerror(parser, "invalid return type: `%s'", ty1);
2678 if (!parser_next(parser)) {
2679 parseerror(parser, "expected return assignment expression");
2683 if (!(exp = parse_expression_leave(parser, false, false, false)))
2686 /* prepare the return value */
2688 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2689 ast_type_adopt(retval, expected->expression.next);
2690 parser->function->return_value = retval;
2693 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2694 char ty1[1024], ty2[1024];
2695 ast_type_to_string(exp, ty1, sizeof(ty1));
2696 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2697 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2700 /* store to 'return' local variable */
2701 var = (ast_expression*)ast_store_new(
2703 type_store_instr[expected->expression.next->vtype],
2704 (ast_expression*)retval, exp);
2711 if (parser->tok != ';')
2712 parseerror(parser, "missing semicolon after return assignment");
2713 else if (!parser_next(parser))
2714 parseerror(parser, "parse error after return assignment");
2720 if (parser->tok != ';') {
2721 exp = parse_expression(parser, false, false);
2725 if (exp->vtype != TYPE_NIL &&
2726 exp->vtype != ((ast_expression*)expected)->next->vtype)
2728 parseerror(parser, "return with invalid expression");
2731 ret = ast_return_new(ctx, exp);
2737 if (!parser_next(parser))
2738 parseerror(parser, "parse error");
2740 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2742 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2744 ret = ast_return_new(ctx, (ast_expression*)retval);
2746 *out = (ast_expression*)ret;
2750 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2753 unsigned int levels = 0;
2754 lex_ctx_t ctx = parser_ctx(parser);
2755 const char **loops = (is_continue ? parser->continues : parser->breaks);
2757 (void)block; /* not touching */
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "expected semicolon or loop label");
2763 if (!vec_size(loops)) {
2765 parseerror(parser, "`continue` can only be used inside loops");
2767 parseerror(parser, "`break` can only be used inside loops or switches");
2770 if (parser->tok == TOKEN_IDENT) {
2771 if (!OPTS_FLAG(LOOP_LABELS))
2772 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2773 i = vec_size(loops);
2775 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2778 parseerror(parser, "no such loop to %s: `%s`",
2779 (is_continue ? "continue" : "break out of"),
2780 parser_tokval(parser));
2785 if (!parser_next(parser)) {
2786 parseerror(parser, "expected semicolon");
2791 if (parser->tok != ';') {
2792 parseerror(parser, "expected semicolon");
2796 if (!parser_next(parser))
2797 parseerror(parser, "parse error");
2799 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2803 /* returns true when it was a variable qualifier, false otherwise!
2804 * on error, cvq is set to CV_WRONG
2811 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2813 bool had_const = false;
2814 bool had_var = false;
2815 bool had_noref = false;
2816 bool had_attrib = false;
2817 bool had_static = false;
2820 static attribute_t attributes[] = {
2821 { "noreturn", AST_FLAG_NORETURN },
2822 { "inline", AST_FLAG_INLINE },
2823 { "eraseable", AST_FLAG_ERASEABLE },
2824 { "accumulate", AST_FLAG_ACCUMULATE },
2825 { "last", AST_FLAG_FINAL_DECL }
2832 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2834 /* parse an attribute */
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "expected attribute after `[[`");
2841 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2842 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2843 flags |= attributes[i].flag;
2844 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2845 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2846 attributes[i].name);
2854 if (i != GMQCC_ARRAY_COUNT(attributes))
2858 if (!strcmp(parser_tokval(parser), "noref")) {
2860 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2861 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2866 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2867 flags |= AST_FLAG_ALIAS;
2870 if (!parser_next(parser)) {
2871 parseerror(parser, "parse error in attribute");
2875 if (parser->tok == '(') {
2876 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2877 parseerror(parser, "`alias` attribute missing parameter");
2881 *message = util_strdup(parser_tokval(parser));
2883 if (!parser_next(parser)) {
2884 parseerror(parser, "parse error in attribute");
2888 if (parser->tok != ')') {
2889 parseerror(parser, "`alias` attribute expected `)` after parameter");
2893 if (!parser_next(parser)) {
2894 parseerror(parser, "parse error in attribute");
2899 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2900 parseerror(parser, "`alias` attribute expected `]]`");
2904 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2905 flags |= AST_FLAG_DEPRECATED;
2908 if (!parser_next(parser)) {
2909 parseerror(parser, "parse error in attribute");
2913 if (parser->tok == '(') {
2914 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2915 parseerror(parser, "`deprecated` attribute missing parameter");
2919 *message = util_strdup(parser_tokval(parser));
2921 if (!parser_next(parser)) {
2922 parseerror(parser, "parse error in attribute");
2926 if(parser->tok != ')') {
2927 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2931 if (!parser_next(parser)) {
2932 parseerror(parser, "parse error in attribute");
2937 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2938 parseerror(parser, "`deprecated` attribute expected `]]`");
2941 if (*message) mem_d(*message);
2947 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2948 flags |= AST_FLAG_COVERAGE;
2949 if (!parser_next(parser)) {
2951 parseerror(parser, "parse error in coverage attribute");
2955 if (parser->tok == '(') {
2956 if (!parser_next(parser)) {
2958 parseerror(parser, "invalid parameter for coverage() attribute\n"
2959 "valid are: block");
2963 if (parser->tok != ')') {
2965 if (parser->tok != TOKEN_IDENT)
2966 goto bad_coverage_arg;
2967 if (!strcmp(parser_tokval(parser), "block"))
2968 flags |= AST_FLAG_BLOCK_COVERAGE;
2969 else if (!strcmp(parser_tokval(parser), "none"))
2970 flags &= ~(AST_FLAG_COVERAGE_MASK);
2972 goto bad_coverage_arg;
2973 if (!parser_next(parser))
2974 goto error_in_coverage;
2975 if (parser->tok == ',') {
2976 if (!parser_next(parser))
2977 goto error_in_coverage;
2979 } while (parser->tok != ')');
2981 if (parser->tok != ')' || !parser_next(parser))
2982 goto error_in_coverage;
2984 /* without parameter [[coverage]] equals [[coverage(block)]] */
2985 flags |= AST_FLAG_BLOCK_COVERAGE;
2990 /* Skip tokens until we hit a ]] */
2991 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2992 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2993 if (!parser_next(parser)) {
2994 parseerror(parser, "error inside attribute");
3001 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3003 else if (!strcmp(parser_tokval(parser), "const"))
3005 else if (!strcmp(parser_tokval(parser), "var"))
3007 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3009 else if (!strcmp(parser_tokval(parser), "noref"))
3011 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3018 if (!parser_next(parser))
3028 *is_static = had_static;
3032 parseerror(parser, "parse error after variable qualifier");
3037 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3038 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3043 /* skip the 'while' and get the body */
3044 if (!parser_next(parser)) {
3045 if (OPTS_FLAG(LOOP_LABELS))
3046 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3048 parseerror(parser, "expected 'switch' operand in parenthesis");
3052 if (parser->tok == ':') {
3053 if (!OPTS_FLAG(LOOP_LABELS))
3054 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3055 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3056 parseerror(parser, "expected loop label");
3059 label = util_strdup(parser_tokval(parser));
3060 if (!parser_next(parser)) {
3062 parseerror(parser, "expected 'switch' operand in parenthesis");
3067 if (parser->tok != '(') {
3068 parseerror(parser, "expected 'switch' operand in parenthesis");
3072 vec_push(parser->breaks, label);
3074 rv = parse_switch_go(parser, block, out);
3077 if (vec_last(parser->breaks) != label) {
3078 parseerror(parser, "internal error: label stack corrupted");
3084 vec_pop(parser->breaks);
3089 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3091 ast_expression *operand;
3094 ast_switch *switchnode;
3095 ast_switch_case swcase;
3098 bool noref, is_static;
3099 uint32_t qflags = 0;
3101 lex_ctx_t ctx = parser_ctx(parser);
3103 (void)block; /* not touching */
3106 /* parse into the expression */
3107 if (!parser_next(parser)) {
3108 parseerror(parser, "expected switch operand");
3111 /* parse the operand */
3112 operand = parse_expression_leave(parser, false, false, false);
3116 switchnode = ast_switch_new(ctx, operand);
3119 if (parser->tok != ')') {
3120 ast_delete(switchnode);
3121 parseerror(parser, "expected closing paren after 'switch' operand");
3125 /* parse over the opening paren */
3126 if (!parser_next(parser) || parser->tok != '{') {
3127 ast_delete(switchnode);
3128 parseerror(parser, "expected list of cases");
3132 if (!parser_next(parser)) {
3133 ast_delete(switchnode);
3134 parseerror(parser, "expected 'case' or 'default'");
3138 /* new block; allow some variables to be declared here */
3139 parser_enterblock(parser);
3142 if (parser->tok == TOKEN_IDENT)
3143 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3144 if (typevar || parser->tok == TOKEN_TYPENAME) {
3145 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3146 ast_delete(switchnode);
3151 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3153 if (cvq == CV_WRONG) {
3154 ast_delete(switchnode);
3157 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3158 ast_delete(switchnode);
3167 while (parser->tok != '}') {
3168 ast_block *caseblock;
3170 if (!strcmp(parser_tokval(parser), "case")) {
3171 if (!parser_next(parser)) {
3172 ast_delete(switchnode);
3173 parseerror(parser, "expected expression for case");
3176 swcase.value = parse_expression_leave(parser, false, false, false);
3177 if (!swcase.value) {
3178 ast_delete(switchnode);
3179 parseerror(parser, "expected expression for case");
3182 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3183 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3184 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3190 else if (!strcmp(parser_tokval(parser), "default")) {
3191 swcase.value = NULL;
3192 if (!parser_next(parser)) {
3193 ast_delete(switchnode);
3194 parseerror(parser, "expected colon");
3199 ast_delete(switchnode);
3200 parseerror(parser, "expected 'case' or 'default'");
3204 /* Now the colon and body */
3205 if (parser->tok != ':') {
3206 if (swcase.value) ast_unref(swcase.value);
3207 ast_delete(switchnode);
3208 parseerror(parser, "expected colon");
3212 if (!parser_next(parser)) {
3213 if (swcase.value) ast_unref(swcase.value);
3214 ast_delete(switchnode);
3215 parseerror(parser, "expected statements or case");
3218 caseblock = ast_block_new(parser_ctx(parser));
3220 if (swcase.value) ast_unref(swcase.value);
3221 ast_delete(switchnode);
3224 swcase.code = (ast_expression*)caseblock;
3225 vec_push(switchnode->cases, swcase);
3227 ast_expression *expr;
3228 if (parser->tok == '}')
3230 if (parser->tok == TOKEN_KEYWORD) {
3231 if (!strcmp(parser_tokval(parser), "case") ||
3232 !strcmp(parser_tokval(parser), "default"))
3237 if (!parse_statement(parser, caseblock, &expr, true)) {
3238 ast_delete(switchnode);
3243 if (!ast_block_add_expr(caseblock, expr)) {
3244 ast_delete(switchnode);
3250 parser_leaveblock(parser);
3253 if (parser->tok != '}') {
3254 ast_delete(switchnode);
3255 parseerror(parser, "expected closing paren of case list");
3258 if (!parser_next(parser)) {
3259 ast_delete(switchnode);
3260 parseerror(parser, "parse error after switch");
3263 *out = (ast_expression*)switchnode;
3267 /* parse computed goto sides */
3268 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3269 ast_expression *on_true;
3270 ast_expression *on_false;
3271 ast_expression *cond;
3276 if (ast_istype(*side, ast_ternary)) {
3277 ast_ternary *tern = (ast_ternary*)*side;
3278 on_true = parse_goto_computed(parser, &tern->on_true);
3279 on_false = parse_goto_computed(parser, &tern->on_false);
3281 if (!on_true || !on_false) {
3282 parseerror(parser, "expected label or expression in ternary");
3283 if (on_true) ast_unref(on_true);
3284 if (on_false) ast_unref(on_false);
3292 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3293 } else if (ast_istype(*side, ast_label)) {
3294 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3295 ast_goto_set_label(gt, ((ast_label*)*side));
3297 return (ast_expression*)gt;
3302 static bool parse_goto(parser_t *parser, ast_expression **out)
3304 ast_goto *gt = NULL;
3305 ast_expression *lbl;
3307 if (!parser_next(parser))
3310 if (parser->tok != TOKEN_IDENT) {
3311 ast_expression *expression;
3313 /* could be an expression i.e computed goto :-) */
3314 if (parser->tok != '(') {
3315 parseerror(parser, "expected label name after `goto`");
3319 /* failed to parse expression for goto */
3320 if (!(expression = parse_expression(parser, false, true)) ||
3321 !(*out = parse_goto_computed(parser, &expression))) {
3322 parseerror(parser, "invalid goto expression");
3324 ast_unref(expression);
3331 /* not computed goto */
3332 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3333 lbl = parser_find_label(parser, gt->name);
3335 if (!ast_istype(lbl, ast_label)) {
3336 parseerror(parser, "internal error: label is not an ast_label");
3340 ast_goto_set_label(gt, (ast_label*)lbl);
3343 vec_push(parser->gotos, gt);
3345 if (!parser_next(parser) || parser->tok != ';') {
3346 parseerror(parser, "semicolon expected after goto label");
3349 if (!parser_next(parser)) {
3350 parseerror(parser, "parse error after goto");
3354 *out = (ast_expression*)gt;
3358 static bool parse_skipwhite(parser_t *parser)
3361 if (!parser_next(parser))
3363 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3364 return parser->tok < TOKEN_ERROR;
3367 static bool parse_eol(parser_t *parser)
3369 if (!parse_skipwhite(parser))
3371 return parser->tok == TOKEN_EOL;
3374 static bool parse_pragma_do(parser_t *parser)
3376 if (!parser_next(parser) ||
3377 parser->tok != TOKEN_IDENT ||
3378 strcmp(parser_tokval(parser), "pragma"))
3380 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3383 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3384 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3388 if (!strcmp(parser_tokval(parser), "noref")) {
3389 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3390 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3393 parser->noref = !!parser_token(parser)->constval.i;
3394 if (!parse_eol(parser)) {
3395 parseerror(parser, "parse error after `noref` pragma");
3401 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3404 while (!parse_eol(parser)) {
3405 parser_next(parser);
3414 static bool parse_pragma(parser_t *parser)
3417 parser->lex->flags.preprocessing = true;
3418 parser->lex->flags.mergelines = true;
3419 rv = parse_pragma_do(parser);
3420 if (parser->tok != TOKEN_EOL) {
3421 parseerror(parser, "junk after pragma");
3424 parser->lex->flags.preprocessing = false;
3425 parser->lex->flags.mergelines = false;
3426 if (!parser_next(parser)) {
3427 parseerror(parser, "parse error after pragma");
3433 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3435 bool noref, is_static;
3437 uint32_t qflags = 0;
3438 ast_value *typevar = NULL;
3439 char *vstring = NULL;
3443 if (parser->tok == TOKEN_IDENT)
3444 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3446 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3448 /* local variable */
3450 parseerror(parser, "cannot declare a variable from here");
3453 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3454 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3457 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3461 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3463 if (cvq == CV_WRONG)
3465 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3467 else if (parser->tok == TOKEN_KEYWORD)
3469 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3474 if (!parser_next(parser)) {
3475 parseerror(parser, "parse error after __builtin_debug_printtype");
3479 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3481 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3482 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3483 if (!parser_next(parser)) {
3484 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3490 if (!parse_statement(parser, block, out, allow_cases))
3493 con_out("__builtin_debug_printtype: got no output node\n");
3496 ast_type_to_string(*out, ty, sizeof(ty));
3497 con_out("__builtin_debug_printtype: `%s`\n", ty);
3502 else if (!strcmp(parser_tokval(parser), "return"))
3504 return parse_return(parser, block, out);
3506 else if (!strcmp(parser_tokval(parser), "if"))
3508 return parse_if(parser, block, out);
3510 else if (!strcmp(parser_tokval(parser), "while"))
3512 return parse_while(parser, block, out);
3514 else if (!strcmp(parser_tokval(parser), "do"))
3516 return parse_dowhile(parser, block, out);
3518 else if (!strcmp(parser_tokval(parser), "for"))
3520 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3521 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3524 return parse_for(parser, block, out);
3526 else if (!strcmp(parser_tokval(parser), "break"))
3528 return parse_break_continue(parser, block, out, false);
3530 else if (!strcmp(parser_tokval(parser), "continue"))
3532 return parse_break_continue(parser, block, out, true);
3534 else if (!strcmp(parser_tokval(parser), "switch"))
3536 return parse_switch(parser, block, out);
3538 else if (!strcmp(parser_tokval(parser), "case") ||
3539 !strcmp(parser_tokval(parser), "default"))
3542 parseerror(parser, "unexpected 'case' label");
3547 else if (!strcmp(parser_tokval(parser), "goto"))
3549 return parse_goto(parser, out);
3551 else if (!strcmp(parser_tokval(parser), "typedef"))
3553 if (!parser_next(parser)) {
3554 parseerror(parser, "expected type definition after 'typedef'");
3557 return parse_typedef(parser);
3559 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3562 else if (parser->tok == '{')
3565 inner = parse_block(parser);
3568 *out = (ast_expression*)inner;
3571 else if (parser->tok == ':')
3575 if (!parser_next(parser)) {
3576 parseerror(parser, "expected label name");
3579 if (parser->tok != TOKEN_IDENT) {
3580 parseerror(parser, "label must be an identifier");
3583 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3585 if (!label->undefined) {
3586 parseerror(parser, "label `%s` already defined", label->name);
3589 label->undefined = false;
3592 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3593 vec_push(parser->labels, label);
3595 *out = (ast_expression*)label;
3596 if (!parser_next(parser)) {
3597 parseerror(parser, "parse error after label");
3600 for (i = 0; i < vec_size(parser->gotos); ++i) {
3601 if (!strcmp(parser->gotos[i]->name, label->name)) {
3602 ast_goto_set_label(parser->gotos[i], label);
3603 vec_remove(parser->gotos, i, 1);
3609 else if (parser->tok == ';')
3611 if (!parser_next(parser)) {
3612 parseerror(parser, "parse error after empty statement");
3619 lex_ctx_t ctx = parser_ctx(parser);
3620 ast_expression *exp = parse_expression(parser, false, false);
3624 if (!ast_side_effects(exp)) {
3625 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3632 static bool parse_enum(parser_t *parser)
3635 bool reverse = false;
3637 ast_value **values = NULL;
3638 ast_value *var = NULL;
3641 ast_expression *old;
3643 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3644 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3648 /* enumeration attributes (can add more later) */
3649 if (parser->tok == ':') {
3650 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3651 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3656 if (!strcmp(parser_tokval(parser), "flag")) {
3660 else if (!strcmp(parser_tokval(parser), "reverse")) {
3664 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3668 if (!parser_next(parser) || parser->tok != '{') {
3669 parseerror(parser, "expected `{` after enum attribute ");
3675 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3676 if (parser->tok == '}') {
3677 /* allow an empty enum */
3680 parseerror(parser, "expected identifier or `}`");
3684 old = parser_find_field(parser, parser_tokval(parser));
3686 old = parser_find_global(parser, parser_tokval(parser));
3688 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3689 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3693 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3694 vec_push(values, var);
3695 var->cvq = CV_CONST;
3696 var->hasvalue = true;
3698 /* for flagged enumerations increment in POTs of TWO */
3699 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3700 parser_addglobal(parser, var->name, (ast_expression*)var);
3702 if (!parser_next(parser)) {
3703 parseerror(parser, "expected `=`, `}` or comma after identifier");
3707 if (parser->tok == ',')
3709 if (parser->tok == '}')
3711 if (parser->tok != '=') {
3712 parseerror(parser, "expected `=`, `}` or comma after identifier");
3716 if (!parser_next(parser)) {
3717 parseerror(parser, "expected expression after `=`");
3721 /* We got a value! */
3722 old = parse_expression_leave(parser, true, false, false);
3723 asvalue = (ast_value*)old;
3724 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3725 compile_error(ast_ctx(var), "constant value or expression expected");
3728 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3730 if (parser->tok == '}')
3732 if (parser->tok != ',') {
3733 parseerror(parser, "expected `}` or comma after expression");
3738 /* patch them all (for reversed attribute) */
3741 for (i = 0; i < vec_size(values); i++)
3742 values[i]->constval.vfloat = vec_size(values) - i - 1;
3745 if (parser->tok != '}') {
3746 parseerror(parser, "internal error: breaking without `}`");
3750 if (!parser_next(parser) || parser->tok != ';') {
3751 parseerror(parser, "expected semicolon after enumeration");
3755 if (!parser_next(parser)) {
3756 parseerror(parser, "parse error after enumeration");
3768 static bool parse_block_into(parser_t *parser, ast_block *block)
3772 parser_enterblock(parser);
3774 if (!parser_next(parser)) { /* skip the '{' */
3775 parseerror(parser, "expected function body");
3779 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3781 ast_expression *expr = NULL;
3782 if (parser->tok == '}')
3785 if (!parse_statement(parser, block, &expr, false)) {
3786 /* parseerror(parser, "parse error"); */
3792 if (!ast_block_add_expr(block, expr)) {
3799 if (parser->tok != '}') {
3802 (void)parser_next(parser);
3806 if (!parser_leaveblock(parser))
3808 return retval && !!block;
3811 static ast_block* parse_block(parser_t *parser)
3814 block = ast_block_new(parser_ctx(parser));
3817 if (!parse_block_into(parser, block)) {
3818 ast_block_delete(block);
3824 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3826 if (parser->tok == '{') {
3827 *out = (ast_expression*)parse_block(parser);
3830 return parse_statement(parser, NULL, out, false);
3833 static bool create_vector_members(ast_value *var, ast_member **me)
3836 size_t len = strlen(var->name);
3838 for (i = 0; i < 3; ++i) {
3839 char *name = (char*)mem_a(len+3);
3840 memcpy(name, var->name, len);
3842 name[len+1] = 'x'+i;
3844 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3853 do { ast_member_delete(me[--i]); } while(i);
3857 static bool parse_function_body(parser_t *parser, ast_value *var)
3859 ast_block *block = NULL;
3864 ast_expression *framenum = NULL;
3865 ast_expression *nextthink = NULL;
3866 /* None of the following have to be deleted */
3867 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3868 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3869 bool has_frame_think;
3873 has_frame_think = false;
3874 old = parser->function;
3876 if (var->expression.flags & AST_FLAG_ALIAS) {
3877 parseerror(parser, "function aliases cannot have bodies");
3881 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3882 parseerror(parser, "gotos/labels leaking");
3886 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3887 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3888 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3894 if (parser->tok == '[') {
3895 /* got a frame definition: [ framenum, nextthink ]
3896 * this translates to:
3897 * self.frame = framenum;
3898 * self.nextthink = time + 0.1;
3899 * self.think = nextthink;
3903 fld_think = parser_find_field(parser, "think");
3904 fld_nextthink = parser_find_field(parser, "nextthink");
3905 fld_frame = parser_find_field(parser, "frame");
3906 if (!fld_think || !fld_nextthink || !fld_frame) {
3907 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3908 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3911 gbl_time = parser_find_global(parser, "time");
3912 gbl_self = parser_find_global(parser, "self");
3913 if (!gbl_time || !gbl_self) {
3914 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3915 parseerror(parser, "please declare the following globals: `time`, `self`");
3919 if (!parser_next(parser))
3922 framenum = parse_expression_leave(parser, true, false, false);
3924 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3927 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3928 ast_unref(framenum);
3929 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3933 if (parser->tok != ',') {
3934 ast_unref(framenum);
3935 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3936 parseerror(parser, "Got a %i\n", parser->tok);
3940 if (!parser_next(parser)) {
3941 ast_unref(framenum);
3945 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3947 /* qc allows the use of not-yet-declared functions here
3948 * - this automatically creates a prototype */
3949 ast_value *thinkfunc;
3950 ast_expression *functype = fld_think->next;
3952 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3953 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3954 ast_unref(framenum);
3955 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3958 ast_type_adopt(thinkfunc, functype);
3960 if (!parser_next(parser)) {
3961 ast_unref(framenum);
3962 ast_delete(thinkfunc);
3966 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3968 nextthink = (ast_expression*)thinkfunc;
3971 nextthink = parse_expression_leave(parser, true, false, false);
3973 ast_unref(framenum);
3974 parseerror(parser, "expected a think-function in [frame,think] notation");
3979 if (!ast_istype(nextthink, ast_value)) {
3980 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3984 if (retval && parser->tok != ']') {
3985 parseerror(parser, "expected closing `]` for [frame,think] notation");
3989 if (retval && !parser_next(parser)) {
3993 if (retval && parser->tok != '{') {
3994 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3999 ast_unref(nextthink);
4000 ast_unref(framenum);
4004 has_frame_think = true;
4007 block = ast_block_new(parser_ctx(parser));
4009 parseerror(parser, "failed to allocate block");
4010 if (has_frame_think) {
4011 ast_unref(nextthink);
4012 ast_unref(framenum);
4017 if (has_frame_think) {
4019 ast_expression *self_frame;
4020 ast_expression *self_nextthink;
4021 ast_expression *self_think;
4022 ast_expression *time_plus_1;
4023 ast_store *store_frame;
4024 ast_store *store_nextthink;
4025 ast_store *store_think;
4027 ctx = parser_ctx(parser);
4028 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4029 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4030 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4032 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4033 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1f, false));
4035 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4036 if (self_frame) ast_delete(self_frame);
4037 if (self_nextthink) ast_delete(self_nextthink);
4038 if (self_think) ast_delete(self_think);
4039 if (time_plus_1) ast_delete(time_plus_1);
4045 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4046 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4047 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4050 ast_delete(self_frame);
4053 if (!store_nextthink) {
4054 ast_delete(self_nextthink);
4058 ast_delete(self_think);
4062 if (store_frame) ast_delete(store_frame);
4063 if (store_nextthink) ast_delete(store_nextthink);
4064 if (store_think) ast_delete(store_think);
4067 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4068 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4069 !ast_block_add_expr(block, (ast_expression*)store_think))
4076 parseerror(parser, "failed to generate code for [frame,think]");
4077 ast_unref(nextthink);
4078 ast_unref(framenum);
4084 if (var->hasvalue) {
4085 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4086 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4087 ast_block_delete(block);
4090 func = var->constval.vfunc;
4093 parseerror(parser, "internal error: NULL function: `%s`", var->name);
4094 ast_block_delete(block);
4098 func = ast_function_new(ast_ctx(var), var->name, var);
4101 parseerror(parser, "failed to allocate function for `%s`", var->name);
4102 ast_block_delete(block);
4105 vec_push(parser->functions, func);
4108 parser_enterblock(parser);
4110 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4112 ast_value *param = var->expression.params[parami];
4115 if (param->expression.vtype != TYPE_VECTOR &&
4116 (param->expression.vtype != TYPE_FIELD ||
4117 param->expression.next->vtype != TYPE_VECTOR))
4122 if (!create_vector_members(param, me)) {
4123 ast_block_delete(block);
4127 for (e = 0; e < 3; ++e) {
4128 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4129 ast_block_collect(block, (ast_expression*)me[e]);
4133 if (var->argcounter && !func->argc) {
4134 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4135 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4139 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4141 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4142 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4143 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4144 varargs->expression.count = 0;
4145 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4146 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4147 ast_delete(varargs);
4148 ast_block_delete(block);
4151 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4152 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4153 ast_delete(varargs);
4154 ast_block_delete(block);
4157 func->varargs = varargs;
4158 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params), false);
4161 parser->function = func;
4162 if (!parse_block_into(parser, block)) {
4163 ast_block_delete(block);
4167 vec_push(func->blocks, block);
4169 parser->function = old;
4170 if (!parser_leaveblock(parser))
4172 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4173 parseerror(parser, "internal error: local scopes left");
4177 if (parser->tok == ';')
4178 return parser_next(parser);
4179 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4180 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4184 (void)!parser_leaveblock(parser);
4185 vec_pop(parser->functions);
4186 ast_function_delete(func);
4187 var->constval.vfunc = NULL;
4190 parser->function = old;
4194 static ast_expression *array_accessor_split(
4199 ast_expression *left,
4200 ast_expression *right
4206 lex_ctx_t ctx = ast_ctx(array);
4208 if (!left || !right) {
4209 if (left) ast_delete(left);
4210 if (right) ast_delete(right);
4214 cmp = ast_binary_new(ctx, INSTR_LT,
4215 (ast_expression*)index,
4216 (ast_expression*)fold_constgen_float(parser->fold, middle, false));
4220 parseerror(parser, "internal error: failed to create comparison for array setter");
4224 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4226 ast_delete(cmp); /* will delete left and right */
4227 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4231 return (ast_expression*)ifthen;
4234 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4236 lex_ctx_t ctx = ast_ctx(array);
4238 if (from+1 == afterend) {
4239 /* set this value */
4242 ast_array_index *subscript;
4244 int assignop = type_store_instr[value->expression.vtype];
4246 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4247 assignop = INSTR_STORE_V;
4249 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4253 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4255 ast_delete(subscript);
4259 block = ast_block_new(ctx);
4265 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4270 ret = ast_return_new(ctx, NULL);
4276 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4281 return (ast_expression*)block;
4283 ast_expression *left, *right;
4284 size_t diff = afterend - from;
4285 size_t middle = from + diff/2;
4286 left = array_setter_node(parser, array, index, value, from, middle);
4287 right = array_setter_node(parser, array, index, value, middle, afterend);
4288 return array_accessor_split(parser, array, index, middle, left, right);
4292 static ast_expression *array_field_setter_node(
4301 lex_ctx_t ctx = ast_ctx(array);
4303 if (from+1 == afterend) {
4304 /* set this value */
4307 ast_entfield *entfield;
4308 ast_array_index *subscript;
4310 int assignop = type_storep_instr[value->expression.vtype];
4312 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4313 assignop = INSTR_STOREP_V;
4315 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4319 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4320 subscript->expression.vtype = TYPE_FIELD;
4322 entfield = ast_entfield_new_force(ctx,
4323 (ast_expression*)entity,
4324 (ast_expression*)subscript,
4325 (ast_expression*)subscript);
4327 ast_delete(subscript);
4331 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4333 ast_delete(entfield);
4337 block = ast_block_new(ctx);
4343 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4348 ret = ast_return_new(ctx, NULL);
4354 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4359 return (ast_expression*)block;
4361 ast_expression *left, *right;
4362 size_t diff = afterend - from;
4363 size_t middle = from + diff/2;
4364 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4365 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4366 return array_accessor_split(parser, array, index, middle, left, right);
4370 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4372 lex_ctx_t ctx = ast_ctx(array);
4374 if (from+1 == afterend) {
4376 ast_array_index *subscript;
4378 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4382 ret = ast_return_new(ctx, (ast_expression*)subscript);
4384 ast_delete(subscript);
4388 return (ast_expression*)ret;
4390 ast_expression *left, *right;
4391 size_t diff = afterend - from;
4392 size_t middle = from + diff/2;
4393 left = array_getter_node(parser, array, index, from, middle);
4394 right = array_getter_node(parser, array, index, middle, afterend);
4395 return array_accessor_split(parser, array, index, middle, left, right);
4399 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4401 ast_function *func = NULL;
4402 ast_value *fval = NULL;
4403 ast_block *body = NULL;
4405 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4407 parseerror(parser, "failed to create accessor function value");
4410 fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4412 func = ast_function_new(ast_ctx(array), funcname, fval);
4415 parseerror(parser, "failed to create accessor function node");
4419 body = ast_block_new(ast_ctx(array));
4421 parseerror(parser, "failed to create block for array accessor");
4427 vec_push(func->blocks, body);
4430 vec_push(parser->accessors, fval);
4435 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4437 ast_value *index = NULL;
4438 ast_value *value = NULL;
4442 if (!ast_istype(array->expression.next, ast_value)) {
4443 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4447 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4449 func = fval->constval.vfunc;
4450 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4452 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4453 value = ast_value_copy((ast_value*)array->expression.next);
4455 if (!index || !value) {
4456 parseerror(parser, "failed to create locals for array accessor");
4459 (void)!ast_value_set_name(value, "value"); /* not important */
4460 vec_push(fval->expression.params, index);
4461 vec_push(fval->expression.params, value);
4463 array->setter = fval;
4466 if (index) ast_delete(index);
4467 if (value) ast_delete(value);
4473 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4475 ast_expression *root = NULL;
4476 root = array_setter_node(parser, array,
4477 array->setter->expression.params[0],
4478 array->setter->expression.params[1],
4479 0, array->expression.count);
4481 parseerror(parser, "failed to build accessor search tree");
4484 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4491 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4493 if (!parser_create_array_setter_proto(parser, array, funcname))
4495 return parser_create_array_setter_impl(parser, array);
4498 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4500 ast_expression *root = NULL;
4501 ast_value *entity = NULL;
4502 ast_value *index = NULL;
4503 ast_value *value = NULL;
4507 if (!ast_istype(array->expression.next, ast_value)) {
4508 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4512 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4514 func = fval->constval.vfunc;
4515 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4517 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4518 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4519 value = ast_value_copy((ast_value*)array->expression.next);
4520 if (!entity || !index || !value) {
4521 parseerror(parser, "failed to create locals for array accessor");
4524 (void)!ast_value_set_name(value, "value"); /* not important */
4525 vec_push(fval->expression.params, entity);
4526 vec_push(fval->expression.params, index);
4527 vec_push(fval->expression.params, value);
4529 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4531 parseerror(parser, "failed to build accessor search tree");
4535 array->setter = fval;
4536 return ast_block_add_expr(func->blocks[0], root);
4538 if (entity) ast_delete(entity);
4539 if (index) ast_delete(index);
4540 if (value) ast_delete(value);
4541 if (root) ast_delete(root);
4547 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4549 ast_value *index = NULL;
4553 /* NOTE: checking array->expression.next rather than elemtype since
4554 * for fields elemtype is a temporary fieldtype.
4556 if (!ast_istype(array->expression.next, ast_value)) {
4557 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4561 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4563 func = fval->constval.vfunc;
4564 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4566 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4569 parseerror(parser, "failed to create locals for array accessor");
4572 vec_push(fval->expression.params, index);
4574 array->getter = fval;
4577 if (index) ast_delete(index);
4583 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4585 ast_expression *root = NULL;
4587 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4589 parseerror(parser, "failed to build accessor search tree");
4592 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4599 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4601 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4603 return parser_create_array_getter_impl(parser, array);
4606 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4614 bool variadic = false;
4615 ast_value *varparam = NULL;
4616 char *argcounter = NULL;
4618 ctx = parser_ctx(parser);
4620 /* for the sake of less code we parse-in in this function */
4621 if (!parser_next(parser)) {
4623 parseerror(parser, "expected parameter list");
4629 /* parse variables until we hit a closing paren */
4630 while (parser->tok != ')') {
4631 bool is_varargs = false;
4634 /* there must be commas between them */
4635 if (parser->tok != ',') {
4636 parseerror(parser, "expected comma or end of parameter list");
4639 if (!parser_next(parser)) {
4640 parseerror(parser, "expected parameter");
4646 param = parse_typename(parser, NULL, NULL, &is_varargs);
4647 if (!param && !is_varargs)
4650 /* '...' indicates a varargs function */
4652 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4653 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4656 if (parser->tok == TOKEN_IDENT) {
4657 argcounter = util_strdup(parser_tokval(parser));
4658 if (!parser_next(parser) || parser->tok != ')') {
4659 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4664 vec_push(params, param);
4665 if (param->expression.vtype >= TYPE_VARIANT) {
4666 char tname[1024]; /* typename is reserved in C++ */
4667 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4668 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4671 /* type-restricted varargs */
4672 if (parser->tok == TOKEN_DOTS) {
4674 varparam = vec_last(params);
4676 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4677 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4680 if (parser->tok == TOKEN_IDENT) {
4681 argcounter = util_strdup(parser_tokval(parser));
4682 if (!parser_next(parser) || parser->tok != ')') {
4683 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4691 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4695 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4696 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4699 if (!parser_next(parser)) {
4700 parseerror(parser, "parse error after typename");
4704 /* now turn 'var' into a function type */
4705 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4706 fval->expression.next = (ast_expression*)var;
4708 fval->expression.flags |= AST_FLAG_VARIADIC;
4711 var->expression.params = params;
4712 var->expression.varparam = (ast_expression*)varparam;
4713 var->argcounter = argcounter;
4722 ast_delete(varparam);
4724 for (i = 0; i < vec_size(params); ++i)
4725 ast_delete(params[i]);
4730 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4732 ast_expression *cexp;
4733 ast_value *cval, *tmp;
4736 ctx = parser_ctx(parser);
4738 if (!parser_next(parser)) {
4740 parseerror(parser, "expected array-size");
4744 if (parser->tok != ']') {
4745 cexp = parse_expression_leave(parser, true, false, false);
4747 if (!cexp || !ast_istype(cexp, ast_value)) {
4751 parseerror(parser, "expected array-size as constant positive integer");
4754 cval = (ast_value*)cexp;
4761 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4762 tmp->expression.next = (ast_expression*)var;
4766 if (cval->expression.vtype == TYPE_INTEGER)
4767 tmp->expression.count = cval->constval.vint;
4768 else if (cval->expression.vtype == TYPE_FLOAT)
4769 tmp->expression.count = cval->constval.vfloat;
4773 parseerror(parser, "array-size must be a positive integer constant");
4779 var->expression.count = -1;
4780 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4783 if (parser->tok != ']') {
4785 parseerror(parser, "expected ']' after array-size");
4788 if (!parser_next(parser)) {
4790 parseerror(parser, "error after parsing array size");
4796 /* Parse a complete typename.
4797 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4798 * but when parsing variables separated by comma
4799 * 'storebase' should point to where the base-type should be kept.
4800 * The base type makes up every bit of type information which comes *before* the
4803 * NOTE: The value must either be named, have a NULL name, or a name starting
4804 * with '<'. In the first case, this will be the actual variable or type
4805 * name, in the other cases it is assumed that the name will appear
4806 * later, and an error is generated otherwise.
4808 * The following will be parsed in its entirety:
4810 * The 'basetype' in this case is 'void()'
4811 * and if there's a comma after it, say:
4813 * then the type-information 'void()' can be stored in 'storebase'
4815 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4817 ast_value *var, *tmp;
4820 const char *name = NULL;
4821 bool isfield = false;
4822 bool wasarray = false;
4823 size_t morefields = 0;
4825 bool vararg = (parser->tok == TOKEN_DOTS);
4827 ctx = parser_ctx(parser);
4829 /* types may start with a dot */
4830 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4832 if (parser->tok == TOKEN_DOTS)
4834 /* if we parsed a dot we need a typename now */
4835 if (!parser_next(parser)) {
4836 parseerror(parser, "expected typename for field definition");
4840 /* Further dots are handled seperately because they won't be part of the
4844 if (parser->tok == '.')
4846 else if (parser->tok == TOKEN_DOTS)
4851 if (!parser_next(parser)) {
4852 parseerror(parser, "expected typename for field definition");
4857 if (parser->tok == TOKEN_IDENT)
4858 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4859 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4860 if (vararg && is_vararg) {
4864 parseerror(parser, "expected typename");
4868 /* generate the basic type value */
4869 if (cached_typedef) {
4870 var = ast_value_copy(cached_typedef);
4871 ast_value_set_name(var, "<type(from_def)>");
4873 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4875 for (; morefields; --morefields) {
4876 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4877 tmp->expression.next = (ast_expression*)var;
4881 /* do not yet turn into a field - remember:
4882 * .void() foo; is a field too
4883 * .void()() foo; is a function
4887 if (!parser_next(parser)) {
4889 parseerror(parser, "parse error after typename");
4893 /* an opening paren now starts the parameter-list of a function
4894 * this is where original-QC has parameter lists.
4895 * We allow a single parameter list here.
4896 * Much like fteqcc we don't allow `float()() x`
4898 if (parser->tok == '(') {
4899 var = parse_parameter_list(parser, var);
4904 /* store the base if requested */
4906 *storebase = ast_value_copy(var);
4908 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4909 tmp->expression.next = (ast_expression*)*storebase;
4914 /* there may be a name now */
4915 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4916 if (!strcmp(parser_tokval(parser), "break"))
4917 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4918 else if (parser->tok == TOKEN_KEYWORD)
4921 name = util_strdup(parser_tokval(parser));
4924 if (!parser_next(parser)) {
4927 parseerror(parser, "error after variable or field declaration");
4933 /* now this may be an array */
4934 if (parser->tok == '[') {
4936 var = parse_arraysize(parser, var);
4938 if (name) mem_d(name);
4943 /* This is the point where we can turn it into a field */
4945 /* turn it into a field if desired */
4946 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4947 tmp->expression.next = (ast_expression*)var;
4951 /* now there may be function parens again */
4952 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4953 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4954 if (parser->tok == '(' && wasarray)
4955 parseerror(parser, "arrays as part of a return type is not supported");
4956 while (parser->tok == '(') {
4957 var = parse_parameter_list(parser, var);
4959 if (name) mem_d(name);
4964 /* finally name it */
4966 if (!ast_value_set_name(var, name)) {
4969 parseerror(parser, "internal error: failed to set name");
4972 /* free the name, ast_value_set_name duplicates */
4979 static bool parse_typedef(parser_t *parser)
4981 ast_value *typevar, *oldtype;
4982 ast_expression *old;
4984 typevar = parse_typename(parser, NULL, NULL, NULL);
4989 /* while parsing types, the ast_value's get named '<something>' */
4990 if (!typevar->name || typevar->name[0] == '<') {
4991 parseerror(parser, "missing name in typedef");
4992 ast_delete(typevar);
4996 if ( (old = parser_find_var(parser, typevar->name)) ) {
4997 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4998 " -> `%s` has been declared here: %s:%i",
4999 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5000 ast_delete(typevar);
5004 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5005 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5006 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5007 ast_delete(typevar);
5011 vec_push(parser->_typedefs, typevar);
5012 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5014 if (parser->tok != ';') {
5015 parseerror(parser, "expected semicolon after typedef");
5018 if (!parser_next(parser)) {
5019 parseerror(parser, "parse error after typedef");
5026 static const char *cvq_to_str(int cvq) {
5028 case CV_NONE: return "none";
5029 case CV_VAR: return "`var`";
5030 case CV_CONST: return "`const`";
5031 default: return "<INVALID>";
5035 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5038 if (proto->cvq != var->cvq) {
5039 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5040 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5041 parser->tok == '='))
5043 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5044 "`%s` declared with different qualifiers: %s\n"
5045 " -> previous declaration here: %s:%i uses %s",
5046 var->name, cvq_to_str(var->cvq),
5047 ast_ctx(proto).file, ast_ctx(proto).line,
5048 cvq_to_str(proto->cvq));
5051 av = (var ->expression.flags & AST_FLAG_NORETURN);
5052 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5054 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5055 "`%s` declared with different attributes%s\n"
5056 " -> previous declaration here: %s:%i",
5057 var->name, (av ? ": noreturn" : ""),
5058 ast_ctx(proto).file, ast_ctx(proto).line,
5059 (ao ? ": noreturn" : ""));
5064 static bool create_array_accessors(parser_t *parser, ast_value *var)
5067 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5068 if (!parser_create_array_setter(parser, var, name))
5070 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5071 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5076 static bool parse_array(parser_t *parser, ast_value *array)
5079 if (array->initlist) {
5080 parseerror(parser, "array already initialized elsewhere");
5083 if (!parser_next(parser)) {
5084 parseerror(parser, "parse error in array initializer");
5088 while (parser->tok != '}') {
5089 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5092 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5094 parseerror(parser, "initializing element must be a compile time constant");
5097 vec_push(array->initlist, v->constval);
5098 if (v->expression.vtype == TYPE_STRING) {
5099 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5103 if (parser->tok == '}')
5105 if (parser->tok != ',' || !parser_next(parser)) {
5106 parseerror(parser, "expected comma or '}' in element list");
5110 if (!parser_next(parser) || parser->tok != ';') {
5111 parseerror(parser, "expected semicolon after initializer, got %s");
5115 if (!parser_next(parser)) {
5116 parseerror(parser, "parse error after initializer");
5121 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5122 if (array->expression.count != (size_t)-1) {
5123 parseerror(parser, "array `%s' has already been initialized with %u elements",
5124 array->name, (unsigned)array->expression.count);
5126 array->expression.count = vec_size(array->initlist);
5127 if (!create_array_accessors(parser, array))
5133 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)
5137 ast_expression *old;
5141 ast_value *basetype = NULL;
5143 bool isparam = false;
5144 bool isvector = false;
5145 bool cleanvar = true;
5146 bool wasarray = false;
5148 ast_member *me[3] = { NULL, NULL, NULL };
5150 if (!localblock && is_static)
5151 parseerror(parser, "`static` qualifier is not supported in global scope");
5153 /* get the first complete variable */
5154 var = parse_typename(parser, &basetype, cached_typedef, NULL);
5157 ast_delete(basetype);
5161 /* while parsing types, the ast_value's get named '<something>' */
5162 if (!var->name || var->name[0] == '<') {
5163 parseerror(parser, "declaration does not declare anything");
5165 ast_delete(basetype);
5173 /* Part 0: finish the type */
5174 if (parser->tok == '(') {
5175 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5176 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5177 var = parse_parameter_list(parser, var);
5183 /* we only allow 1-dimensional arrays */
5184 if (parser->tok == '[') {
5186 var = parse_arraysize(parser, var);
5192 if (parser->tok == '(' && wasarray) {
5193 parseerror(parser, "arrays as part of a return type is not supported");
5194 /* we'll still parse the type completely for now */
5196 /* for functions returning functions */
5197 while (parser->tok == '(') {
5198 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5199 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5200 var = parse_parameter_list(parser, var);
5207 var->cvq = qualifier;
5208 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5209 var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5210 var->expression.flags |= qflags;
5213 * store the vstring back to var for alias and
5214 * deprecation messages.
5216 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5217 var->expression.flags & AST_FLAG_ALIAS)
5218 var->desc = vstring;
5220 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5221 parseerror(parser, "function aliases cannot be forward declared");
5228 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5229 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5230 * is then filled with the previous definition and the parameter-names replaced.
5232 if (!strcmp(var->name, "nil")) {
5233 if (OPTS_FLAG(UNTYPED_NIL)) {
5234 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5235 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5237 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5240 /* Deal with end_sys_ vars */
5242 if (!strcmp(var->name, "end_sys_globals")) {
5244 parser->crc_globals = vec_size(parser->globals);
5247 else if (!strcmp(var->name, "end_sys_fields")) {
5249 parser->crc_fields = vec_size(parser->fields);
5252 if (was_end && var->expression.vtype == TYPE_FIELD) {
5253 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5254 "global '%s' hint should not be a field",
5255 parser_tokval(parser)))
5262 if (!nofields && var->expression.vtype == TYPE_FIELD)
5264 /* deal with field declarations */
5265 old = parser_find_field(parser, var->name);
5267 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5268 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5277 parseerror(parser, "field `%s` already declared here: %s:%i",
5278 var->name, ast_ctx(old).file, ast_ctx(old).line);
5283 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5284 (old = parser_find_global(parser, var->name)))
5286 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5287 parseerror(parser, "field `%s` already declared here: %s:%i",
5288 var->name, ast_ctx(old).file, ast_ctx(old).line);
5295 /* deal with other globals */
5296 old = parser_find_global(parser, var->name);
5297 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5299 /* This is a function which had a prototype */
5300 if (!ast_istype(old, ast_value)) {
5301 parseerror(parser, "internal error: prototype is not an ast_value");
5305 proto = (ast_value*)old;
5306 proto->desc = var->desc;
5307 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5308 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5310 ast_ctx(proto).file, ast_ctx(proto).line);
5314 /* we need the new parameter-names */
5315 for (i = 0; i < vec_size(proto->expression.params); ++i)
5316 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5317 if (!parser_check_qualifiers(parser, var, proto)) {
5324 proto->expression.flags |= var->expression.flags;
5332 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5333 "global `%s` already declared here: %s:%i",
5334 var->name, ast_ctx(old).file, ast_ctx(old).line))
5339 if (old->flags & AST_FLAG_FINAL_DECL) {
5340 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5341 var->name, ast_ctx(old).file, ast_ctx(old).line);
5345 proto = (ast_value*)old;
5346 if (!ast_istype(old, ast_value)) {
5347 parseerror(parser, "internal error: not an ast_value");
5352 if (!parser_check_qualifiers(parser, var, proto)) {
5357 proto->expression.flags |= var->expression.flags;
5358 /* copy the context for finals,
5359 * so the error can show where it was actually made 'final'
5361 if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5362 ast_ctx(old) = ast_ctx(var);
5366 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5367 (old = parser_find_field(parser, var->name)))
5369 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5370 parseerror(parser, "global `%s` already declared here: %s:%i",
5371 var->name, ast_ctx(old).file, ast_ctx(old).line);
5378 else /* it's not a global */
5380 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5381 if (old && !isparam) {
5382 parseerror(parser, "local `%s` already declared here: %s:%i",
5383 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5387 /* doing this here as the above is just for a single scope */
5388 old = parser_find_local(parser, var->name, 0, &isparam);
5389 if (old && isparam) {
5390 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5391 "local `%s` is shadowing a parameter", var->name))
5393 parseerror(parser, "local `%s` already declared here: %s:%i",
5394 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5398 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5400 if (ast_istype(old, ast_value))
5401 var = proto = (ast_value*)old;
5410 /* in a noref section we simply bump the usecount */
5411 if (noref || parser->noref)
5415 * Create the global/local, and deal with vector types.
5418 if (var->expression.vtype == TYPE_VECTOR)
5420 else if (var->expression.vtype == TYPE_FIELD &&
5421 var->expression.next->vtype == TYPE_VECTOR)
5425 if (!create_vector_members(var, me)) {
5432 /* deal with global variables, fields, functions */
5433 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5434 var->isfield = true;
5435 vec_push(parser->fields, (ast_expression*)var);
5436 util_htset(parser->htfields, var->name, var);
5438 for (i = 0; i < 3; ++i) {
5439 vec_push(parser->fields, (ast_expression*)me[i]);
5440 util_htset(parser->htfields, me[i]->name, me[i]);
5445 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5446 parser_addglobal(parser, var->name, (ast_expression*)var);
5448 for (i = 0; i < 3; ++i) {
5449 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5453 ast_expression *find = parser_find_global(parser, var->desc);
5456 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5460 if (!ast_compare_type((ast_expression*)var, find)) {
5464 ast_type_to_string(find, ty1, sizeof(ty1));
5465 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5467 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5474 * add alias to aliases table and to corrector
5475 * so corrections can apply for aliases as well.
5477 util_htset(parser->aliases, var->name, find);
5480 * add to corrector so corrections can work
5481 * even for aliases too.
5484 vec_last(parser->correct_variables),
5485 &vec_last(parser->correct_variables_score),
5489 /* generate aliases for vector components */
5493 util_asprintf(&buffer[0], "%s_x", var->desc);
5494 util_asprintf(&buffer[1], "%s_y", var->desc);
5495 util_asprintf(&buffer[2], "%s_z", var->desc);
5497 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5498 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5499 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5506 * add to corrector so corrections can work
5507 * even for aliases too.
5510 vec_last(parser->correct_variables),
5511 &vec_last(parser->correct_variables_score),
5515 vec_last(parser->correct_variables),
5516 &vec_last(parser->correct_variables_score),
5520 vec_last(parser->correct_variables),
5521 &vec_last(parser->correct_variables_score),
5529 /* a static adds itself to be generated like any other global
5530 * but is added to the local namespace instead
5532 char *defname = NULL;
5533 size_t prefix_len, ln;
5536 ln = strlen(parser->function->name);
5537 vec_append(defname, ln, parser->function->name);
5539 vec_append(defname, 2, "::");
5540 /* remember the length up to here */
5541 prefix_len = vec_size(defname);
5543 /* Add it to the local scope */
5544 util_htset(vec_last(parser->variables), var->name, (void*)var);
5548 vec_last(parser->correct_variables),
5549 &vec_last(parser->correct_variables_score),
5553 /* now rename the global */
5554 ln = strlen(var->name);
5555 vec_append(defname, ln, var->name);
5556 /* if a variable of that name already existed, add the
5558 * The counter is incremented either way.
5560 sn_size = vec_size(parser->function->static_names);
5561 for (sn = 0; sn != sn_size; ++sn) {
5562 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5565 if (sn != sn_size) {
5567 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5568 vec_append(defname, len, num);
5572 vec_push(parser->function->static_names, util_strdup(var->name));
5573 parser->function->static_count++;
5574 ast_value_set_name(var, defname);
5576 /* push it to the to-be-generated globals */
5577 vec_push(parser->globals, (ast_expression*)var);
5579 /* same game for the vector members */
5581 for (i = 0; i < 3; ++i) {
5582 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5586 vec_last(parser->correct_variables),
5587 &vec_last(parser->correct_variables_score),
5591 vec_shrinkto(defname, prefix_len);
5592 ln = strlen(me[i]->name);
5593 vec_append(defname, ln, me[i]->name);
5594 ast_member_set_name(me[i], defname);
5596 vec_push(parser->globals, (ast_expression*)me[i]);
5601 vec_push(localblock->locals, var);
5602 parser_addlocal(parser, var->name, (ast_expression*)var);
5604 for (i = 0; i < 3; ++i) {
5605 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5606 ast_block_collect(localblock, (ast_expression*)me[i]);
5612 me[0] = me[1] = me[2] = NULL;
5617 if (var->expression.vtype == TYPE_ARRAY) {
5618 if (var->expression.count != (size_t)-1) {
5619 if (!create_array_accessors(parser, var))
5623 else if (!localblock && !nofields &&
5624 var->expression.vtype == TYPE_FIELD &&
5625 var->expression.next->vtype == TYPE_ARRAY)
5628 ast_expression *telem;
5630 ast_value *array = (ast_value*)var->expression.next;
5632 if (!ast_istype(var->expression.next, ast_value)) {
5633 parseerror(parser, "internal error: field element type must be an ast_value");
5637 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5638 if (!parser_create_array_field_setter(parser, array, name))
5641 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5642 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5643 tfield->expression.next = telem;
5644 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5645 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5653 if (parser->tok == ';') {
5654 ast_delete(basetype);
5655 if (!parser_next(parser)) {
5656 parseerror(parser, "error after variable declaration");
5662 if (parser->tok == ',')
5666 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5669 parseerror(parser, "missing comma or semicolon while parsing variables");
5673 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5674 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5675 "initializing expression turns variable `%s` into a constant in this standard",
5682 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5683 if (parser->tok != '=') {
5684 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5688 if (!parser_next(parser)) {
5689 parseerror(parser, "error parsing initializer");
5693 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5694 parseerror(parser, "expected '=' before function body in this standard");
5697 if (parser->tok == '#') {
5698 ast_function *func = NULL;
5699 ast_value *number = NULL;
5705 parseerror(parser, "cannot declare builtins within functions");
5708 if (var->expression.vtype != TYPE_FUNCTION) {
5709 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5712 if (!parser_next(parser)) {
5713 parseerror(parser, "expected builtin number");
5717 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5718 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5720 parseerror(parser, "builtin number expected");
5723 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5726 parseerror(parser, "builtin number must be a compile time constant");
5729 if (number->expression.vtype == TYPE_INTEGER)
5730 builtin_num = number->constval.vint;
5731 else if (number->expression.vtype == TYPE_FLOAT)
5732 builtin_num = number->constval.vfloat;
5735 parseerror(parser, "builtin number must be an integer constant");
5740 fractional = modff(builtin_num, &integral);
5741 if (builtin_num < 0 || fractional != 0) {
5742 parseerror(parser, "builtin number must be an integer greater than zero");
5746 /* we only want the integral part anyways */
5747 builtin_num = integral;
5748 } else if (parser->tok == TOKEN_INTCONST) {
5749 builtin_num = parser_token(parser)->constval.i;
5751 parseerror(parser, "builtin number must be a compile time constant");
5755 if (var->hasvalue) {
5756 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5757 "builtin `%s` has already been defined\n"
5758 " -> previous declaration here: %s:%i",
5759 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5763 func = ast_function_new(ast_ctx(var), var->name, var);
5765 parseerror(parser, "failed to allocate function for `%s`", var->name);
5768 vec_push(parser->functions, func);
5770 func->builtin = -builtin_num-1;
5773 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5774 ? (parser->tok != ',' && parser->tok != ';')
5775 : (!parser_next(parser)))
5777 parseerror(parser, "expected comma or semicolon");
5779 ast_function_delete(func);
5780 var->constval.vfunc = NULL;
5784 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5787 /* Note that fteqcc and most others don't even *have*
5788 * local arrays, so this is not a high priority.
5790 parseerror(parser, "TODO: initializers for local arrays");
5794 var->hasvalue = true;
5795 if (!parse_array(parser, var))
5798 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5801 parseerror(parser, "cannot declare functions within functions");
5806 ast_ctx(proto) = parser_ctx(parser);
5808 if (!parse_function_body(parser, var))
5810 ast_delete(basetype);
5811 for (i = 0; i < vec_size(parser->gotos); ++i)
5812 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5813 vec_free(parser->gotos);
5814 vec_free(parser->labels);
5817 ast_expression *cexp;
5820 cexp = parse_expression_leave(parser, true, false, false);
5824 if (!localblock || is_static) {
5825 cval = (ast_value*)cexp;
5826 if (cval != parser->nil &&
5827 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5830 parseerror(parser, "initializer is non constant");
5835 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5836 qualifier != CV_VAR)
5838 var->cvq = CV_CONST;
5840 if (cval == parser->nil)
5841 var->expression.flags |= AST_FLAG_INITIALIZED;
5844 var->hasvalue = true;
5845 if (cval->expression.vtype == TYPE_STRING)
5846 var->constval.vstring = parser_strdup(cval->constval.vstring);
5847 else if (cval->expression.vtype == TYPE_FIELD)
5848 var->constval.vfield = cval;
5850 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5856 shunt sy = { NULL, NULL, NULL, NULL };
5859 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5860 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5861 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5862 if (!parser_sy_apply_operator(parser, &sy))
5865 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5866 parseerror(parser, "internal error: leaked operands");
5867 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5875 /* a constant initialized to an inexact value should be marked inexact:
5876 * const float x = <inexact>; should propagate the inexact flag
5878 if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5879 cval = (ast_value*)cexp;
5880 if (ast_istype(cexp, ast_value) && cval->hasvalue && cval->cvq == CV_CONST)
5881 var->inexact = cval->inexact;
5886 if (parser->tok == ',') {
5887 if (!parser_next(parser)) {
5888 parseerror(parser, "expected another variable");
5892 if (parser->tok != TOKEN_IDENT) {
5893 parseerror(parser, "expected another variable");
5896 var = ast_value_copy(basetype);
5898 ast_value_set_name(var, parser_tokval(parser));
5899 if (!parser_next(parser)) {
5900 parseerror(parser, "error parsing variable declaration");
5906 if (parser->tok != ';') {
5907 parseerror(parser, "missing semicolon after variables");
5911 if (!parser_next(parser)) {
5912 parseerror(parser, "parse error after variable declaration");
5916 ast_delete(basetype);
5920 if (cleanvar && var)
5922 ast_delete(basetype);
5926 ast_delete(basetype);
5927 if (cleanvar && var)
5929 if (me[0]) ast_member_delete(me[0]);
5930 if (me[1]) ast_member_delete(me[1]);
5931 if (me[2]) ast_member_delete(me[2]);
5935 static bool parser_global_statement(parser_t *parser)
5939 bool is_static = false;
5940 uint32_t qflags = 0;
5941 ast_value *istype = NULL;
5942 char *vstring = NULL;
5944 if (parser->tok == TOKEN_IDENT)
5945 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5947 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5949 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5951 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5953 if (cvq == CV_WRONG)
5955 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5957 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5959 return parse_enum(parser);
5961 else if (parser->tok == TOKEN_KEYWORD)
5963 if (!strcmp(parser_tokval(parser), "typedef")) {
5964 if (!parser_next(parser)) {
5965 parseerror(parser, "expected type definition after 'typedef'");
5968 return parse_typedef(parser);
5970 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5973 else if (parser->tok == '#')
5975 return parse_pragma(parser);
5977 else if (parser->tok == '$')
5979 if (!parser_next(parser)) {
5980 parseerror(parser, "parse error");
5986 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5992 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5994 return util_crc16(old, str, strlen(str));
5997 static void progdefs_crc_file(const char *str)
5999 /* write to progdefs.h here */
6003 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6005 old = progdefs_crc_sum(old, str);
6006 progdefs_crc_file(str);
6010 static void generate_checksum(parser_t *parser, ir_builder *ir)
6012 uint16_t crc = 0xFFFF;
6016 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6017 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6019 progdefs_crc_file("\tint\tpad;\n");
6020 progdefs_crc_file("\tint\tofs_return[3];\n");
6021 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6022 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6023 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6024 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6025 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6026 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6027 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6028 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6030 for (i = 0; i < parser->crc_globals; ++i) {
6031 if (!ast_istype(parser->globals[i], ast_value))
6033 value = (ast_value*)(parser->globals[i]);
6034 switch (value->expression.vtype) {
6035 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6036 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6037 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6038 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6040 crc = progdefs_crc_both(crc, "\tint\t");
6043 crc = progdefs_crc_both(crc, value->name);
6044 crc = progdefs_crc_both(crc, ";\n");
6046 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6047 for (i = 0; i < parser->crc_fields; ++i) {
6048 if (!ast_istype(parser->fields[i], ast_value))
6050 value = (ast_value*)(parser->fields[i]);
6051 switch (value->expression.next->vtype) {
6052 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6053 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6054 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6055 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6057 crc = progdefs_crc_both(crc, "\tint\t");
6060 crc = progdefs_crc_both(crc, value->name);
6061 crc = progdefs_crc_both(crc, ";\n");
6063 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6064 ir->code->crc = crc;
6067 parser_t *parser_create()
6070 lex_ctx_t empty_ctx;
6073 parser = (parser_t*)mem_a(sizeof(parser_t));
6077 memset(parser, 0, sizeof(*parser));
6079 for (i = 0; i < operator_count; ++i) {
6080 if (operators[i].id == opid1('=')) {
6081 parser->assign_op = operators+i;
6085 if (!parser->assign_op) {
6086 con_err("internal error: initializing parser: failed to find assign operator\n");
6091 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6092 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6093 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6094 vec_push(parser->_blocktypedefs, 0);
6096 parser->aliases = util_htnew(PARSER_HT_SIZE);
6099 vec_push(parser->correct_variables, correct_trie_new());
6100 vec_push(parser->correct_variables_score, NULL);
6102 empty_ctx.file = "<internal>";
6104 empty_ctx.column = 0;
6105 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6106 parser->nil->cvq = CV_CONST;
6107 if (OPTS_FLAG(UNTYPED_NIL))
6108 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6110 parser->max_param_count = 1;
6112 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6113 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6114 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6116 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6117 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6118 parser->reserved_version->cvq = CV_CONST;
6119 parser->reserved_version->hasvalue = true;
6120 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6121 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6123 parser->reserved_version = NULL;
6126 parser->fold = fold_init (parser);
6127 parser->intrin = intrin_init(parser);
6131 static bool parser_compile(parser_t *parser)
6133 /* initial lexer/parser state */
6134 parser->lex->flags.noops = true;
6136 if (parser_next(parser))
6138 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6140 if (!parser_global_statement(parser)) {
6141 if (parser->tok == TOKEN_EOF)
6142 parseerror(parser, "unexpected end of file");
6143 else if (compile_errors)
6144 parseerror(parser, "there have been errors, bailing out");
6145 lex_close(parser->lex);
6151 parseerror(parser, "parse error");
6152 lex_close(parser->lex);
6157 lex_close(parser->lex);
6160 return !compile_errors;
6163 bool parser_compile_file(parser_t *parser, const char *filename)
6165 parser->lex = lex_open(filename);
6167 con_err("failed to open file \"%s\"\n", filename);
6170 return parser_compile(parser);
6173 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6175 parser->lex = lex_open_string(str, len, name);
6177 con_err("failed to create lexer for string \"%s\"\n", name);
6180 return parser_compile(parser);
6183 static void parser_remove_ast(parser_t *parser)
6186 if (parser->ast_cleaned)
6188 parser->ast_cleaned = true;
6189 for (i = 0; i < vec_size(parser->accessors); ++i) {
6190 ast_delete(parser->accessors[i]->constval.vfunc);
6191 parser->accessors[i]->constval.vfunc = NULL;
6192 ast_delete(parser->accessors[i]);
6194 for (i = 0; i < vec_size(parser->functions); ++i) {
6195 ast_delete(parser->functions[i]);
6197 for (i = 0; i < vec_size(parser->fields); ++i) {
6198 ast_delete(parser->fields[i]);
6200 for (i = 0; i < vec_size(parser->globals); ++i) {
6201 ast_delete(parser->globals[i]);
6203 vec_free(parser->accessors);
6204 vec_free(parser->functions);
6205 vec_free(parser->globals);
6206 vec_free(parser->fields);
6208 for (i = 0; i < vec_size(parser->variables); ++i)
6209 util_htdel(parser->variables[i]);
6210 vec_free(parser->variables);
6211 vec_free(parser->_blocklocals);
6212 vec_free(parser->_locals);
6215 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6216 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6218 vec_free(parser->correct_variables);
6219 vec_free(parser->correct_variables_score);
6221 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6222 ast_delete(parser->_typedefs[i]);
6223 vec_free(parser->_typedefs);
6224 for (i = 0; i < vec_size(parser->typedefs); ++i)
6225 util_htdel(parser->typedefs[i]);
6226 vec_free(parser->typedefs);
6227 vec_free(parser->_blocktypedefs);
6229 vec_free(parser->_block_ctx);
6231 vec_free(parser->labels);
6232 vec_free(parser->gotos);
6233 vec_free(parser->breaks);
6234 vec_free(parser->continues);
6236 ast_value_delete(parser->nil);
6238 ast_value_delete(parser->const_vec[0]);
6239 ast_value_delete(parser->const_vec[1]);
6240 ast_value_delete(parser->const_vec[2]);
6242 if (parser->reserved_version)
6243 ast_value_delete(parser->reserved_version);
6245 util_htdel(parser->aliases);
6246 fold_cleanup(parser->fold);
6247 intrin_cleanup(parser->intrin);
6250 void parser_cleanup(parser_t *parser)
6252 parser_remove_ast(parser);
6256 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6258 ast_expression *expr;
6262 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6266 for (i = 0; i != vec_size(parser->functions); ++i) {
6267 if (!strcmp(parser->functions[i]->name, "coverage")) {
6268 func = parser->functions[i];
6273 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6274 con_out("coverage support requested but no coverage() builtin declared\n");
6275 ir_builder_delete(ir);
6282 expr = (ast_expression*)cov;
6284 if (expr->vtype != TYPE_FUNCTION || vec_size(expr->params) != 0) {
6286 ast_type_to_string(expr, ty, sizeof(ty));
6287 con_out("invalid type for coverage(): %s\n", ty);
6288 ir_builder_delete(ir);
6292 ir->coverage_func = func->ir_func->value;
6296 bool parser_finish(parser_t *parser, const char *output)
6302 if (compile_errors) {
6303 con_out("*** there were compile errors\n");
6307 ir = ir_builder_new("gmqcc_out");
6309 con_out("failed to allocate builder\n");
6313 for (i = 0; i < vec_size(parser->fields); ++i) {
6316 if (!ast_istype(parser->fields[i], ast_value))
6318 field = (ast_value*)parser->fields[i];
6319 hasvalue = field->hasvalue;
6320 field->hasvalue = false;
6321 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6322 con_out("failed to generate field %s\n", field->name);
6323 ir_builder_delete(ir);
6328 ast_expression *subtype;
6329 field->hasvalue = true;
6330 subtype = field->expression.next;
6331 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6332 if (subtype->vtype == TYPE_FIELD)
6333 ifld->fieldtype = subtype->next->vtype;
6334 else if (subtype->vtype == TYPE_FUNCTION)
6335 ifld->outtype = subtype->next->vtype;
6336 (void)!ir_value_set_field(field->ir_v, ifld);
6339 for (i = 0; i < vec_size(parser->globals); ++i) {
6341 if (!ast_istype(parser->globals[i], ast_value))
6343 asvalue = (ast_value*)(parser->globals[i]);
6344 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6345 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6346 "unused global: `%s`", asvalue->name);
6348 if (!ast_global_codegen(asvalue, ir, false)) {
6349 con_out("failed to generate global %s\n", asvalue->name);
6350 ir_builder_delete(ir);
6354 /* Build function vararg accessor ast tree now before generating
6355 * immediates, because the accessors may add new immediates
6357 for (i = 0; i < vec_size(parser->functions); ++i) {
6358 ast_function *f = parser->functions[i];
6360 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6361 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6362 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6363 con_out("failed to generate vararg setter for %s\n", f->name);
6364 ir_builder_delete(ir);
6367 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6368 con_out("failed to generate vararg getter for %s\n", f->name);
6369 ir_builder_delete(ir);
6373 ast_delete(f->varargs);
6378 /* Now we can generate immediates */
6379 if (!fold_generate(parser->fold, ir))
6382 /* before generating any functions we need to set the coverage_func */
6383 if (!parser_set_coverage_func(parser, ir))
6386 for (i = 0; i < vec_size(parser->globals); ++i) {
6388 if (!ast_istype(parser->globals[i], ast_value))
6390 asvalue = (ast_value*)(parser->globals[i]);
6391 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6393 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6394 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6395 "uninitialized constant: `%s`",
6397 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6398 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6399 "uninitialized global: `%s`",
6402 if (!ast_generate_accessors(asvalue, ir)) {
6403 ir_builder_delete(ir);
6407 for (i = 0; i < vec_size(parser->fields); ++i) {
6409 asvalue = (ast_value*)(parser->fields[i]->next);
6411 if (!ast_istype((ast_expression*)asvalue, ast_value))
6413 if (asvalue->expression.vtype != TYPE_ARRAY)
6415 if (!ast_generate_accessors(asvalue, ir)) {
6416 ir_builder_delete(ir);
6420 if (parser->reserved_version &&
6421 !ast_global_codegen(parser->reserved_version, ir, false))
6423 con_out("failed to generate reserved::version");
6424 ir_builder_delete(ir);
6427 for (i = 0; i < vec_size(parser->functions); ++i) {
6428 ast_function *f = parser->functions[i];
6429 if (!ast_function_codegen(f, ir)) {
6430 con_out("failed to generate function %s\n", f->name);
6431 ir_builder_delete(ir);
6436 generate_checksum(parser, ir);
6438 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6439 ir_builder_dump(ir, con_out);
6440 for (i = 0; i < vec_size(parser->functions); ++i) {
6441 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6442 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6443 ir_builder_delete(ir);
6447 parser_remove_ast(parser);
6449 if (compile_Werrors) {
6450 con_out("*** there were warnings treated as errors\n");
6451 compile_show_werrors();
6456 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6457 ir_builder_dump(ir, con_out);
6459 if (!ir_builder_generate(ir, output)) {
6460 con_out("*** failed to generate output file\n");
6461 ir_builder_delete(ir);
6465 ir_builder_delete(ir);