9 #define PARSER_HT_LOCALS 2
10 #define PARSER_HT_SIZE 512
11 #define TYPEDEF_HT_SIZE 512
13 static void parser_enterblock(parser_t *parser);
14 static bool parser_leaveblock(parser_t *parser);
15 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
16 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
17 static bool parse_typedef(parser_t *parser);
18 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);
19 static ast_block* parse_block(parser_t *parser);
20 static bool parse_block_into(parser_t *parser, ast_block *block);
21 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
22 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
23 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
24 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
25 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
26 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
27 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
29 static void parseerror(parser_t *parser, const char *fmt, ...)
33 vcompile_error(parser->lex->tok.ctx, fmt, ap);
37 /* returns true if it counts as an error */
38 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
43 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
48 /**********************************************************************
52 static bool parser_next(parser_t *parser)
54 /* lex_do kills the previous token */
55 parser->tok = lex_do(parser->lex);
56 if (parser->tok == TOKEN_EOF)
58 if (parser->tok >= TOKEN_ERROR) {
59 parseerror(parser, "lex error");
65 #define parser_tokval(p) ((p)->lex->tok.value)
66 #define parser_token(p) (&((p)->lex->tok))
68 char *parser_strdup(const char *str)
71 /* actually dup empty strings */
72 char *out = (char*)mem_a(1);
76 return util_strdup(str);
79 static ast_expression* parser_find_field(parser_t *parser, const char *name)
81 return ( ast_expression*)util_htget(parser->htfields, name);
84 static ast_expression* parser_find_label(parser_t *parser, const char *name)
86 for (auto &it : parser->labels)
87 if (!strcmp(it->name, name))
88 return (ast_expression*)it;
92 ast_expression* parser_find_global(parser_t *parser, const char *name)
94 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
97 return (ast_expression*)util_htget(parser->htglobals, name);
100 static ast_expression* parser_find_param(parser_t *parser, const char *name)
103 if (!parser->function)
105 fun = parser->function->function_type;
106 for (auto &it : fun->expression.type_params) {
107 if (!strcmp(it->name, name))
108 return (ast_expression*)it;
113 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
118 hash = util_hthash(parser->htglobals, name);
121 for (i = vec_size(parser->variables); i > upto;) {
123 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
127 return parser_find_param(parser, name);
130 static ast_expression* parser_find_var(parser_t *parser, const char *name)
134 v = parser_find_local(parser, name, 0, &dummy);
135 if (!v) v = parser_find_global(parser, name);
139 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
143 hash = util_hthash(parser->typedefs[0], name);
145 for (i = vec_size(parser->typedefs); i > upto;) {
147 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
154 size_t etype; /* 0 = expression, others are operators */
158 ast_block *block; /* for commas and function calls */
171 std::vector<sy_elem> out;
172 std::vector<sy_elem> ops;
173 std::vector<size_t> argc;
174 std::vector<unsigned int> paren;
177 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
188 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
192 e.out = (ast_expression*)v;
199 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
201 e.etype = 1 + (op - operators);
210 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
221 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
222 * so we need to rotate it to become ent.(foo[n]).
224 static bool rotate_entfield_array_index_nodes(ast_expression **out)
226 ast_array_index *index, *oldindex;
227 ast_entfield *entfield;
231 ast_expression *entity;
233 lex_ctx_t ctx = ast_ctx(*out);
235 if (!ast_istype(*out, ast_array_index))
237 index = (ast_array_index*)*out;
239 if (!ast_istype(index->array, ast_entfield))
241 entfield = (ast_entfield*)index->array;
243 if (!ast_istype(entfield->field, ast_value))
245 field = (ast_value*)entfield->field;
248 entity = entfield->entity;
252 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
253 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
254 *out = (ast_expression*)entfield;
256 oldindex->array = nullptr;
257 oldindex->index = nullptr;
258 ast_delete(oldindex);
263 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
265 if (ast_istype(expr, ast_value)) {
266 ast_value *val = (ast_value*)expr;
267 if (val->cvq == CV_CONST) {
268 if (val->name[0] == '#') {
269 compile_error(ctx, "invalid assignment to a literal constant");
273 * To work around quakeworld we must elide the error and make it
276 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
277 compile_error(ctx, "assignment to constant `%s`", val->name);
279 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
286 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
290 ast_expression *out = nullptr;
291 ast_expression *exprs[3];
292 ast_block *blocks[3];
293 ast_binstore *asbinstore;
294 size_t i, assignop, addop, subop;
295 qcint_t generated_op = 0;
300 if (sy->ops.empty()) {
301 parseerror(parser, "internal error: missing operator");
305 if (sy->ops.back().isparen) {
306 parseerror(parser, "unmatched parenthesis");
310 op = &operators[sy->ops.back().etype - 1];
311 ctx = sy->ops.back().ctx;
313 if (sy->out.size() < op->operands) {
314 if (op->flags & OP_PREFIX)
315 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
316 else /* this should have errored previously already */
317 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
323 /* op(:?) has no input and no output */
327 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
328 for (i = 0; i < op->operands; ++i) {
329 exprs[i] = sy->out[sy->out.size()+i].out;
330 blocks[i] = sy->out[sy->out.size()+i].block;
332 if (exprs[i]->vtype == TYPE_NOEXPR &&
333 !(i != 0 && op->id == opid2('?',':')) &&
334 !(i == 1 && op->id == opid1('.')))
336 if (ast_istype(exprs[i], ast_label))
337 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
339 compile_error(ast_ctx(exprs[i]), "not an expression");
340 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
344 if (blocks[0] && blocks[0]->exprs.empty() && op->id != opid1(',')) {
345 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
349 #define NotSameType(T) \
350 (exprs[0]->vtype != exprs[1]->vtype || \
351 exprs[0]->vtype != T)
356 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
360 if (exprs[0]->vtype == TYPE_VECTOR &&
361 exprs[1]->vtype == TYPE_NOEXPR)
363 if (exprs[1] == (ast_expression*)parser->const_vec[0])
364 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, nullptr);
365 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
366 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, nullptr);
367 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
368 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, nullptr);
370 compile_error(ctx, "access to invalid vector component");
374 else if (exprs[0]->vtype == TYPE_ENTITY) {
375 if (exprs[1]->vtype != TYPE_FIELD) {
376 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
379 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
381 else if (exprs[0]->vtype == TYPE_VECTOR) {
382 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
386 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
392 if (exprs[0]->vtype != TYPE_ARRAY &&
393 !(exprs[0]->vtype == TYPE_FIELD &&
394 exprs[0]->next->vtype == TYPE_ARRAY))
396 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
397 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
400 if (exprs[1]->vtype != TYPE_FLOAT) {
401 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
402 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
405 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
406 rotate_entfield_array_index_nodes(&out);
410 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
411 sy->out.push_back(syexp(ctx, exprs[0]));
412 sy->out.push_back(syexp(ctx, exprs[1]));
417 if (!ast_block_add_expr(blocks[0], exprs[1]))
420 blocks[0] = ast_block_new(ctx);
421 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
422 !ast_block_add_expr(blocks[0], exprs[1]))
427 ast_block_set_type(blocks[0], exprs[1]);
429 sy->out.push_back(syblock(ctx, blocks[0]));
436 if ((out = parser->m_fold.op(op, exprs)))
439 if (exprs[0]->vtype != TYPE_FLOAT &&
440 exprs[0]->vtype != TYPE_VECTOR) {
441 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
442 type_name[exprs[0]->vtype]);
445 if (exprs[0]->vtype == TYPE_FLOAT)
446 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
448 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
452 if (!(out = parser->m_fold.op(op, exprs))) {
453 switch (exprs[0]->vtype) {
455 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
458 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
461 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
462 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
464 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
466 /* we don't constant-fold NOT for these types */
468 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
471 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
474 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
475 type_name[exprs[0]->vtype]);
482 if (exprs[0]->vtype != exprs[1]->vtype ||
483 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
485 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
486 type_name[exprs[0]->vtype],
487 type_name[exprs[1]->vtype]);
490 if (!(out = parser->m_fold.op(op, exprs))) {
491 switch (exprs[0]->vtype) {
493 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
496 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
499 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
500 type_name[exprs[0]->vtype],
501 type_name[exprs[1]->vtype]);
507 if (exprs[0]->vtype != exprs[1]->vtype ||
508 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
510 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
511 type_name[exprs[1]->vtype],
512 type_name[exprs[0]->vtype]);
515 if (!(out = parser->m_fold.op(op, exprs))) {
516 switch (exprs[0]->vtype) {
518 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
521 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
524 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
525 type_name[exprs[1]->vtype],
526 type_name[exprs[0]->vtype]);
532 if (exprs[0]->vtype != exprs[1]->vtype &&
533 !(exprs[0]->vtype == TYPE_VECTOR &&
534 exprs[1]->vtype == TYPE_FLOAT) &&
535 !(exprs[1]->vtype == TYPE_VECTOR &&
536 exprs[0]->vtype == TYPE_FLOAT)
539 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
540 type_name[exprs[1]->vtype],
541 type_name[exprs[0]->vtype]);
544 if (!(out = parser->m_fold.op(op, exprs))) {
545 switch (exprs[0]->vtype) {
547 if (exprs[1]->vtype == TYPE_VECTOR)
548 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
550 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
553 if (exprs[1]->vtype == TYPE_FLOAT)
554 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
556 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
559 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
560 type_name[exprs[1]->vtype],
561 type_name[exprs[0]->vtype]);
568 if (exprs[1]->vtype != TYPE_FLOAT) {
569 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
570 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
571 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
574 if (!(out = parser->m_fold.op(op, exprs))) {
575 if (exprs[0]->vtype == TYPE_FLOAT)
576 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
578 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
579 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
580 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
587 if (NotSameType(TYPE_FLOAT)) {
588 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
589 type_name[exprs[0]->vtype],
590 type_name[exprs[1]->vtype]);
592 } else if (!(out = parser->m_fold.op(op, exprs))) {
593 /* generate a call to __builtin_mod */
594 ast_expression *mod = parser->m_intrin.func("mod");
595 ast_call *call = nullptr;
596 if (!mod) return false; /* can return null for missing floor */
598 call = ast_call_new(parser_ctx(parser), mod);
599 call->params.push_back(exprs[0]);
600 call->params.push_back(exprs[1]);
602 out = (ast_expression*)call;
607 compile_error(ctx, "%= is unimplemented");
613 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
614 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
615 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
617 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
618 type_name[exprs[0]->vtype],
619 type_name[exprs[1]->vtype]);
623 if (!(out = parser->m_fold.op(op, exprs))) {
625 * IF the first expression is float, the following will be too
626 * since scalar ^ vector is not allowed.
628 if (exprs[0]->vtype == TYPE_FLOAT) {
629 out = fold::binary(ctx,
630 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
634 * The first is a vector: vector is allowed to bitop with vector and
635 * with scalar, branch here for the second operand.
637 if (exprs[1]->vtype == TYPE_VECTOR) {
639 * Bitop all the values of the vector components against the
640 * vectors components in question.
642 out = fold::binary(ctx,
643 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
646 out = fold::binary(ctx,
647 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
656 if (NotSameType(TYPE_FLOAT)) {
657 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
658 type_name[exprs[0]->vtype],
659 type_name[exprs[1]->vtype]);
663 if (!(out = parser->m_fold.op(op, exprs))) {
664 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
665 ast_call *call = ast_call_new(parser_ctx(parser), shift);
666 call->params.push_back(exprs[0]);
667 call->params.push_back(exprs[1]);
668 out = (ast_expression*)call;
672 case opid3('<','<','='):
673 case opid3('>','>','='):
674 if (NotSameType(TYPE_FLOAT)) {
675 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
676 type_name[exprs[0]->vtype],
677 type_name[exprs[1]->vtype]);
681 if(!(out = parser->m_fold.op(op, exprs))) {
682 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
683 ast_call *call = ast_call_new(parser_ctx(parser), shift);
684 call->params.push_back(exprs[0]);
685 call->params.push_back(exprs[1]);
686 out = (ast_expression*)ast_store_new(
690 (ast_expression*)call
697 generated_op += 1; /* INSTR_OR */
699 generated_op += INSTR_AND;
700 if (!(out = parser->m_fold.op(op, exprs))) {
701 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
702 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
703 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
704 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
707 for (i = 0; i < 2; ++i) {
708 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
709 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
711 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
713 exprs[i] = out; out = nullptr;
714 if (OPTS_FLAG(PERL_LOGIC)) {
715 /* here we want to keep the right expressions' type */
719 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
720 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
724 exprs[i] = out; out = nullptr;
725 if (OPTS_FLAG(PERL_LOGIC)) {
726 /* here we want to keep the right expressions' type */
731 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
736 if (sy->paren.back() != PAREN_TERNARY2) {
737 compile_error(ctx, "mismatched parenthesis/ternary");
740 sy->paren.pop_back();
741 if (!ast_compare_type(exprs[1], exprs[2])) {
742 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
743 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
744 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
747 if (!(out = parser->m_fold.op(op, exprs)))
748 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
751 case opid2('*', '*'):
752 if (NotSameType(TYPE_FLOAT)) {
753 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
754 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
755 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
760 if (!(out = parser->m_fold.op(op, exprs))) {
761 ast_call *gencall = ast_call_new(parser_ctx(parser), parser->m_intrin.func("pow"));
762 gencall->params.push_back(exprs[0]);
763 gencall->params.push_back(exprs[1]);
764 out = (ast_expression*)gencall;
768 case opid2('>', '<'):
769 if (NotSameType(TYPE_VECTOR)) {
770 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
771 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
772 compile_error(ctx, "invalid types used in cross product: %s and %s",
777 if (!(out = parser->m_fold.op(op, exprs))) {
788 case opid3('<','=','>'): /* -1, 0, or 1 */
789 if (NotSameType(TYPE_FLOAT)) {
790 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
791 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
792 compile_error(ctx, "invalid types used in comparision: %s and %s",
798 if (!(out = parser->m_fold.op(op, exprs))) {
799 /* This whole block is NOT fold_binary safe */
800 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
802 eq->refs = AST_REF_NONE;
805 out = (ast_expression*)ast_ternary_new(ctx,
806 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
808 (ast_expression*)parser->m_fold.imm_float(2),
811 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
813 (ast_expression*)parser->m_fold.imm_float(0),
816 (ast_expression*)parser->m_fold.imm_float(1)
826 generated_op += 1; /* INSTR_GT */
828 generated_op += 1; /* INSTR_LT */
829 case opid2('>', '='):
830 generated_op += 1; /* INSTR_GE */
831 case opid2('<', '='):
832 generated_op += INSTR_LE;
833 if (NotSameType(TYPE_FLOAT)) {
834 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
835 type_name[exprs[0]->vtype],
836 type_name[exprs[1]->vtype]);
839 if (!(out = parser->m_fold.op(op, exprs)))
840 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
842 case opid2('!', '='):
843 if (exprs[0]->vtype != exprs[1]->vtype) {
844 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
845 type_name[exprs[0]->vtype],
846 type_name[exprs[1]->vtype]);
849 if (!(out = parser->m_fold.op(op, exprs)))
850 out = fold::binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
852 case opid2('=', '='):
853 if (exprs[0]->vtype != exprs[1]->vtype) {
854 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
855 type_name[exprs[0]->vtype],
856 type_name[exprs[1]->vtype]);
859 if (!(out = parser->m_fold.op(op, exprs)))
860 out = fold::binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
864 if (ast_istype(exprs[0], ast_entfield)) {
865 ast_expression *field = ((ast_entfield*)exprs[0])->field;
866 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
867 exprs[0]->vtype == TYPE_FIELD &&
868 exprs[0]->next->vtype == TYPE_VECTOR)
870 assignop = type_storep_instr[TYPE_VECTOR];
873 assignop = type_storep_instr[exprs[0]->vtype];
874 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
876 ast_type_to_string(field->next, ty1, sizeof(ty1));
877 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
878 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
879 field->next->vtype == TYPE_FUNCTION &&
880 exprs[1]->vtype == TYPE_FUNCTION)
882 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
883 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
886 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
891 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
892 exprs[0]->vtype == TYPE_FIELD &&
893 exprs[0]->next->vtype == TYPE_VECTOR)
895 assignop = type_store_instr[TYPE_VECTOR];
898 assignop = type_store_instr[exprs[0]->vtype];
901 if (assignop == VINSTR_END) {
902 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
903 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
904 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
906 else if (!ast_compare_type(exprs[0], exprs[1]))
908 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
909 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
910 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
911 exprs[0]->vtype == TYPE_FUNCTION &&
912 exprs[1]->vtype == TYPE_FUNCTION)
914 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
915 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
918 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
921 (void)check_write_to(ctx, exprs[0]);
922 /* When we're a vector of part of an entity field we use STOREP */
923 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->owner, ast_entfield))
924 assignop = INSTR_STOREP_F;
925 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
927 case opid3('+','+','P'):
928 case opid3('-','-','P'):
930 if (exprs[0]->vtype != TYPE_FLOAT) {
931 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
932 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
935 if (op->id == opid3('+','+','P'))
939 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
940 if (ast_istype(exprs[0], ast_entfield)) {
941 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
943 (ast_expression*)parser->m_fold.imm_float(1));
945 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
947 (ast_expression*)parser->m_fold.imm_float(1));
950 case opid3('S','+','+'):
951 case opid3('S','-','-'):
953 if (exprs[0]->vtype != TYPE_FLOAT) {
954 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
955 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
958 if (op->id == opid3('S','+','+')) {
965 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
966 if (ast_istype(exprs[0], ast_entfield)) {
967 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
969 (ast_expression*)parser->m_fold.imm_float(1));
971 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
973 (ast_expression*)parser->m_fold.imm_float(1));
977 out = fold::binary(ctx, subop,
979 (ast_expression*)parser->m_fold.imm_float(1));
984 if (exprs[0]->vtype != exprs[1]->vtype ||
985 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
987 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
988 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
989 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
993 (void)check_write_to(ctx, exprs[0]);
994 if (ast_istype(exprs[0], ast_entfield))
995 assignop = type_storep_instr[exprs[0]->vtype];
997 assignop = type_store_instr[exprs[0]->vtype];
998 switch (exprs[0]->vtype) {
1000 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1001 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1002 exprs[0], exprs[1]);
1005 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1006 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1007 exprs[0], exprs[1]);
1010 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1011 type_name[exprs[0]->vtype],
1012 type_name[exprs[1]->vtype]);
1016 case opid2('*','='):
1017 case opid2('/','='):
1018 if (exprs[1]->vtype != TYPE_FLOAT ||
1019 !(exprs[0]->vtype == TYPE_FLOAT ||
1020 exprs[0]->vtype == TYPE_VECTOR))
1022 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1023 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1024 compile_error(ctx, "invalid types used in expression: %s and %s",
1028 (void)check_write_to(ctx, exprs[0]);
1029 if (ast_istype(exprs[0], ast_entfield))
1030 assignop = type_storep_instr[exprs[0]->vtype];
1032 assignop = type_store_instr[exprs[0]->vtype];
1033 switch (exprs[0]->vtype) {
1035 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1036 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1037 exprs[0], exprs[1]);
1040 if (op->id == opid2('*','=')) {
1041 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1042 exprs[0], exprs[1]);
1044 out = fold::binary(ctx, INSTR_DIV_F,
1045 (ast_expression*)parser->m_fold.imm_float(1),
1048 compile_error(ctx, "internal error: failed to generate division");
1051 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1056 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1057 type_name[exprs[0]->vtype],
1058 type_name[exprs[1]->vtype]);
1062 case opid2('&','='):
1063 case opid2('|','='):
1064 case opid2('^','='):
1065 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1066 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1067 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1068 compile_error(ctx, "invalid types used in expression: %s and %s",
1072 (void)check_write_to(ctx, exprs[0]);
1073 if (ast_istype(exprs[0], ast_entfield))
1074 assignop = type_storep_instr[exprs[0]->vtype];
1076 assignop = type_store_instr[exprs[0]->vtype];
1077 if (exprs[0]->vtype == TYPE_FLOAT)
1078 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1079 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1080 exprs[0], exprs[1]);
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1083 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1084 exprs[0], exprs[1]);
1086 case opid3('&','~','='):
1087 /* This is like: a &= ~(b);
1088 * But QC has no bitwise-not, so we implement it as
1091 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1092 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1094 compile_error(ctx, "invalid types used in expression: %s and %s",
1098 if (ast_istype(exprs[0], ast_entfield))
1099 assignop = type_storep_instr[exprs[0]->vtype];
1101 assignop = type_store_instr[exprs[0]->vtype];
1102 if (exprs[0]->vtype == TYPE_FLOAT)
1103 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1105 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1108 (void)check_write_to(ctx, exprs[0]);
1109 if (exprs[0]->vtype == TYPE_FLOAT)
1110 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1112 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1113 asbinstore->keep_dest = true;
1114 out = (ast_expression*)asbinstore;
1117 case opid3('l', 'e', 'n'):
1118 if (exprs[0]->vtype != TYPE_STRING && exprs[0]->vtype != TYPE_ARRAY) {
1119 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1120 compile_error(ast_ctx(exprs[0]), "invalid type for length operator: %s", ty1);
1123 /* strings must be const, arrays are statically sized */
1124 if (exprs[0]->vtype == TYPE_STRING &&
1125 !(((ast_value*)exprs[0])->hasvalue && ((ast_value*)exprs[0])->cvq == CV_CONST))
1127 compile_error(ast_ctx(exprs[0]), "operand of length operator not a valid constant expression");
1130 out = parser->m_fold.op(op, exprs);
1133 case opid2('~', 'P'):
1134 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1139 if (!(out = parser->m_fold.op(op, exprs))) {
1140 if (exprs[0]->vtype == TYPE_FLOAT) {
1141 out = fold::binary(ctx, INSTR_SUB_F, (ast_expression*)parser->m_fold.imm_float(2), exprs[0]);
1143 out = fold::binary(ctx, INSTR_SUB_V, (ast_expression*)parser->m_fold.imm_vector(1), exprs[0]);
1150 compile_error(ctx, "failed to apply operator %s", op->op);
1154 sy->out.push_back(syexp(ctx, out));
1158 static bool parser_close_call(parser_t *parser, shunt *sy)
1160 /* was a function call */
1161 ast_expression *fun;
1162 ast_value *funval = nullptr;
1166 size_t paramcount, i;
1169 fid = sy->ops.back().off;
1172 /* out[fid] is the function
1173 * everything above is parameters...
1175 if (sy->argc.empty()) {
1176 parseerror(parser, "internal error: no argument counter available");
1180 paramcount = sy->argc.back();
1181 sy->argc.pop_back();
1183 if (sy->out.size() < fid) {
1184 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1192 * TODO handle this at the intrinsic level with an ast_intrinsic
1195 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1197 if (fid+2 != sy->out.size() || sy->out.back().block) {
1198 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1201 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1202 ast_unref(sy->out.back().out);
1203 sy->out[fid] = syexp(ast_ctx(sy->out.back().out),
1204 (ast_expression*)parser->m_fold.constgen_string(ty, false));
1210 * Now we need to determine if the function that is being called is
1211 * an intrinsic so we can evaluate if the arguments to it are constant
1212 * and than fruitfully fold them.
1214 #define fold_can_1(X) \
1215 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1216 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1218 if (fid + 1 < sy->out.size())
1221 for (i = 0; i < paramcount; ++i) {
1222 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1229 * All is well which ends well, if we make it into here we can ignore the
1230 * intrinsic call and just evaluate it i.e constant fold it.
1232 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1233 ast_expression **exprs = nullptr;
1234 ast_expression *foldval = nullptr;
1236 for (i = 0; i < paramcount; i++)
1237 vec_push(exprs, sy->out[fid+1 + i].out);
1239 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs))) {
1245 * Blub: what sorts of unreffing and resizing of
1246 * sy->out should I be doing here?
1248 sy->out[fid] = syexp(foldval->context, foldval);
1249 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1256 call = ast_call_new(sy->ops[sy->ops.size()].ctx, fun);
1261 if (fid+1 + paramcount != sy->out.size()) {
1262 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1269 for (i = 0; i < paramcount; ++i)
1270 call->params.push_back(sy->out[fid+1 + i].out);
1271 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1272 (void)!ast_call_check_types(call, parser->function->function_type->expression.varparam);
1273 if (parser->max_param_count < paramcount)
1274 parser->max_param_count = paramcount;
1276 if (ast_istype(fun, ast_value)) {
1277 funval = (ast_value*)fun;
1278 if ((fun->flags & AST_FLAG_VARIADIC) &&
1279 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1281 call->va_count = (ast_expression*)parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1285 /* overwrite fid, the function, with a call */
1286 sy->out[fid] = syexp(call->expression.context, (ast_expression*)call);
1288 if (fun->vtype != TYPE_FUNCTION) {
1289 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1294 parseerror(parser, "could not determine function return type");
1297 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1299 if (fun->flags & AST_FLAG_DEPRECATED) {
1301 return !parsewarning(parser, WARN_DEPRECATED,
1302 "call to function (which is marked deprecated)\n",
1303 "-> it has been declared here: %s:%i",
1304 ast_ctx(fun).file, ast_ctx(fun).line);
1307 return !parsewarning(parser, WARN_DEPRECATED,
1308 "call to `%s` (which is marked deprecated)\n"
1309 "-> `%s` declared here: %s:%i",
1310 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1312 return !parsewarning(parser, WARN_DEPRECATED,
1313 "call to `%s` (deprecated: %s)\n"
1314 "-> `%s` declared here: %s:%i",
1315 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1319 if (fun->type_params.size() != paramcount &&
1320 !((fun->flags & AST_FLAG_VARIADIC) &&
1321 fun->type_params.size() < paramcount))
1323 const char *fewmany = (fun->type_params.size() > paramcount) ? "few" : "many";
1325 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1326 "too %s parameters for call to %s: expected %i, got %i\n"
1327 " -> `%s` has been declared here: %s:%i",
1328 fewmany, fval->name, (int)fun->type_params.size(), (int)paramcount,
1329 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1331 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1332 "too %s parameters for function call: expected %i, got %i\n"
1333 " -> it has been declared here: %s:%i",
1334 fewmany, (int)fun->type_params.size(), (int)paramcount,
1335 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1342 static bool parser_close_paren(parser_t *parser, shunt *sy)
1344 if (sy->ops.empty()) {
1345 parseerror(parser, "unmatched closing paren");
1349 while (sy->ops.size()) {
1350 if (sy->ops.back().isparen) {
1351 if (sy->paren.back() == PAREN_FUNC) {
1352 sy->paren.pop_back();
1353 if (!parser_close_call(parser, sy))
1357 if (sy->paren.back() == PAREN_EXPR) {
1358 sy->paren.pop_back();
1359 if (sy->out.empty()) {
1360 compile_error(sy->ops.back().ctx, "empty paren expression");
1367 if (sy->paren.back() == PAREN_INDEX) {
1368 sy->paren.pop_back();
1369 // pop off the parenthesis
1371 /* then apply the index operator */
1372 if (!parser_sy_apply_operator(parser, sy))
1376 if (sy->paren.back() == PAREN_TERNARY1) {
1377 sy->paren.back() = PAREN_TERNARY2;
1378 // pop off the parenthesis
1382 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1385 if (!parser_sy_apply_operator(parser, sy))
1391 static void parser_reclassify_token(parser_t *parser)
1394 if (parser->tok >= TOKEN_START)
1396 for (i = 0; i < operator_count; ++i) {
1397 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1398 parser->tok = TOKEN_OPERATOR;
1404 static ast_expression* parse_vararg_do(parser_t *parser)
1406 ast_expression *idx, *out;
1408 ast_value *funtype = parser->function->function_type;
1409 lex_ctx_t ctx = parser_ctx(parser);
1411 if (!parser->function->varargs) {
1412 parseerror(parser, "function has no variable argument list");
1416 if (!parser_next(parser) || parser->tok != '(') {
1417 parseerror(parser, "expected parameter index and type in parenthesis");
1420 if (!parser_next(parser)) {
1421 parseerror(parser, "error parsing parameter index");
1425 idx = parse_expression_leave(parser, true, false, false);
1429 if (parser->tok != ',') {
1430 if (parser->tok != ')') {
1432 parseerror(parser, "expected comma after parameter index");
1435 /* vararg piping: ...(start) */
1436 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1440 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1442 parseerror(parser, "expected typename for vararg");
1446 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1452 if (parser->tok != ')') {
1454 ast_delete(typevar);
1455 parseerror(parser, "expected closing paren");
1459 if (funtype->expression.varparam &&
1460 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1464 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1465 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1466 compile_error(ast_ctx(typevar),
1467 "function was declared to take varargs of type `%s`, requested type is: %s",
1471 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1472 ast_type_adopt(out, typevar);
1473 ast_delete(typevar);
1477 static ast_expression* parse_vararg(parser_t *parser)
1479 bool old_noops = parser->lex->flags.noops;
1481 ast_expression *out;
1483 parser->lex->flags.noops = true;
1484 out = parse_vararg_do(parser);
1486 parser->lex->flags.noops = old_noops;
1490 /* not to be exposed */
1491 bool ftepp_predef_exists(const char *name);
1492 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1494 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1495 parser->tok == TOKEN_IDENT &&
1496 !strcmp(parser_tokval(parser), "_"))
1498 /* a translatable string */
1501 parser->lex->flags.noops = true;
1502 if (!parser_next(parser) || parser->tok != '(') {
1503 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1506 parser->lex->flags.noops = false;
1507 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1508 parseerror(parser, "expected a constant string in translatable-string extension");
1511 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1514 sy->out.push_back(syexp(parser_ctx(parser), (ast_expression*)val));
1516 if (!parser_next(parser) || parser->tok != ')') {
1517 parseerror(parser, "expected closing paren after translatable string");
1522 else if (parser->tok == TOKEN_DOTS)
1525 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1526 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1529 va = parse_vararg(parser);
1532 sy->out.push_back(syexp(parser_ctx(parser), va));
1535 else if (parser->tok == TOKEN_FLOATCONST) {
1536 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1539 sy->out.push_back(syexp(parser_ctx(parser), val));
1542 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1543 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1546 sy->out.push_back(syexp(parser_ctx(parser), val));
1549 else if (parser->tok == TOKEN_STRINGCONST) {
1550 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1553 sy->out.push_back(syexp(parser_ctx(parser), val));
1556 else if (parser->tok == TOKEN_VECTORCONST) {
1557 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1560 sy->out.push_back(syexp(parser_ctx(parser), val));
1563 else if (parser->tok == TOKEN_IDENT)
1565 const char *ctoken = parser_tokval(parser);
1566 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1567 ast_expression *var;
1568 /* a_vector.{x,y,z} */
1569 if (sy->ops.empty() ||
1570 !sy->ops.back().etype ||
1571 operators[sy->ops.back().etype-1].id != opid1('.'))
1573 /* When adding more intrinsics, fix the above condition */
1576 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1578 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1580 var = parser_find_var(parser, parser_tokval(parser));
1582 var = parser_find_field(parser, parser_tokval(parser));
1584 if (!var && with_labels) {
1585 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1587 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1588 var = (ast_expression*)lbl;
1589 parser->labels.push_back(lbl);
1592 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1593 var = (ast_expression*)parser->m_fold.constgen_string(parser->function->name, false);
1596 * now we try for the real intrinsic hashtable. If the string
1597 * begins with __builtin, we simply skip past it, otherwise we
1598 * use the identifier as is.
1600 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1601 var = parser->m_intrin.func(parser_tokval(parser));
1605 * Try it again, intrin_func deals with the alias method as well
1606 * the first one masks for __builtin though, we emit warning here.
1609 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1610 (void)!compile_warning(
1613 "using implicitly defined builtin `__builtin_%s' for `%s'",
1614 parser_tokval(parser),
1615 parser_tokval(parser)
1623 * sometimes people use preprocessing predefs without enabling them
1624 * i've done this thousands of times already myself. Lets check for
1625 * it in the predef table. And diagnose it better :)
1627 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1628 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1632 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1638 if (ast_istype(var, ast_value)) {
1639 ((ast_value*)var)->uses++;
1641 else if (ast_istype(var, ast_member)) {
1642 ast_member *mem = (ast_member*)var;
1643 if (ast_istype(mem->owner, ast_value))
1644 ((ast_value*)(mem->owner))->uses++;
1647 sy->out.push_back(syexp(parser_ctx(parser), var));
1650 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1654 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1656 ast_expression *expr = nullptr;
1658 bool wantop = false;
1659 /* only warn once about an assignment in a truth value because the current code
1660 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1662 bool warn_parenthesis = true;
1664 /* count the parens because an if starts with one, so the
1665 * end of a condition is an unmatched closing paren
1669 memset(&sy, 0, sizeof(sy));
1671 parser->lex->flags.noops = false;
1673 parser_reclassify_token(parser);
1677 if (parser->tok == TOKEN_TYPENAME) {
1678 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1682 if (parser->tok == TOKEN_OPERATOR)
1684 /* classify the operator */
1685 const oper_info *op;
1686 const oper_info *olast = nullptr;
1688 for (o = 0; o < operator_count; ++o) {
1689 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1690 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1691 !strcmp(parser_tokval(parser), operators[o].op))
1696 if (o == operator_count) {
1697 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1700 /* found an operator */
1703 /* when declaring variables, a comma starts a new variable */
1704 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1705 /* fixup the token */
1710 /* a colon without a pervious question mark cannot be a ternary */
1711 if (!ternaries && op->id == opid2(':','?')) {
1716 if (op->id == opid1(',')) {
1717 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1718 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1722 if (sy.ops.size() && !sy.ops.back().isparen)
1723 olast = &operators[sy.ops.back().etype-1];
1725 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1726 while (olast && op->prec < olast->prec)
1728 if (!parser_sy_apply_operator(parser, &sy))
1730 if (sy.ops.size() && !sy.ops.back().isparen)
1731 olast = &operators[sy.ops.back().etype-1];
1736 #define IsAssignOp(x) (\
1737 (x) == opid1('=') || \
1738 (x) == opid2('+','=') || \
1739 (x) == opid2('-','=') || \
1740 (x) == opid2('*','=') || \
1741 (x) == opid2('/','=') || \
1742 (x) == opid2('%','=') || \
1743 (x) == opid2('&','=') || \
1744 (x) == opid2('|','=') || \
1745 (x) == opid3('&','~','=') \
1747 if (warn_parenthesis) {
1748 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1749 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1750 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1753 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1754 warn_parenthesis = false;
1757 if (olast && olast->id != op->id) {
1758 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1759 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1761 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1762 warn_parenthesis = false;
1764 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1765 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1767 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1768 warn_parenthesis = false;
1774 (op->prec < olast->prec) ||
1775 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1777 if (!parser_sy_apply_operator(parser, &sy))
1779 if (sy.ops.size() && !sy.ops.back().isparen)
1780 olast = &operators[sy.ops.back().etype-1];
1785 if (op->id == opid1('(')) {
1787 size_t sycount = sy.out.size();
1788 /* we expected an operator, this is the function-call operator */
1789 sy.paren.push_back(PAREN_FUNC);
1790 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1791 sy.argc.push_back(0);
1793 sy.paren.push_back(PAREN_EXPR);
1794 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1797 } else if (op->id == opid1('[')) {
1799 parseerror(parser, "unexpected array subscript");
1802 sy.paren.push_back(PAREN_INDEX);
1803 /* push both the operator and the paren, this makes life easier */
1804 sy.ops.push_back(syop(parser_ctx(parser), op));
1805 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1807 } else if (op->id == opid2('?',':')) {
1808 sy.ops.push_back(syop(parser_ctx(parser), op));
1809 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1812 sy.paren.push_back(PAREN_TERNARY1);
1813 } else if (op->id == opid2(':','?')) {
1814 if (sy.paren.empty()) {
1815 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1818 if (sy.paren.back() != PAREN_TERNARY1) {
1819 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1822 if (!parser_close_paren(parser, &sy))
1824 sy.ops.push_back(syop(parser_ctx(parser), op));
1828 sy.ops.push_back(syop(parser_ctx(parser), op));
1829 wantop = !!(op->flags & OP_SUFFIX);
1832 else if (parser->tok == ')') {
1833 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1834 if (!parser_sy_apply_operator(parser, &sy))
1837 if (sy.paren.empty())
1840 if (sy.paren.back() == PAREN_TERNARY1) {
1841 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1844 if (!parser_close_paren(parser, &sy))
1847 /* must be a function call without parameters */
1848 if (sy.paren.back() != PAREN_FUNC) {
1849 parseerror(parser, "closing paren in invalid position");
1852 if (!parser_close_paren(parser, &sy))
1857 else if (parser->tok == '(') {
1858 parseerror(parser, "internal error: '(' should be classified as operator");
1861 else if (parser->tok == '[') {
1862 parseerror(parser, "internal error: '[' should be classified as operator");
1865 else if (parser->tok == ']') {
1866 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1867 if (!parser_sy_apply_operator(parser, &sy))
1870 if (sy.paren.empty())
1872 if (sy.paren.back() != PAREN_INDEX) {
1873 parseerror(parser, "mismatched parentheses, unexpected ']'");
1876 if (!parser_close_paren(parser, &sy))
1881 if (!parse_sya_operand(parser, &sy, with_labels))
1886 /* in this case we might want to allow constant string concatenation */
1887 bool concatenated = false;
1888 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1889 ast_expression *lexpr = sy.out.back().out;
1890 if (ast_istype(lexpr, ast_value)) {
1891 ast_value *last = (ast_value*)lexpr;
1892 if (last->isimm == true && last->cvq == CV_CONST &&
1893 last->hasvalue && last->expression.vtype == TYPE_STRING)
1895 char *newstr = nullptr;
1896 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1897 sy.out.back().out = (ast_expression*)parser->m_fold.constgen_string(newstr, false);
1899 concatenated = true;
1903 if (!concatenated) {
1904 parseerror(parser, "expected operator or end of statement");
1909 if (!parser_next(parser)) {
1912 if (parser->tok == ';' ||
1913 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1914 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1920 while (sy.ops.size()) {
1921 if (!parser_sy_apply_operator(parser, &sy))
1925 parser->lex->flags.noops = true;
1926 if (sy.out.size() != 1) {
1927 parseerror(parser, "expression expected");
1930 expr = sy.out[0].out;
1931 if (sy.paren.size()) {
1932 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1938 parser->lex->flags.noops = true;
1939 for (auto &it : sy.out)
1940 if (it.out) ast_unref(it.out);
1944 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1946 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1949 if (parser->tok != ';') {
1950 parseerror(parser, "semicolon expected after expression");
1954 if (!parser_next(parser)) {
1961 static void parser_enterblock(parser_t *parser)
1963 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1964 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1965 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1966 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1967 vec_push(parser->_block_ctx, parser_ctx(parser));
1970 static bool parser_leaveblock(parser_t *parser)
1973 size_t locals, typedefs;
1975 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1976 parseerror(parser, "internal error: parser_leaveblock with no block");
1980 util_htdel(vec_last(parser->variables));
1982 vec_pop(parser->variables);
1983 if (!vec_size(parser->_blocklocals)) {
1984 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1988 locals = vec_last(parser->_blocklocals);
1989 vec_pop(parser->_blocklocals);
1990 while (vec_size(parser->_locals) != locals) {
1991 ast_expression *e = vec_last(parser->_locals);
1992 ast_value *v = (ast_value*)e;
1993 vec_pop(parser->_locals);
1994 if (ast_istype(e, ast_value) && !v->uses) {
1995 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2000 typedefs = vec_last(parser->_blocktypedefs);
2001 while (vec_size(parser->_typedefs) != typedefs) {
2002 ast_delete(vec_last(parser->_typedefs));
2003 vec_pop(parser->_typedefs);
2005 util_htdel(vec_last(parser->typedefs));
2006 vec_pop(parser->typedefs);
2008 vec_pop(parser->_block_ctx);
2013 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2015 vec_push(parser->_locals, e);
2016 util_htset(vec_last(parser->variables), name, (void*)e);
2019 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2021 parser->globals.push_back(e);
2022 util_htset(parser->htglobals, name, e);
2025 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2029 ast_expression *prev;
2031 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2033 ast_type_to_string(cond, ty, sizeof(ty));
2034 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2037 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2040 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2043 parseerror(parser, "internal error: failed to process condition");
2048 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2050 /* vector types need to be cast to true booleans */
2051 ast_binary *bin = (ast_binary*)cond;
2052 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2054 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2056 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2059 parseerror(parser, "internal error: failed to process condition");
2066 unary = (ast_unary*)cond;
2067 /* ast_istype dereferences cond, should test here for safety */
2068 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2070 cond = unary->operand;
2071 unary->operand = nullptr;
2074 unary = (ast_unary*)cond;
2078 parseerror(parser, "internal error: failed to process condition");
2080 if (ifnot) *_ifnot = !*_ifnot;
2084 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2087 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2090 lex_ctx_t ctx = parser_ctx(parser);
2092 (void)block; /* not touching */
2094 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2095 if (!parser_next(parser)) {
2096 parseerror(parser, "expected condition or 'not'");
2099 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2101 if (!parser_next(parser)) {
2102 parseerror(parser, "expected condition in parenthesis");
2106 if (parser->tok != '(') {
2107 parseerror(parser, "expected 'if' condition in parenthesis");
2110 /* parse into the expression */
2111 if (!parser_next(parser)) {
2112 parseerror(parser, "expected 'if' condition after opening paren");
2115 /* parse the condition */
2116 cond = parse_expression_leave(parser, false, true, false);
2120 if (parser->tok != ')') {
2121 parseerror(parser, "expected closing paren after 'if' condition");
2125 /* parse into the 'then' branch */
2126 if (!parser_next(parser)) {
2127 parseerror(parser, "expected statement for on-true branch of 'if'");
2131 if (!parse_statement_or_block(parser, &ontrue)) {
2136 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2137 /* check for an else */
2138 if (!strcmp(parser_tokval(parser), "else")) {
2139 /* parse into the 'else' branch */
2140 if (!parser_next(parser)) {
2141 parseerror(parser, "expected on-false branch after 'else'");
2146 if (!parse_statement_or_block(parser, &onfalse)) {
2153 cond = process_condition(parser, cond, &ifnot);
2155 if (ontrue) ast_delete(ontrue);
2156 if (onfalse) ast_delete(onfalse);
2161 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2163 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2164 *out = (ast_expression*)ifthen;
2168 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2169 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2172 char *label = nullptr;
2174 /* skip the 'while' and get the body */
2175 if (!parser_next(parser)) {
2176 if (OPTS_FLAG(LOOP_LABELS))
2177 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2179 parseerror(parser, "expected 'while' condition in parenthesis");
2183 if (parser->tok == ':') {
2184 if (!OPTS_FLAG(LOOP_LABELS))
2185 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2186 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2187 parseerror(parser, "expected loop label");
2190 label = util_strdup(parser_tokval(parser));
2191 if (!parser_next(parser)) {
2193 parseerror(parser, "expected 'while' condition in parenthesis");
2198 if (parser->tok != '(') {
2199 parseerror(parser, "expected 'while' condition in parenthesis");
2203 parser->breaks.push_back(label);
2204 parser->continues.push_back(label);
2206 rv = parse_while_go(parser, block, out);
2209 if (parser->breaks.back() != label || parser->continues.back() != label) {
2210 parseerror(parser, "internal error: label stack corrupted");
2216 parser->breaks.pop_back();
2217 parser->continues.pop_back();
2222 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2225 ast_expression *cond, *ontrue;
2229 lex_ctx_t ctx = parser_ctx(parser);
2231 (void)block; /* not touching */
2233 /* parse into the expression */
2234 if (!parser_next(parser)) {
2235 parseerror(parser, "expected 'while' condition after opening paren");
2238 /* parse the condition */
2239 cond = parse_expression_leave(parser, false, true, false);
2243 if (parser->tok != ')') {
2244 parseerror(parser, "expected closing paren after 'while' condition");
2248 /* parse into the 'then' branch */
2249 if (!parser_next(parser)) {
2250 parseerror(parser, "expected while-loop body");
2254 if (!parse_statement_or_block(parser, &ontrue)) {
2259 cond = process_condition(parser, cond, &ifnot);
2264 aloop = ast_loop_new(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2265 *out = (ast_expression*)aloop;
2269 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2270 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2273 char *label = nullptr;
2275 /* skip the 'do' and get the body */
2276 if (!parser_next(parser)) {
2277 if (OPTS_FLAG(LOOP_LABELS))
2278 parseerror(parser, "expected loop label or body");
2280 parseerror(parser, "expected loop body");
2284 if (parser->tok == ':') {
2285 if (!OPTS_FLAG(LOOP_LABELS))
2286 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2287 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2288 parseerror(parser, "expected loop label");
2291 label = util_strdup(parser_tokval(parser));
2292 if (!parser_next(parser)) {
2294 parseerror(parser, "expected loop body");
2299 parser->breaks.push_back(label);
2300 parser->continues.push_back(label);
2302 rv = parse_dowhile_go(parser, block, out);
2305 if (parser->breaks.back() != label || parser->continues.back() != label) {
2306 parseerror(parser, "internal error: label stack corrupted");
2309 * Test for nullptr otherwise ast_delete dereferences null pointer
2317 parser->breaks.pop_back();
2318 parser->continues.pop_back();
2323 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2326 ast_expression *cond, *ontrue;
2330 lex_ctx_t ctx = parser_ctx(parser);
2332 (void)block; /* not touching */
2334 if (!parse_statement_or_block(parser, &ontrue))
2337 /* expect the "while" */
2338 if (parser->tok != TOKEN_KEYWORD ||
2339 strcmp(parser_tokval(parser), "while"))
2341 parseerror(parser, "expected 'while' and condition");
2346 /* skip the 'while' and check for opening paren */
2347 if (!parser_next(parser) || parser->tok != '(') {
2348 parseerror(parser, "expected 'while' condition in parenthesis");
2352 /* parse into the expression */
2353 if (!parser_next(parser)) {
2354 parseerror(parser, "expected 'while' condition after opening paren");
2358 /* parse the condition */
2359 cond = parse_expression_leave(parser, false, true, false);
2363 if (parser->tok != ')') {
2364 parseerror(parser, "expected closing paren after 'while' condition");
2370 if (!parser_next(parser) || parser->tok != ';') {
2371 parseerror(parser, "expected semicolon after condition");
2377 if (!parser_next(parser)) {
2378 parseerror(parser, "parse error");
2384 cond = process_condition(parser, cond, &ifnot);
2389 aloop = ast_loop_new(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2390 *out = (ast_expression*)aloop;
2394 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2395 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2398 char *label = nullptr;
2400 /* skip the 'for' and check for opening paren */
2401 if (!parser_next(parser)) {
2402 if (OPTS_FLAG(LOOP_LABELS))
2403 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2405 parseerror(parser, "expected 'for' expressions in parenthesis");
2409 if (parser->tok == ':') {
2410 if (!OPTS_FLAG(LOOP_LABELS))
2411 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2412 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2413 parseerror(parser, "expected loop label");
2416 label = util_strdup(parser_tokval(parser));
2417 if (!parser_next(parser)) {
2419 parseerror(parser, "expected 'for' expressions in parenthesis");
2424 if (parser->tok != '(') {
2425 parseerror(parser, "expected 'for' expressions in parenthesis");
2429 parser->breaks.push_back(label);
2430 parser->continues.push_back(label);
2432 rv = parse_for_go(parser, block, out);
2435 if (parser->breaks.back() != label || parser->continues.back() != label) {
2436 parseerror(parser, "internal error: label stack corrupted");
2442 parser->breaks.pop_back();
2443 parser->continues.pop_back();
2447 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2450 ast_expression *initexpr, *cond, *increment, *ontrue;
2455 lex_ctx_t ctx = parser_ctx(parser);
2457 parser_enterblock(parser);
2461 increment = nullptr;
2464 /* parse into the expression */
2465 if (!parser_next(parser)) {
2466 parseerror(parser, "expected 'for' initializer after opening paren");
2471 if (parser->tok == TOKEN_IDENT)
2472 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2474 if (typevar || parser->tok == TOKEN_TYPENAME) {
2475 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2478 else if (parser->tok != ';')
2480 initexpr = parse_expression_leave(parser, false, false, false);
2484 /* move on to condition */
2485 if (parser->tok != ';') {
2486 parseerror(parser, "expected semicolon after for-loop initializer");
2490 if (!parser_next(parser)) {
2491 parseerror(parser, "expected for-loop condition");
2496 /* parse the condition */
2497 if (parser->tok != ';') {
2498 cond = parse_expression_leave(parser, false, true, false);
2503 /* move on to incrementor */
2504 if (parser->tok != ';') {
2505 parseerror(parser, "expected semicolon after for-loop initializer");
2508 if (!parser_next(parser)) {
2509 parseerror(parser, "expected for-loop condition");
2513 /* parse the incrementor */
2514 if (parser->tok != ')') {
2515 lex_ctx_t condctx = parser_ctx(parser);
2516 increment = parse_expression_leave(parser, false, false, false);
2519 if (!ast_side_effects(increment)) {
2520 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2526 if (parser->tok != ')') {
2527 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2530 /* parse into the 'then' branch */
2531 if (!parser_next(parser)) {
2532 parseerror(parser, "expected for-loop body");
2535 if (!parse_statement_or_block(parser, &ontrue))
2539 cond = process_condition(parser, cond, &ifnot);
2543 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2544 *out = (ast_expression*)aloop;
2546 if (!parser_leaveblock(parser)) {
2552 if (initexpr) ast_unref(initexpr);
2553 if (cond) ast_unref(cond);
2554 if (increment) ast_unref(increment);
2555 (void)!parser_leaveblock(parser);
2559 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2561 ast_expression *exp = nullptr;
2562 ast_expression *var = nullptr;
2563 ast_return *ret = nullptr;
2564 ast_value *retval = parser->function->return_value;
2565 ast_value *expected = parser->function->function_type;
2567 lex_ctx_t ctx = parser_ctx(parser);
2569 (void)block; /* not touching */
2571 if (!parser_next(parser)) {
2572 parseerror(parser, "expected return expression");
2576 /* return assignments */
2577 if (parser->tok == '=') {
2578 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2579 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2583 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2585 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2586 parseerror(parser, "invalid return type: `%s'", ty1);
2590 if (!parser_next(parser)) {
2591 parseerror(parser, "expected return assignment expression");
2595 if (!(exp = parse_expression_leave(parser, false, false, false)))
2598 /* prepare the return value */
2600 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2601 ast_type_adopt(retval, expected->expression.next);
2602 parser->function->return_value = retval;
2605 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2606 char ty1[1024], ty2[1024];
2607 ast_type_to_string(exp, ty1, sizeof(ty1));
2608 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2609 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2612 /* store to 'return' local variable */
2613 var = (ast_expression*)ast_store_new(
2615 type_store_instr[expected->expression.next->vtype],
2616 (ast_expression*)retval, exp);
2623 if (parser->tok != ';')
2624 parseerror(parser, "missing semicolon after return assignment");
2625 else if (!parser_next(parser))
2626 parseerror(parser, "parse error after return assignment");
2632 if (parser->tok != ';') {
2633 exp = parse_expression(parser, false, false);
2637 if (exp->vtype != TYPE_NIL &&
2638 exp->vtype != ((ast_expression*)expected)->next->vtype)
2640 parseerror(parser, "return with invalid expression");
2643 ret = ast_return_new(ctx, exp);
2649 if (!parser_next(parser))
2650 parseerror(parser, "parse error");
2652 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2654 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2656 ret = ast_return_new(ctx, (ast_expression*)retval);
2658 *out = (ast_expression*)ret;
2662 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2665 unsigned int levels = 0;
2666 lex_ctx_t ctx = parser_ctx(parser);
2667 auto &loops = (is_continue ? parser->continues : parser->breaks);
2669 (void)block; /* not touching */
2670 if (!parser_next(parser)) {
2671 parseerror(parser, "expected semicolon or loop label");
2675 if (loops.empty()) {
2677 parseerror(parser, "`continue` can only be used inside loops");
2679 parseerror(parser, "`break` can only be used inside loops or switches");
2682 if (parser->tok == TOKEN_IDENT) {
2683 if (!OPTS_FLAG(LOOP_LABELS))
2684 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2687 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2690 parseerror(parser, "no such loop to %s: `%s`",
2691 (is_continue ? "continue" : "break out of"),
2692 parser_tokval(parser));
2697 if (!parser_next(parser)) {
2698 parseerror(parser, "expected semicolon");
2703 if (parser->tok != ';') {
2704 parseerror(parser, "expected semicolon");
2708 if (!parser_next(parser))
2709 parseerror(parser, "parse error");
2711 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2715 /* returns true when it was a variable qualifier, false otherwise!
2716 * on error, cvq is set to CV_WRONG
2718 struct attribute_t {
2723 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2725 bool had_const = false;
2726 bool had_var = false;
2727 bool had_noref = false;
2728 bool had_attrib = false;
2729 bool had_static = false;
2732 static attribute_t attributes[] = {
2733 { "noreturn", AST_FLAG_NORETURN },
2734 { "inline", AST_FLAG_INLINE },
2735 { "eraseable", AST_FLAG_ERASEABLE },
2736 { "accumulate", AST_FLAG_ACCUMULATE },
2737 { "last", AST_FLAG_FINAL_DECL }
2744 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2746 /* parse an attribute */
2747 if (!parser_next(parser)) {
2748 parseerror(parser, "expected attribute after `[[`");
2753 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2754 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2755 flags |= attributes[i].flag;
2756 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2757 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2758 attributes[i].name);
2766 if (i != GMQCC_ARRAY_COUNT(attributes))
2770 if (!strcmp(parser_tokval(parser), "noref")) {
2772 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2773 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2778 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2779 flags |= AST_FLAG_ALIAS;
2782 if (!parser_next(parser)) {
2783 parseerror(parser, "parse error in attribute");
2787 if (parser->tok == '(') {
2788 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2789 parseerror(parser, "`alias` attribute missing parameter");
2793 *message = util_strdup(parser_tokval(parser));
2795 if (!parser_next(parser)) {
2796 parseerror(parser, "parse error in attribute");
2800 if (parser->tok != ')') {
2801 parseerror(parser, "`alias` attribute expected `)` after parameter");
2805 if (!parser_next(parser)) {
2806 parseerror(parser, "parse error in attribute");
2811 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2812 parseerror(parser, "`alias` attribute expected `]]`");
2816 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2817 flags |= AST_FLAG_DEPRECATED;
2820 if (!parser_next(parser)) {
2821 parseerror(parser, "parse error in attribute");
2825 if (parser->tok == '(') {
2826 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2827 parseerror(parser, "`deprecated` attribute missing parameter");
2831 *message = util_strdup(parser_tokval(parser));
2833 if (!parser_next(parser)) {
2834 parseerror(parser, "parse error in attribute");
2838 if(parser->tok != ')') {
2839 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2843 if (!parser_next(parser)) {
2844 parseerror(parser, "parse error in attribute");
2849 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2850 parseerror(parser, "`deprecated` attribute expected `]]`");
2853 if (*message) mem_d(*message);
2859 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2860 flags |= AST_FLAG_COVERAGE;
2861 if (!parser_next(parser)) {
2863 parseerror(parser, "parse error in coverage attribute");
2867 if (parser->tok == '(') {
2868 if (!parser_next(parser)) {
2870 parseerror(parser, "invalid parameter for coverage() attribute\n"
2871 "valid are: block");
2875 if (parser->tok != ')') {
2877 if (parser->tok != TOKEN_IDENT)
2878 goto bad_coverage_arg;
2879 if (!strcmp(parser_tokval(parser), "block"))
2880 flags |= AST_FLAG_BLOCK_COVERAGE;
2881 else if (!strcmp(parser_tokval(parser), "none"))
2882 flags &= ~(AST_FLAG_COVERAGE_MASK);
2884 goto bad_coverage_arg;
2885 if (!parser_next(parser))
2886 goto error_in_coverage;
2887 if (parser->tok == ',') {
2888 if (!parser_next(parser))
2889 goto error_in_coverage;
2891 } while (parser->tok != ')');
2893 if (parser->tok != ')' || !parser_next(parser))
2894 goto error_in_coverage;
2896 /* without parameter [[coverage]] equals [[coverage(block)]] */
2897 flags |= AST_FLAG_BLOCK_COVERAGE;
2902 /* Skip tokens until we hit a ]] */
2903 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2904 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2905 if (!parser_next(parser)) {
2906 parseerror(parser, "error inside attribute");
2913 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2915 else if (!strcmp(parser_tokval(parser), "const"))
2917 else if (!strcmp(parser_tokval(parser), "var"))
2919 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2921 else if (!strcmp(parser_tokval(parser), "noref"))
2923 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2930 if (!parser_next(parser))
2940 *is_static = had_static;
2944 parseerror(parser, "parse error after variable qualifier");
2949 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2950 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2953 char *label = nullptr;
2955 /* skip the 'while' and get the body */
2956 if (!parser_next(parser)) {
2957 if (OPTS_FLAG(LOOP_LABELS))
2958 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2960 parseerror(parser, "expected 'switch' operand in parenthesis");
2964 if (parser->tok == ':') {
2965 if (!OPTS_FLAG(LOOP_LABELS))
2966 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2967 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2968 parseerror(parser, "expected loop label");
2971 label = util_strdup(parser_tokval(parser));
2972 if (!parser_next(parser)) {
2974 parseerror(parser, "expected 'switch' operand in parenthesis");
2979 if (parser->tok != '(') {
2980 parseerror(parser, "expected 'switch' operand in parenthesis");
2984 parser->breaks.push_back(label);
2986 rv = parse_switch_go(parser, block, out);
2989 if (parser->breaks.back() != label) {
2990 parseerror(parser, "internal error: label stack corrupted");
2996 parser->breaks.pop_back();
3001 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3003 ast_expression *operand;
3006 ast_switch *switchnode;
3007 ast_switch_case swcase;
3010 bool noref, is_static;
3011 uint32_t qflags = 0;
3013 lex_ctx_t ctx = parser_ctx(parser);
3015 (void)block; /* not touching */
3018 /* parse into the expression */
3019 if (!parser_next(parser)) {
3020 parseerror(parser, "expected switch operand");
3023 /* parse the operand */
3024 operand = parse_expression_leave(parser, false, false, false);
3028 switchnode = ast_switch_new(ctx, operand);
3031 if (parser->tok != ')') {
3032 ast_delete(switchnode);
3033 parseerror(parser, "expected closing paren after 'switch' operand");
3037 /* parse over the opening paren */
3038 if (!parser_next(parser) || parser->tok != '{') {
3039 ast_delete(switchnode);
3040 parseerror(parser, "expected list of cases");
3044 if (!parser_next(parser)) {
3045 ast_delete(switchnode);
3046 parseerror(parser, "expected 'case' or 'default'");
3050 /* new block; allow some variables to be declared here */
3051 parser_enterblock(parser);
3054 if (parser->tok == TOKEN_IDENT)
3055 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3056 if (typevar || parser->tok == TOKEN_TYPENAME) {
3057 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3058 ast_delete(switchnode);
3063 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3065 if (cvq == CV_WRONG) {
3066 ast_delete(switchnode);
3069 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3070 ast_delete(switchnode);
3079 while (parser->tok != '}') {
3080 ast_block *caseblock;
3082 if (!strcmp(parser_tokval(parser), "case")) {
3083 if (!parser_next(parser)) {
3084 ast_delete(switchnode);
3085 parseerror(parser, "expected expression for case");
3088 swcase.value = parse_expression_leave(parser, false, false, false);
3089 if (!swcase.value) {
3090 ast_delete(switchnode);
3091 parseerror(parser, "expected expression for case");
3094 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3095 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3096 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3102 else if (!strcmp(parser_tokval(parser), "default")) {
3103 swcase.value = nullptr;
3104 if (!parser_next(parser)) {
3105 ast_delete(switchnode);
3106 parseerror(parser, "expected colon");
3111 ast_delete(switchnode);
3112 parseerror(parser, "expected 'case' or 'default'");
3116 /* Now the colon and body */
3117 if (parser->tok != ':') {
3118 if (swcase.value) ast_unref(swcase.value);
3119 ast_delete(switchnode);
3120 parseerror(parser, "expected colon");
3124 if (!parser_next(parser)) {
3125 if (swcase.value) ast_unref(swcase.value);
3126 ast_delete(switchnode);
3127 parseerror(parser, "expected statements or case");
3130 caseblock = ast_block_new(parser_ctx(parser));
3132 if (swcase.value) ast_unref(swcase.value);
3133 ast_delete(switchnode);
3136 swcase.code = (ast_expression*)caseblock;
3137 switchnode->cases.push_back(swcase);
3139 ast_expression *expr;
3140 if (parser->tok == '}')
3142 if (parser->tok == TOKEN_KEYWORD) {
3143 if (!strcmp(parser_tokval(parser), "case") ||
3144 !strcmp(parser_tokval(parser), "default"))
3149 if (!parse_statement(parser, caseblock, &expr, true)) {
3150 ast_delete(switchnode);
3155 if (!ast_block_add_expr(caseblock, expr)) {
3156 ast_delete(switchnode);
3162 parser_leaveblock(parser);
3165 if (parser->tok != '}') {
3166 ast_delete(switchnode);
3167 parseerror(parser, "expected closing paren of case list");
3170 if (!parser_next(parser)) {
3171 ast_delete(switchnode);
3172 parseerror(parser, "parse error after switch");
3175 *out = (ast_expression*)switchnode;
3179 /* parse computed goto sides */
3180 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3181 ast_expression *on_true;
3182 ast_expression *on_false;
3183 ast_expression *cond;
3188 if (ast_istype(*side, ast_ternary)) {
3189 ast_ternary *tern = (ast_ternary*)*side;
3190 on_true = parse_goto_computed(parser, &tern->on_true);
3191 on_false = parse_goto_computed(parser, &tern->on_false);
3193 if (!on_true || !on_false) {
3194 parseerror(parser, "expected label or expression in ternary");
3195 if (on_true) ast_unref(on_true);
3196 if (on_false) ast_unref(on_false);
3201 tern->cond = nullptr;
3204 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3205 } else if (ast_istype(*side, ast_label)) {
3206 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3207 ast_goto_set_label(gt, ((ast_label*)*side));
3209 return (ast_expression*)gt;
3214 static bool parse_goto(parser_t *parser, ast_expression **out)
3216 ast_goto *gt = nullptr;
3217 ast_expression *lbl;
3219 if (!parser_next(parser))
3222 if (parser->tok != TOKEN_IDENT) {
3223 ast_expression *expression;
3225 /* could be an expression i.e computed goto :-) */
3226 if (parser->tok != '(') {
3227 parseerror(parser, "expected label name after `goto`");
3231 /* failed to parse expression for goto */
3232 if (!(expression = parse_expression(parser, false, true)) ||
3233 !(*out = parse_goto_computed(parser, &expression))) {
3234 parseerror(parser, "invalid goto expression");
3236 ast_unref(expression);
3243 /* not computed goto */
3244 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3245 lbl = parser_find_label(parser, gt->name);
3247 if (!ast_istype(lbl, ast_label)) {
3248 parseerror(parser, "internal error: label is not an ast_label");
3252 ast_goto_set_label(gt, (ast_label*)lbl);
3255 parser->gotos.push_back(gt);
3257 if (!parser_next(parser) || parser->tok != ';') {
3258 parseerror(parser, "semicolon expected after goto label");
3261 if (!parser_next(parser)) {
3262 parseerror(parser, "parse error after goto");
3266 *out = (ast_expression*)gt;
3270 static bool parse_skipwhite(parser_t *parser)
3273 if (!parser_next(parser))
3275 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3276 return parser->tok < TOKEN_ERROR;
3279 static bool parse_eol(parser_t *parser)
3281 if (!parse_skipwhite(parser))
3283 return parser->tok == TOKEN_EOL;
3286 static bool parse_pragma_do(parser_t *parser)
3288 if (!parser_next(parser) ||
3289 parser->tok != TOKEN_IDENT ||
3290 strcmp(parser_tokval(parser), "pragma"))
3292 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3295 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3296 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3300 if (!strcmp(parser_tokval(parser), "noref")) {
3301 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3302 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3305 parser->noref = !!parser_token(parser)->constval.i;
3306 if (!parse_eol(parser)) {
3307 parseerror(parser, "parse error after `noref` pragma");
3313 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3316 while (!parse_eol(parser)) {
3317 parser_next(parser);
3326 static bool parse_pragma(parser_t *parser)
3329 parser->lex->flags.preprocessing = true;
3330 parser->lex->flags.mergelines = true;
3331 rv = parse_pragma_do(parser);
3332 if (parser->tok != TOKEN_EOL) {
3333 parseerror(parser, "junk after pragma");
3336 parser->lex->flags.preprocessing = false;
3337 parser->lex->flags.mergelines = false;
3338 if (!parser_next(parser)) {
3339 parseerror(parser, "parse error after pragma");
3345 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3347 bool noref, is_static;
3349 uint32_t qflags = 0;
3350 ast_value *typevar = nullptr;
3351 char *vstring = nullptr;
3355 if (parser->tok == TOKEN_IDENT)
3356 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3358 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3360 /* local variable */
3362 parseerror(parser, "cannot declare a variable from here");
3365 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3366 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3369 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3373 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3375 if (cvq == CV_WRONG)
3377 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3379 else if (parser->tok == TOKEN_KEYWORD)
3381 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3386 if (!parser_next(parser)) {
3387 parseerror(parser, "parse error after __builtin_debug_printtype");
3391 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3393 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3394 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3395 if (!parser_next(parser)) {
3396 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3402 if (!parse_statement(parser, block, out, allow_cases))
3405 con_out("__builtin_debug_printtype: got no output node\n");
3408 ast_type_to_string(*out, ty, sizeof(ty));
3409 con_out("__builtin_debug_printtype: `%s`\n", ty);
3414 else if (!strcmp(parser_tokval(parser), "return"))
3416 return parse_return(parser, block, out);
3418 else if (!strcmp(parser_tokval(parser), "if"))
3420 return parse_if(parser, block, out);
3422 else if (!strcmp(parser_tokval(parser), "while"))
3424 return parse_while(parser, block, out);
3426 else if (!strcmp(parser_tokval(parser), "do"))
3428 return parse_dowhile(parser, block, out);
3430 else if (!strcmp(parser_tokval(parser), "for"))
3432 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3433 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3436 return parse_for(parser, block, out);
3438 else if (!strcmp(parser_tokval(parser), "break"))
3440 return parse_break_continue(parser, block, out, false);
3442 else if (!strcmp(parser_tokval(parser), "continue"))
3444 return parse_break_continue(parser, block, out, true);
3446 else if (!strcmp(parser_tokval(parser), "switch"))
3448 return parse_switch(parser, block, out);
3450 else if (!strcmp(parser_tokval(parser), "case") ||
3451 !strcmp(parser_tokval(parser), "default"))
3454 parseerror(parser, "unexpected 'case' label");
3459 else if (!strcmp(parser_tokval(parser), "goto"))
3461 return parse_goto(parser, out);
3463 else if (!strcmp(parser_tokval(parser), "typedef"))
3465 if (!parser_next(parser)) {
3466 parseerror(parser, "expected type definition after 'typedef'");
3469 return parse_typedef(parser);
3471 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3474 else if (parser->tok == '{')
3477 inner = parse_block(parser);
3480 *out = (ast_expression*)inner;
3483 else if (parser->tok == ':')
3487 if (!parser_next(parser)) {
3488 parseerror(parser, "expected label name");
3491 if (parser->tok != TOKEN_IDENT) {
3492 parseerror(parser, "label must be an identifier");
3495 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3497 if (!label->undefined) {
3498 parseerror(parser, "label `%s` already defined", label->name);
3501 label->undefined = false;
3504 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3505 parser->labels.push_back(label);
3507 *out = (ast_expression*)label;
3508 if (!parser_next(parser)) {
3509 parseerror(parser, "parse error after label");
3512 for (i = 0; i < parser->gotos.size(); ++i) {
3513 if (!strcmp(parser->gotos[i]->name, label->name)) {
3514 ast_goto_set_label(parser->gotos[i], label);
3515 parser->gotos.erase(parser->gotos.begin() + i);
3521 else if (parser->tok == ';')
3523 if (!parser_next(parser)) {
3524 parseerror(parser, "parse error after empty statement");
3531 lex_ctx_t ctx = parser_ctx(parser);
3532 ast_expression *exp = parse_expression(parser, false, false);
3536 if (!ast_side_effects(exp)) {
3537 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3544 static bool parse_enum(parser_t *parser)
3547 bool reverse = false;
3549 ast_value **values = nullptr;
3550 ast_value *var = nullptr;
3553 ast_expression *old;
3555 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3556 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3560 /* enumeration attributes (can add more later) */
3561 if (parser->tok == ':') {
3562 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3563 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3568 if (!strcmp(parser_tokval(parser), "flag")) {
3572 else if (!strcmp(parser_tokval(parser), "reverse")) {
3576 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3580 if (!parser_next(parser) || parser->tok != '{') {
3581 parseerror(parser, "expected `{` after enum attribute ");
3587 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3588 if (parser->tok == '}') {
3589 /* allow an empty enum */
3592 parseerror(parser, "expected identifier or `}`");
3596 old = parser_find_field(parser, parser_tokval(parser));
3598 old = parser_find_global(parser, parser_tokval(parser));
3600 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3601 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3605 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3606 vec_push(values, var);
3607 var->cvq = CV_CONST;
3608 var->hasvalue = true;
3610 /* for flagged enumerations increment in POTs of TWO */
3611 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3612 parser_addglobal(parser, var->name, (ast_expression*)var);
3614 if (!parser_next(parser)) {
3615 parseerror(parser, "expected `=`, `}` or comma after identifier");
3619 if (parser->tok == ',')
3621 if (parser->tok == '}')
3623 if (parser->tok != '=') {
3624 parseerror(parser, "expected `=`, `}` or comma after identifier");
3628 if (!parser_next(parser)) {
3629 parseerror(parser, "expected expression after `=`");
3633 /* We got a value! */
3634 old = parse_expression_leave(parser, true, false, false);
3635 asvalue = (ast_value*)old;
3636 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3637 compile_error(ast_ctx(var), "constant value or expression expected");
3640 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3642 if (parser->tok == '}')
3644 if (parser->tok != ',') {
3645 parseerror(parser, "expected `}` or comma after expression");
3650 /* patch them all (for reversed attribute) */
3653 for (i = 0; i < vec_size(values); i++)
3654 values[i]->constval.vfloat = vec_size(values) - i - 1;
3657 if (parser->tok != '}') {
3658 parseerror(parser, "internal error: breaking without `}`");
3662 if (!parser_next(parser) || parser->tok != ';') {
3663 parseerror(parser, "expected semicolon after enumeration");
3667 if (!parser_next(parser)) {
3668 parseerror(parser, "parse error after enumeration");
3680 static bool parse_block_into(parser_t *parser, ast_block *block)
3684 parser_enterblock(parser);
3686 if (!parser_next(parser)) { /* skip the '{' */
3687 parseerror(parser, "expected function body");
3691 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3693 ast_expression *expr = nullptr;
3694 if (parser->tok == '}')
3697 if (!parse_statement(parser, block, &expr, false)) {
3698 /* parseerror(parser, "parse error"); */
3704 if (!ast_block_add_expr(block, expr)) {
3711 if (parser->tok != '}') {
3714 (void)parser_next(parser);
3718 if (!parser_leaveblock(parser))
3720 return retval && !!block;
3723 static ast_block* parse_block(parser_t *parser)
3726 block = ast_block_new(parser_ctx(parser));
3729 if (!parse_block_into(parser, block)) {
3730 ast_block_delete(block);
3736 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3738 if (parser->tok == '{') {
3739 *out = (ast_expression*)parse_block(parser);
3742 return parse_statement(parser, nullptr, out, false);
3745 static bool create_vector_members(ast_value *var, ast_member **me)
3748 size_t len = strlen(var->name);
3750 for (i = 0; i < 3; ++i) {
3751 char *name = (char*)mem_a(len+3);
3752 memcpy(name, var->name, len);
3754 name[len+1] = 'x'+i;
3756 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3765 do { ast_member_delete(me[--i]); } while(i);
3769 static bool parse_function_body(parser_t *parser, ast_value *var)
3771 ast_block *block = nullptr;
3775 ast_expression *framenum = nullptr;
3776 ast_expression *nextthink = nullptr;
3777 /* None of the following have to be deleted */
3778 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3779 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3780 bool has_frame_think;
3784 has_frame_think = false;
3785 old = parser->function;
3787 if (var->expression.flags & AST_FLAG_ALIAS) {
3788 parseerror(parser, "function aliases cannot have bodies");
3792 if (parser->gotos.size() || parser->labels.size()) {
3793 parseerror(parser, "gotos/labels leaking");
3797 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3798 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3799 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3805 if (parser->tok == '[') {
3806 /* got a frame definition: [ framenum, nextthink ]
3807 * this translates to:
3808 * self.frame = framenum;
3809 * self.nextthink = time + 0.1;
3810 * self.think = nextthink;
3812 nextthink = nullptr;
3814 fld_think = parser_find_field(parser, "think");
3815 fld_nextthink = parser_find_field(parser, "nextthink");
3816 fld_frame = parser_find_field(parser, "frame");
3817 if (!fld_think || !fld_nextthink || !fld_frame) {
3818 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3819 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3822 gbl_time = parser_find_global(parser, "time");
3823 gbl_self = parser_find_global(parser, "self");
3824 if (!gbl_time || !gbl_self) {
3825 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3826 parseerror(parser, "please declare the following globals: `time`, `self`");
3830 if (!parser_next(parser))
3833 framenum = parse_expression_leave(parser, true, false, false);
3835 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3838 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3839 ast_unref(framenum);
3840 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3844 if (parser->tok != ',') {
3845 ast_unref(framenum);
3846 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3847 parseerror(parser, "Got a %i\n", parser->tok);
3851 if (!parser_next(parser)) {
3852 ast_unref(framenum);
3856 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3858 /* qc allows the use of not-yet-declared functions here
3859 * - this automatically creates a prototype */
3860 ast_value *thinkfunc;
3861 ast_expression *functype = fld_think->next;
3863 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3864 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3865 ast_unref(framenum);
3866 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3869 ast_type_adopt(thinkfunc, functype);
3871 if (!parser_next(parser)) {
3872 ast_unref(framenum);
3873 ast_delete(thinkfunc);
3877 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3879 nextthink = (ast_expression*)thinkfunc;
3882 nextthink = parse_expression_leave(parser, true, false, false);
3884 ast_unref(framenum);
3885 parseerror(parser, "expected a think-function in [frame,think] notation");
3890 if (!ast_istype(nextthink, ast_value)) {
3891 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3895 if (retval && parser->tok != ']') {
3896 parseerror(parser, "expected closing `]` for [frame,think] notation");
3900 if (retval && !parser_next(parser)) {
3904 if (retval && parser->tok != '{') {
3905 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3910 ast_unref(nextthink);
3911 ast_unref(framenum);
3915 has_frame_think = true;
3918 block = ast_block_new(parser_ctx(parser));
3920 parseerror(parser, "failed to allocate block");
3921 if (has_frame_think) {
3922 ast_unref(nextthink);
3923 ast_unref(framenum);
3928 if (has_frame_think) {
3929 if (!OPTS_FLAG(EMULATE_STATE)) {
3930 ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
3931 if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
3932 parseerror(parser, "failed to generate state op for [frame,think]");
3933 ast_unref(nextthink);
3934 ast_unref(framenum);
3939 /* emulate OP_STATE in code: */
3941 ast_expression *self_frame;
3942 ast_expression *self_nextthink;
3943 ast_expression *self_think;
3944 ast_expression *time_plus_1;
3945 ast_store *store_frame;
3946 ast_store *store_nextthink;
3947 ast_store *store_think;
3949 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3951 ctx = parser_ctx(parser);
3952 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3953 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3954 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3956 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3957 gbl_time, (ast_expression*)parser->m_fold.constgen_float(frame_delta, false));
3959 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3960 if (self_frame) ast_delete(self_frame);
3961 if (self_nextthink) ast_delete(self_nextthink);
3962 if (self_think) ast_delete(self_think);
3963 if (time_plus_1) ast_delete(time_plus_1);
3969 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3970 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3971 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3974 ast_delete(self_frame);
3977 if (!store_nextthink) {
3978 ast_delete(self_nextthink);
3982 ast_delete(self_think);
3986 if (store_frame) ast_delete(store_frame);
3987 if (store_nextthink) ast_delete(store_nextthink);
3988 if (store_think) ast_delete(store_think);
3991 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3992 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3993 !ast_block_add_expr(block, (ast_expression*)store_think))
4000 parseerror(parser, "failed to generate code for [frame,think]");
4001 ast_unref(nextthink);
4002 ast_unref(framenum);
4009 if (var->hasvalue) {
4010 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4011 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4012 ast_block_delete(block);
4015 func = var->constval.vfunc;
4018 parseerror(parser, "internal error: nullptr function: `%s`", var->name);
4019 ast_block_delete(block);
4023 func = ast_function_new(ast_ctx(var), var->name, var);
4026 parseerror(parser, "failed to allocate function for `%s`", var->name);
4027 ast_block_delete(block);
4030 parser->functions.push_back(func);
4033 parser_enterblock(parser);
4035 for (auto &it : var->expression.type_params) {
4039 if (it->expression.vtype != TYPE_VECTOR &&
4040 (it->expression.vtype != TYPE_FIELD ||
4041 it->expression.next->vtype != TYPE_VECTOR))
4046 if (!create_vector_members(it, me)) {
4047 ast_block_delete(block);
4051 for (e = 0; e < 3; ++e) {
4052 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4053 ast_block_collect(block, (ast_expression*)me[e]);
4057 if (var->argcounter && !func->argc) {
4058 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4059 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4063 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4065 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4066 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4067 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), nullptr, TYPE_VECTOR);
4068 varargs->expression.count = 0;
4069 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4070 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4071 ast_delete(varargs);
4072 ast_block_delete(block);
4075 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4076 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4077 ast_delete(varargs);
4078 ast_block_delete(block);
4081 func->varargs = varargs;
4082 func->fixedparams = (ast_value*)parser->m_fold.constgen_float(var->expression.type_params.size(), false);
4085 parser->function = func;
4086 if (!parse_block_into(parser, block)) {
4087 ast_block_delete(block);
4091 func->blocks.push_back(block);
4093 parser->function = old;
4094 if (!parser_leaveblock(parser))
4096 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4097 parseerror(parser, "internal error: local scopes left");
4101 if (parser->tok == ';')
4102 return parser_next(parser);
4103 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4104 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4108 (void)!parser_leaveblock(parser);
4109 parser->functions.pop_back();
4110 ast_function_delete(func);
4111 var->constval.vfunc = nullptr;
4114 parser->function = old;
4118 static ast_expression *array_accessor_split(
4123 ast_expression *left,
4124 ast_expression *right
4130 lex_ctx_t ctx = ast_ctx(array);
4132 if (!left || !right) {
4133 if (left) ast_delete(left);
4134 if (right) ast_delete(right);
4138 cmp = ast_binary_new(ctx, INSTR_LT,
4139 (ast_expression*)index,
4140 (ast_expression*)parser->m_fold.constgen_float(middle, false));
4144 parseerror(parser, "internal error: failed to create comparison for array setter");
4148 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4150 ast_delete(cmp); /* will delete left and right */
4151 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4155 return (ast_expression*)ifthen;
4158 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4160 lex_ctx_t ctx = ast_ctx(array);
4162 if (from+1 == afterend) {
4163 /* set this value */
4166 ast_array_index *subscript;
4168 int assignop = type_store_instr[value->expression.vtype];
4170 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4171 assignop = INSTR_STORE_V;
4173 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4177 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4179 ast_delete(subscript);
4183 block = ast_block_new(ctx);
4189 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4194 ret = ast_return_new(ctx, nullptr);
4200 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4205 return (ast_expression*)block;
4207 ast_expression *left, *right;
4208 size_t diff = afterend - from;
4209 size_t middle = from + diff/2;
4210 left = array_setter_node(parser, array, index, value, from, middle);
4211 right = array_setter_node(parser, array, index, value, middle, afterend);
4212 return array_accessor_split(parser, array, index, middle, left, right);
4216 static ast_expression *array_field_setter_node(
4225 lex_ctx_t ctx = ast_ctx(array);
4227 if (from+1 == afterend) {
4228 /* set this value */
4231 ast_entfield *entfield;
4232 ast_array_index *subscript;
4234 int assignop = type_storep_instr[value->expression.vtype];
4236 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4237 assignop = INSTR_STOREP_V;
4239 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4243 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4244 subscript->expression.vtype = TYPE_FIELD;
4246 entfield = ast_entfield_new_force(ctx,
4247 (ast_expression*)entity,
4248 (ast_expression*)subscript,
4249 (ast_expression*)subscript);
4251 ast_delete(subscript);
4255 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4257 ast_delete(entfield);
4261 block = ast_block_new(ctx);
4267 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4272 ret = ast_return_new(ctx, nullptr);
4278 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4283 return (ast_expression*)block;
4285 ast_expression *left, *right;
4286 size_t diff = afterend - from;
4287 size_t middle = from + diff/2;
4288 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4289 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4290 return array_accessor_split(parser, array, index, middle, left, right);
4294 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4296 lex_ctx_t ctx = ast_ctx(array);
4298 if (from+1 == afterend) {
4300 ast_array_index *subscript;
4302 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4306 ret = ast_return_new(ctx, (ast_expression*)subscript);
4308 ast_delete(subscript);
4312 return (ast_expression*)ret;
4314 ast_expression *left, *right;
4315 size_t diff = afterend - from;
4316 size_t middle = from + diff/2;
4317 left = array_getter_node(parser, array, index, from, middle);
4318 right = array_getter_node(parser, array, index, middle, afterend);
4319 return array_accessor_split(parser, array, index, middle, left, right);
4323 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4325 ast_function *func = nullptr;
4326 ast_value *fval = nullptr;
4327 ast_block *body = nullptr;
4329 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4331 parseerror(parser, "failed to create accessor function value");
4334 fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4336 func = ast_function_new(ast_ctx(array), funcname, fval);
4339 parseerror(parser, "failed to create accessor function node");
4343 body = ast_block_new(ast_ctx(array));
4345 parseerror(parser, "failed to create block for array accessor");
4351 func->blocks.push_back(body);
4354 parser->accessors.push_back(fval);
4359 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4361 ast_value *index = nullptr;
4362 ast_value *value = nullptr;
4366 if (!ast_istype(array->expression.next, ast_value)) {
4367 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4371 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4373 func = fval->constval.vfunc;
4374 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4376 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4377 value = ast_value_copy((ast_value*)array->expression.next);
4379 if (!index || !value) {
4380 parseerror(parser, "failed to create locals for array accessor");
4383 (void)!ast_value_set_name(value, "value"); /* not important */
4384 fval->expression.type_params.push_back(index);
4385 fval->expression.type_params.push_back(value);
4387 array->setter = fval;
4390 if (index) ast_delete(index);
4391 if (value) ast_delete(value);
4397 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4399 ast_expression *root = nullptr;
4400 root = array_setter_node(parser, array,
4401 array->setter->expression.type_params[0],
4402 array->setter->expression.type_params[1],
4403 0, array->expression.count);
4405 parseerror(parser, "failed to build accessor search tree");
4408 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4415 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4417 if (!parser_create_array_setter_proto(parser, array, funcname))
4419 return parser_create_array_setter_impl(parser, array);
4422 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4424 ast_expression *root = nullptr;
4425 ast_value *entity = nullptr;
4426 ast_value *index = nullptr;
4427 ast_value *value = nullptr;
4431 if (!ast_istype(array->expression.next, ast_value)) {
4432 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4436 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4438 func = fval->constval.vfunc;
4439 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4441 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4442 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4443 value = ast_value_copy((ast_value*)array->expression.next);
4444 if (!entity || !index || !value) {
4445 parseerror(parser, "failed to create locals for array accessor");
4448 (void)!ast_value_set_name(value, "value"); /* not important */
4449 fval->expression.type_params.push_back(entity);
4450 fval->expression.type_params.push_back(index);
4451 fval->expression.type_params.push_back(value);
4453 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4455 parseerror(parser, "failed to build accessor search tree");
4459 array->setter = fval;
4460 return ast_block_add_expr(func->blocks[0], root);
4462 if (entity) ast_delete(entity);
4463 if (index) ast_delete(index);
4464 if (value) ast_delete(value);
4465 if (root) ast_delete(root);
4471 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4473 ast_value *index = nullptr;
4477 /* NOTE: checking array->expression.next rather than elemtype since
4478 * for fields elemtype is a temporary fieldtype.
4480 if (!ast_istype(array->expression.next, ast_value)) {
4481 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4485 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4487 func = fval->constval.vfunc;
4488 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4490 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4493 parseerror(parser, "failed to create locals for array accessor");
4496 fval->expression.type_params.push_back(index);
4498 array->getter = fval;
4501 if (index) ast_delete(index);
4507 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4509 ast_expression *root = nullptr;
4511 root = array_getter_node(parser, array, array->getter->expression.type_params[0], 0, array->expression.count);
4513 parseerror(parser, "failed to build accessor search tree");
4516 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4523 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4525 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4527 return parser_create_array_getter_impl(parser, array);
4530 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4532 lex_ctx_t ctx = parser_ctx(parser);
4533 std::vector<ast_value *> params;
4536 bool variadic = false;
4537 ast_value *varparam = nullptr;
4538 char *argcounter = nullptr;
4540 /* for the sake of less code we parse-in in this function */
4541 if (!parser_next(parser)) {
4543 parseerror(parser, "expected parameter list");
4547 /* parse variables until we hit a closing paren */
4548 while (parser->tok != ')') {
4549 bool is_varargs = false;
4552 /* there must be commas between them */
4553 if (parser->tok != ',') {
4554 parseerror(parser, "expected comma or end of parameter list");
4557 if (!parser_next(parser)) {
4558 parseerror(parser, "expected parameter");
4564 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4565 if (!param && !is_varargs)
4568 /* '...' indicates a varargs function */
4570 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4571 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4574 if (parser->tok == TOKEN_IDENT) {
4575 argcounter = util_strdup(parser_tokval(parser));
4576 if (!parser_next(parser) || parser->tok != ')') {
4577 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4582 params.push_back(param);
4583 if (param->expression.vtype >= TYPE_VARIANT) {
4584 char tname[1024]; /* typename is reserved in C++ */
4585 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4586 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4589 /* type-restricted varargs */
4590 if (parser->tok == TOKEN_DOTS) {
4592 varparam = params.back();
4594 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4595 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4598 if (parser->tok == TOKEN_IDENT) {
4599 argcounter = util_strdup(parser_tokval(parser));
4600 ast_value_set_name(param, argcounter);
4601 if (!parser_next(parser) || parser->tok != ')') {
4602 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4607 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->name[0] == '<') {
4608 parseerror(parser, "parameter name omitted");
4614 if (params.size() == 1 && params[0]->expression.vtype == TYPE_VOID)
4618 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4619 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4622 if (!parser_next(parser)) {
4623 parseerror(parser, "parse error after typename");
4627 /* now turn 'var' into a function type */
4628 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4629 fval->expression.next = (ast_expression*)var;
4631 fval->expression.flags |= AST_FLAG_VARIADIC;
4634 var->expression.type_params = params;
4635 var->expression.varparam = (ast_expression*)varparam;
4636 var->argcounter = argcounter;
4644 ast_delete(varparam);
4646 for (auto &it : params)
4651 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4653 ast_expression *cexp;
4654 ast_value *cval, *tmp;
4657 ctx = parser_ctx(parser);
4659 if (!parser_next(parser)) {
4661 parseerror(parser, "expected array-size");
4665 if (parser->tok != ']') {
4666 cexp = parse_expression_leave(parser, true, false, false);
4668 if (!cexp || !ast_istype(cexp, ast_value)) {
4672 parseerror(parser, "expected array-size as constant positive integer");
4675 cval = (ast_value*)cexp;
4682 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4683 tmp->expression.next = (ast_expression*)var;
4687 if (cval->expression.vtype == TYPE_INTEGER)
4688 tmp->expression.count = cval->constval.vint;
4689 else if (cval->expression.vtype == TYPE_FLOAT)
4690 tmp->expression.count = cval->constval.vfloat;
4694 parseerror(parser, "array-size must be a positive integer constant");
4700 var->expression.count = -1;
4701 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4704 if (parser->tok != ']') {
4706 parseerror(parser, "expected ']' after array-size");
4709 if (!parser_next(parser)) {
4711 parseerror(parser, "error after parsing array size");
4717 /* Parse a complete typename.
4718 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4719 * but when parsing variables separated by comma
4720 * 'storebase' should point to where the base-type should be kept.
4721 * The base type makes up every bit of type information which comes *before* the
4724 * NOTE: The value must either be named, have a nullptr name, or a name starting
4725 * with '<'. In the first case, this will be the actual variable or type
4726 * name, in the other cases it is assumed that the name will appear
4727 * later, and an error is generated otherwise.
4729 * The following will be parsed in its entirety:
4731 * The 'basetype' in this case is 'void()'
4732 * and if there's a comma after it, say:
4734 * then the type-information 'void()' can be stored in 'storebase'
4736 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4738 ast_value *var, *tmp;
4741 const char *name = nullptr;
4742 bool isfield = false;
4743 bool wasarray = false;
4744 size_t morefields = 0;
4746 bool vararg = (parser->tok == TOKEN_DOTS);
4748 ctx = parser_ctx(parser);
4750 /* types may start with a dot */
4751 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4753 if (parser->tok == TOKEN_DOTS)
4755 /* if we parsed a dot we need a typename now */
4756 if (!parser_next(parser)) {
4757 parseerror(parser, "expected typename for field definition");
4761 /* Further dots are handled seperately because they won't be part of the
4765 if (parser->tok == '.')
4767 else if (parser->tok == TOKEN_DOTS)
4772 if (!parser_next(parser)) {
4773 parseerror(parser, "expected typename for field definition");
4778 if (parser->tok == TOKEN_IDENT)
4779 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4780 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4781 if (vararg && is_vararg) {
4785 parseerror(parser, "expected typename");
4789 /* generate the basic type value */
4790 if (cached_typedef) {
4791 var = ast_value_copy(cached_typedef);
4792 ast_value_set_name(var, "<type(from_def)>");
4794 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4796 for (; morefields; --morefields) {
4797 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4798 tmp->expression.next = (ast_expression*)var;
4802 /* do not yet turn into a field - remember:
4803 * .void() foo; is a field too
4804 * .void()() foo; is a function
4808 if (!parser_next(parser)) {
4810 parseerror(parser, "parse error after typename");
4814 /* an opening paren now starts the parameter-list of a function
4815 * this is where original-QC has parameter lists.
4816 * We allow a single parameter list here.
4817 * Much like fteqcc we don't allow `float()() x`
4819 if (parser->tok == '(') {
4820 var = parse_parameter_list(parser, var);
4825 /* store the base if requested */
4827 *storebase = ast_value_copy(var);
4829 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4830 tmp->expression.next = (ast_expression*)*storebase;
4835 /* there may be a name now */
4836 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4837 if (!strcmp(parser_tokval(parser), "break"))
4838 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4839 else if (parser->tok == TOKEN_KEYWORD)
4842 name = util_strdup(parser_tokval(parser));
4845 if (!parser_next(parser)) {
4848 parseerror(parser, "error after variable or field declaration");
4854 /* now this may be an array */
4855 if (parser->tok == '[') {
4857 var = parse_arraysize(parser, var);
4859 if (name) mem_d(name);
4864 /* This is the point where we can turn it into a field */
4866 /* turn it into a field if desired */
4867 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4868 tmp->expression.next = (ast_expression*)var;
4872 /* now there may be function parens again */
4873 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4874 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4875 if (parser->tok == '(' && wasarray)
4876 parseerror(parser, "arrays as part of a return type is not supported");
4877 while (parser->tok == '(') {
4878 var = parse_parameter_list(parser, var);
4880 if (name) mem_d(name);
4885 /* finally name it */
4887 if (!ast_value_set_name(var, name)) {
4890 parseerror(parser, "internal error: failed to set name");
4893 /* free the name, ast_value_set_name duplicates */
4900 static bool parse_typedef(parser_t *parser)
4902 ast_value *typevar, *oldtype;
4903 ast_expression *old;
4905 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4910 /* while parsing types, the ast_value's get named '<something>' */
4911 if (!typevar->name || typevar->name[0] == '<') {
4912 parseerror(parser, "missing name in typedef");
4913 ast_delete(typevar);
4917 if ( (old = parser_find_var(parser, typevar->name)) ) {
4918 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4919 " -> `%s` has been declared here: %s:%i",
4920 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4921 ast_delete(typevar);
4925 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4926 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4927 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4928 ast_delete(typevar);
4932 vec_push(parser->_typedefs, typevar);
4933 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4935 if (parser->tok != ';') {
4936 parseerror(parser, "expected semicolon after typedef");
4939 if (!parser_next(parser)) {
4940 parseerror(parser, "parse error after typedef");
4947 static const char *cvq_to_str(int cvq) {
4949 case CV_NONE: return "none";
4950 case CV_VAR: return "`var`";
4951 case CV_CONST: return "`const`";
4952 default: return "<INVALID>";
4956 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4959 if (proto->cvq != var->cvq) {
4960 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4961 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4962 parser->tok == '='))
4964 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4965 "`%s` declared with different qualifiers: %s\n"
4966 " -> previous declaration here: %s:%i uses %s",
4967 var->name, cvq_to_str(var->cvq),
4968 ast_ctx(proto).file, ast_ctx(proto).line,
4969 cvq_to_str(proto->cvq));
4972 av = (var ->expression.flags & AST_FLAG_NORETURN);
4973 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4975 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4976 "`%s` declared with different attributes%s\n"
4977 " -> previous declaration here: %s:%i",
4978 var->name, (av ? ": noreturn" : ""),
4979 ast_ctx(proto).file, ast_ctx(proto).line,
4980 (ao ? ": noreturn" : ""));
4985 static bool create_array_accessors(parser_t *parser, ast_value *var)
4988 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4989 if (!parser_create_array_setter(parser, var, name))
4991 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4992 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4997 static bool parse_array(parser_t *parser, ast_value *array)
5000 if (array->initlist.size()) {
5001 parseerror(parser, "array already initialized elsewhere");
5004 if (!parser_next(parser)) {
5005 parseerror(parser, "parse error in array initializer");
5009 while (parser->tok != '}') {
5010 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5013 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5015 parseerror(parser, "initializing element must be a compile time constant");
5018 array->initlist.push_back(v->constval);
5019 if (v->expression.vtype == TYPE_STRING) {
5020 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5024 if (parser->tok == '}')
5026 if (parser->tok != ',' || !parser_next(parser)) {
5027 parseerror(parser, "expected comma or '}' in element list");
5031 if (!parser_next(parser) || parser->tok != ';') {
5032 parseerror(parser, "expected semicolon after initializer, got %s");
5036 if (!parser_next(parser)) {
5037 parseerror(parser, "parse error after initializer");
5042 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5043 if (array->expression.count != (size_t)-1) {
5044 parseerror(parser, "array `%s' has already been initialized with %u elements",
5045 array->name, (unsigned)array->expression.count);
5047 array->expression.count = array->initlist.size();
5048 if (!create_array_accessors(parser, array))
5054 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)
5058 ast_expression *old;
5062 ast_value *basetype = nullptr;
5064 bool isparam = false;
5065 bool isvector = false;
5066 bool cleanvar = true;
5067 bool wasarray = false;
5069 ast_member *me[3] = { nullptr, nullptr, nullptr };
5070 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5072 if (!localblock && is_static)
5073 parseerror(parser, "`static` qualifier is not supported in global scope");
5075 /* get the first complete variable */
5076 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5079 ast_delete(basetype);
5083 /* while parsing types, the ast_value's get named '<something>' */
5084 if (!var->name || var->name[0] == '<') {
5085 parseerror(parser, "declaration does not declare anything");
5087 ast_delete(basetype);
5095 /* Part 0: finish the type */
5096 if (parser->tok == '(') {
5097 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5098 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5099 var = parse_parameter_list(parser, var);
5105 /* we only allow 1-dimensional arrays */
5106 if (parser->tok == '[') {
5108 var = parse_arraysize(parser, var);
5114 if (parser->tok == '(' && wasarray) {
5115 parseerror(parser, "arrays as part of a return type is not supported");
5116 /* we'll still parse the type completely for now */
5118 /* for functions returning functions */
5119 while (parser->tok == '(') {
5120 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5121 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5122 var = parse_parameter_list(parser, var);
5129 var->cvq = qualifier;
5130 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5131 var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5132 var->expression.flags |= qflags;
5135 * store the vstring back to var for alias and
5136 * deprecation messages.
5138 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5139 var->expression.flags & AST_FLAG_ALIAS)
5140 var->desc = vstring;
5142 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5143 parseerror(parser, "function aliases cannot be forward declared");
5150 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5151 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5152 * is then filled with the previous definition and the parameter-names replaced.
5154 if (!strcmp(var->name, "nil")) {
5155 if (OPTS_FLAG(UNTYPED_NIL)) {
5156 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5157 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5159 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5162 /* Deal with end_sys_ vars */
5164 if (!strcmp(var->name, "end_sys_globals")) {
5166 parser->crc_globals = parser->globals.size();
5169 else if (!strcmp(var->name, "end_sys_fields")) {
5171 parser->crc_fields = parser->fields.size();
5174 if (was_end && var->expression.vtype == TYPE_FIELD) {
5175 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5176 "global '%s' hint should not be a field",
5177 parser_tokval(parser)))
5184 if (!nofields && var->expression.vtype == TYPE_FIELD)
5186 /* deal with field declarations */
5187 old = parser_find_field(parser, var->name);
5189 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5190 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5199 parseerror(parser, "field `%s` already declared here: %s:%i",
5200 var->name, ast_ctx(old).file, ast_ctx(old).line);
5205 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5206 (old = parser_find_global(parser, var->name)))
5208 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5209 parseerror(parser, "field `%s` already declared here: %s:%i",
5210 var->name, ast_ctx(old).file, ast_ctx(old).line);
5217 /* deal with other globals */
5218 old = parser_find_global(parser, var->name);
5219 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5221 /* This is a function which had a prototype */
5222 if (!ast_istype(old, ast_value)) {
5223 parseerror(parser, "internal error: prototype is not an ast_value");
5227 proto = (ast_value*)old;
5228 proto->desc = var->desc;
5229 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5230 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5232 ast_ctx(proto).file, ast_ctx(proto).line);
5236 /* we need the new parameter-names */
5237 for (i = 0; i < proto->expression.type_params.size(); ++i)
5238 ast_value_set_name(proto->expression.type_params[i], var->expression.type_params[i]->name);
5239 if (!parser_check_qualifiers(parser, var, proto)) {
5246 proto->expression.flags |= var->expression.flags;
5254 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5255 "global `%s` already declared here: %s:%i",
5256 var->name, ast_ctx(old).file, ast_ctx(old).line))
5261 if (old->flags & AST_FLAG_FINAL_DECL) {
5262 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5263 var->name, ast_ctx(old).file, ast_ctx(old).line);
5267 proto = (ast_value*)old;
5268 if (!ast_istype(old, ast_value)) {
5269 parseerror(parser, "internal error: not an ast_value");
5274 if (!parser_check_qualifiers(parser, var, proto)) {
5279 proto->expression.flags |= var->expression.flags;
5280 /* copy the context for finals,
5281 * so the error can show where it was actually made 'final'
5283 if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5284 ast_ctx(old) = ast_ctx(var);
5288 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5289 (old = parser_find_field(parser, var->name)))
5291 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5292 parseerror(parser, "global `%s` already declared here: %s:%i",
5293 var->name, ast_ctx(old).file, ast_ctx(old).line);
5300 else /* it's not a global */
5302 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5303 if (old && !isparam) {
5304 parseerror(parser, "local `%s` already declared here: %s:%i",
5305 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5309 /* doing this here as the above is just for a single scope */
5310 old = parser_find_local(parser, var->name, 0, &isparam);
5311 if (old && isparam) {
5312 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5313 "local `%s` is shadowing a parameter", var->name))
5315 parseerror(parser, "local `%s` already declared here: %s:%i",
5316 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5320 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5322 if (ast_istype(old, ast_value))
5323 var = proto = (ast_value*)old;
5332 /* in a noref section we simply bump the usecount */
5333 if (noref || parser->noref)
5337 * Create the global/local, and deal with vector types.
5340 if (var->expression.vtype == TYPE_VECTOR)
5342 else if (var->expression.vtype == TYPE_FIELD &&
5343 var->expression.next->vtype == TYPE_VECTOR)
5347 if (!create_vector_members(var, me)) {
5354 /* deal with global variables, fields, functions */
5355 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5356 var->isfield = true;
5357 parser->fields.push_back((ast_expression*)var);
5358 util_htset(parser->htfields, var->name, var);
5360 for (i = 0; i < 3; ++i) {
5361 parser->fields.push_back((ast_expression*)me[i]);
5362 util_htset(parser->htfields, me[i]->name, me[i]);
5367 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5368 parser_addglobal(parser, var->name, (ast_expression*)var);
5370 for (i = 0; i < 3; ++i) {
5371 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5375 ast_expression *find = parser_find_global(parser, var->desc);
5378 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5382 if (!ast_compare_type((ast_expression*)var, find)) {
5386 ast_type_to_string(find, ty1, sizeof(ty1));
5387 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5389 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5395 util_htset(parser->aliases, var->name, find);
5397 /* generate aliases for vector components */
5401 util_asprintf(&buffer[0], "%s_x", var->desc);
5402 util_asprintf(&buffer[1], "%s_y", var->desc);
5403 util_asprintf(&buffer[2], "%s_z", var->desc);
5405 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5406 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5407 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5417 /* a static adds itself to be generated like any other global
5418 * but is added to the local namespace instead
5420 char *defname = nullptr;
5421 size_t prefix_len, ln;
5424 ln = strlen(parser->function->name);
5425 vec_append(defname, ln, parser->function->name);
5427 vec_append(defname, 2, "::");
5428 /* remember the length up to here */
5429 prefix_len = vec_size(defname);
5431 /* Add it to the local scope */
5432 util_htset(vec_last(parser->variables), var->name, (void*)var);
5434 /* now rename the global */
5435 ln = strlen(var->name);
5436 vec_append(defname, ln, var->name);
5437 /* if a variable of that name already existed, add the
5439 * The counter is incremented either way.
5441 sn_size = parser->function->static_names.size();
5442 for (sn = 0; sn != sn_size; ++sn) {
5443 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5446 if (sn != sn_size) {
5447 char *num = nullptr;
5448 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5449 vec_append(defname, len, num);
5453 parser->function->static_names.push_back(util_strdup(var->name));
5454 parser->function->static_count++;
5455 ast_value_set_name(var, defname);
5457 /* push it to the to-be-generated globals */
5458 parser->globals.push_back((ast_expression*)var);
5460 /* same game for the vector members */
5462 for (i = 0; i < 3; ++i) {
5463 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5465 vec_shrinkto(defname, prefix_len);
5466 ln = strlen(me[i]->name);
5467 vec_append(defname, ln, me[i]->name);
5468 ast_member_set_name(me[i], defname);
5470 parser->globals.push_back((ast_expression*)me[i]);
5475 localblock->locals.push_back(var);
5476 parser_addlocal(parser, var->name, (ast_expression*)var);
5478 for (i = 0; i < 3; ++i) {
5479 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5480 ast_block_collect(localblock, (ast_expression*)me[i]);
5486 memcpy(last_me, me, sizeof(me));
5487 me[0] = me[1] = me[2] = nullptr;
5492 if (var->expression.vtype == TYPE_ARRAY) {
5493 if (var->expression.count != (size_t)-1) {
5494 if (!create_array_accessors(parser, var))
5498 else if (!localblock && !nofields &&
5499 var->expression.vtype == TYPE_FIELD &&
5500 var->expression.next->vtype == TYPE_ARRAY)
5503 ast_expression *telem;
5505 ast_value *array = (ast_value*)var->expression.next;
5507 if (!ast_istype(var->expression.next, ast_value)) {
5508 parseerror(parser, "internal error: field element type must be an ast_value");
5512 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5513 if (!parser_create_array_field_setter(parser, array, name))
5516 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5517 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5518 tfield->expression.next = telem;
5519 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5520 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5528 if (parser->tok == ';') {
5529 ast_delete(basetype);
5530 if (!parser_next(parser)) {
5531 parseerror(parser, "error after variable declaration");
5537 if (parser->tok == ',')
5541 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5544 parseerror(parser, "missing comma or semicolon while parsing variables");
5548 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5549 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5550 "initializing expression turns variable `%s` into a constant in this standard",
5557 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5558 if (parser->tok != '=') {
5559 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5563 if (!parser_next(parser)) {
5564 parseerror(parser, "error parsing initializer");
5568 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5569 parseerror(parser, "expected '=' before function body in this standard");
5572 if (parser->tok == '#') {
5573 ast_function *func = nullptr;
5574 ast_value *number = nullptr;
5580 parseerror(parser, "cannot declare builtins within functions");
5583 if (var->expression.vtype != TYPE_FUNCTION) {
5584 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5587 if (!parser_next(parser)) {
5588 parseerror(parser, "expected builtin number");
5592 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5593 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5595 parseerror(parser, "builtin number expected");
5598 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5601 parseerror(parser, "builtin number must be a compile time constant");
5604 if (number->expression.vtype == TYPE_INTEGER)
5605 builtin_num = number->constval.vint;
5606 else if (number->expression.vtype == TYPE_FLOAT)
5607 builtin_num = number->constval.vfloat;
5610 parseerror(parser, "builtin number must be an integer constant");
5615 fractional = modff(builtin_num, &integral);
5616 if (builtin_num < 0 || fractional != 0) {
5617 parseerror(parser, "builtin number must be an integer greater than zero");
5621 /* we only want the integral part anyways */
5622 builtin_num = integral;
5623 } else if (parser->tok == TOKEN_INTCONST) {
5624 builtin_num = parser_token(parser)->constval.i;
5626 parseerror(parser, "builtin number must be a compile time constant");
5630 if (var->hasvalue) {
5631 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5632 "builtin `%s` has already been defined\n"
5633 " -> previous declaration here: %s:%i",
5634 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5638 func = ast_function_new(ast_ctx(var), var->name, var);
5640 parseerror(parser, "failed to allocate function for `%s`", var->name);
5643 parser->functions.push_back(func);
5645 func->builtin = -builtin_num-1;
5648 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5649 ? (parser->tok != ',' && parser->tok != ';')
5650 : (!parser_next(parser)))
5652 parseerror(parser, "expected comma or semicolon");
5654 ast_function_delete(func);
5655 var->constval.vfunc = nullptr;
5659 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5662 /* Note that fteqcc and most others don't even *have*
5663 * local arrays, so this is not a high priority.
5665 parseerror(parser, "TODO: initializers for local arrays");
5669 var->hasvalue = true;
5670 if (!parse_array(parser, var))
5673 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5676 parseerror(parser, "cannot declare functions within functions");
5681 ast_ctx(proto) = parser_ctx(parser);
5683 if (!parse_function_body(parser, var))
5685 ast_delete(basetype);
5686 for (auto &it : parser->gotos)
5687 parseerror(parser, "undefined label: `%s`", it->name);
5690 ast_expression *cexp;
5692 bool folded_const = false;
5694 cexp = parse_expression_leave(parser, true, false, false);
5697 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5699 /* deal with foldable constants: */
5701 var->cvq == CV_CONST && cval && cval->hasvalue && cval->cvq == CV_CONST && !cval->isfield)
5703 /* remove it from the current locals */
5705 for (i = 0; i < 3; ++i) {
5706 vec_pop(parser->_locals);
5707 localblock->collect.pop_back();
5710 /* do sanity checking, this function really needs refactoring */
5711 if (vec_last(parser->_locals) != (ast_expression*)var)
5712 parseerror(parser, "internal error: unexpected change in local variable handling");
5714 vec_pop(parser->_locals);
5715 if (localblock->locals.back() != var)
5716 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5718 localblock->locals.pop_back();
5719 /* push it to the to-be-generated globals */
5720 parser->globals.push_back((ast_expression*)var);
5722 for (i = 0; i < 3; ++i)
5723 parser->globals.push_back((ast_expression*)last_me[i]);
5724 folded_const = true;
5727 if (folded_const || !localblock || is_static) {
5728 if (cval != parser->nil &&
5729 (!cval || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5732 parseerror(parser, "initializer is non constant");
5737 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5738 qualifier != CV_VAR)
5740 var->cvq = CV_CONST;
5742 if (cval == parser->nil)
5743 var->expression.flags |= AST_FLAG_INITIALIZED;
5746 var->hasvalue = true;
5747 if (cval->expression.vtype == TYPE_STRING)
5748 var->constval.vstring = parser_strdup(cval->constval.vstring);
5749 else if (cval->expression.vtype == TYPE_FIELD)
5750 var->constval.vfield = cval;
5752 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5761 sy.out.push_back(syexp(ast_ctx(var), (ast_expression*)var));
5762 sy.out.push_back(syexp(ast_ctx(cexp), (ast_expression*)cexp));
5763 sy.ops.push_back(syop(ast_ctx(var), parser->assign_op));
5764 if (!parser_sy_apply_operator(parser, &sy))
5767 if (sy.out.size() != 1 && sy.ops.size() != 0)
5768 parseerror(parser, "internal error: leaked operands");
5769 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5774 /* a constant initialized to an inexact value should be marked inexact:
5775 * const float x = <inexact>; should propagate the inexact flag
5777 if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5778 if (cval && cval->hasvalue && cval->cvq == CV_CONST)
5779 var->inexact = cval->inexact;
5784 if (parser->tok == ',') {
5785 if (!parser_next(parser)) {
5786 parseerror(parser, "expected another variable");
5790 if (parser->tok != TOKEN_IDENT) {
5791 parseerror(parser, "expected another variable");
5794 var = ast_value_copy(basetype);
5796 ast_value_set_name(var, parser_tokval(parser));
5797 if (!parser_next(parser)) {
5798 parseerror(parser, "error parsing variable declaration");
5804 if (parser->tok != ';') {
5805 parseerror(parser, "missing semicolon after variables");
5809 if (!parser_next(parser)) {
5810 parseerror(parser, "parse error after variable declaration");
5814 ast_delete(basetype);
5818 if (cleanvar && var)
5820 ast_delete(basetype);
5824 ast_delete(basetype);
5825 if (cleanvar && var)
5827 if (me[0]) ast_member_delete(me[0]);
5828 if (me[1]) ast_member_delete(me[1]);
5829 if (me[2]) ast_member_delete(me[2]);
5833 static bool parser_global_statement(parser_t *parser)
5837 bool is_static = false;
5838 uint32_t qflags = 0;
5839 ast_value *istype = nullptr;
5840 char *vstring = nullptr;
5842 if (parser->tok == TOKEN_IDENT)
5843 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5845 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5847 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5849 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5851 if (cvq == CV_WRONG)
5853 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5855 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5857 return parse_enum(parser);
5859 else if (parser->tok == TOKEN_KEYWORD)
5861 if (!strcmp(parser_tokval(parser), "typedef")) {
5862 if (!parser_next(parser)) {
5863 parseerror(parser, "expected type definition after 'typedef'");
5866 return parse_typedef(parser);
5868 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5871 else if (parser->tok == '#')
5873 return parse_pragma(parser);
5875 else if (parser->tok == '$')
5877 if (!parser_next(parser)) {
5878 parseerror(parser, "parse error");
5884 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5890 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5892 return util_crc16(old, str, strlen(str));
5895 static void progdefs_crc_file(const char *str)
5897 /* write to progdefs.h here */
5901 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5903 old = progdefs_crc_sum(old, str);
5904 progdefs_crc_file(str);
5908 static void generate_checksum(parser_t *parser, ir_builder *ir)
5910 uint16_t crc = 0xFFFF;
5914 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5915 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5917 progdefs_crc_file("\tint\tpad;\n");
5918 progdefs_crc_file("\tint\tofs_return[3];\n");
5919 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5920 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5921 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5922 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5923 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5924 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5925 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5926 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5928 for (i = 0; i < parser->crc_globals; ++i) {
5929 if (!ast_istype(parser->globals[i], ast_value))
5931 value = (ast_value*)(parser->globals[i]);
5932 switch (value->expression.vtype) {
5933 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5934 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5935 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5936 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5938 crc = progdefs_crc_both(crc, "\tint\t");
5941 crc = progdefs_crc_both(crc, value->name);
5942 crc = progdefs_crc_both(crc, ";\n");
5944 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5945 for (i = 0; i < parser->crc_fields; ++i) {
5946 if (!ast_istype(parser->fields[i], ast_value))
5948 value = (ast_value*)(parser->fields[i]);
5949 switch (value->expression.next->vtype) {
5950 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5951 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5952 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5953 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5955 crc = progdefs_crc_both(crc, "\tint\t");
5958 crc = progdefs_crc_both(crc, value->name);
5959 crc = progdefs_crc_both(crc, ";\n");
5961 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5962 ir->code->crc = crc;
5965 parser_t *parser_create()
5968 lex_ctx_t empty_ctx;
5971 parser = (parser_t*)mem_a(sizeof(parser_t));
5975 memset(parser, 0, sizeof(*parser));
5978 new (parser) parser_t();
5980 for (i = 0; i < operator_count; ++i) {
5981 if (operators[i].id == opid1('=')) {
5982 parser->assign_op = operators+i;
5986 if (!parser->assign_op) {
5987 con_err("internal error: initializing parser: failed to find assign operator\n");
5992 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5993 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5994 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5995 vec_push(parser->_blocktypedefs, 0);
5997 parser->aliases = util_htnew(PARSER_HT_SIZE);
5999 empty_ctx.file = "<internal>";
6001 empty_ctx.column = 0;
6002 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6003 parser->nil->cvq = CV_CONST;
6004 if (OPTS_FLAG(UNTYPED_NIL))
6005 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6007 parser->max_param_count = 1;
6009 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6010 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6011 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6013 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6014 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6015 parser->reserved_version->cvq = CV_CONST;
6016 parser->reserved_version->hasvalue = true;
6017 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6018 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6020 parser->reserved_version = nullptr;
6023 parser->m_fold = fold(parser);
6024 parser->m_intrin = intrin(parser);
6028 static bool parser_compile(parser_t *parser)
6030 /* initial lexer/parser state */
6031 parser->lex->flags.noops = true;
6033 if (parser_next(parser))
6035 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6037 if (!parser_global_statement(parser)) {
6038 if (parser->tok == TOKEN_EOF)
6039 parseerror(parser, "unexpected end of file");
6040 else if (compile_errors)
6041 parseerror(parser, "there have been errors, bailing out");
6042 lex_close(parser->lex);
6043 parser->lex = nullptr;
6048 parseerror(parser, "parse error");
6049 lex_close(parser->lex);
6050 parser->lex = nullptr;
6054 lex_close(parser->lex);
6055 parser->lex = nullptr;
6057 return !compile_errors;
6060 bool parser_compile_file(parser_t *parser, const char *filename)
6062 parser->lex = lex_open(filename);
6064 con_err("failed to open file \"%s\"\n", filename);
6067 return parser_compile(parser);
6070 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6072 parser->lex = lex_open_string(str, len, name);
6074 con_err("failed to create lexer for string \"%s\"\n", name);
6077 return parser_compile(parser);
6080 static void parser_remove_ast(parser_t *parser)
6083 if (parser->ast_cleaned)
6085 parser->ast_cleaned = true;
6086 for (auto &it : parser->accessors) {
6087 ast_delete(it->constval.vfunc);
6088 it->constval.vfunc = nullptr;
6091 for (auto &it : parser->functions) ast_delete(it);
6092 for (auto &it : parser->globals) ast_delete(it);
6093 for (auto &it : parser->fields) ast_delete(it);
6095 for (i = 0; i < vec_size(parser->variables); ++i)
6096 util_htdel(parser->variables[i]);
6097 vec_free(parser->variables);
6098 vec_free(parser->_blocklocals);
6099 vec_free(parser->_locals);
6101 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6102 ast_delete(parser->_typedefs[i]);
6103 vec_free(parser->_typedefs);
6104 for (i = 0; i < vec_size(parser->typedefs); ++i)
6105 util_htdel(parser->typedefs[i]);
6106 vec_free(parser->typedefs);
6107 vec_free(parser->_blocktypedefs);
6109 vec_free(parser->_block_ctx);
6111 ast_value_delete(parser->nil);
6113 ast_value_delete(parser->const_vec[0]);
6114 ast_value_delete(parser->const_vec[1]);
6115 ast_value_delete(parser->const_vec[2]);
6117 if (parser->reserved_version)
6118 ast_value_delete(parser->reserved_version);
6120 util_htdel(parser->aliases);
6123 void parser_cleanup(parser_t *parser)
6125 parser_remove_ast(parser);
6129 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6130 ast_expression *expr;
6134 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6138 for (auto &it : parser->functions) {
6139 if (!strcmp(it->name, "coverage")) {
6145 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6146 con_out("coverage support requested but no coverage() builtin declared\n");
6147 ir_builder_delete(ir);
6153 cov = func->function_type;
6154 expr = (ast_expression*)cov;
6156 if (expr->vtype != TYPE_FUNCTION || expr->type_params.size()) {
6158 ast_type_to_string(expr, ty, sizeof(ty));
6159 con_out("invalid type for coverage(): %s\n", ty);
6160 ir_builder_delete(ir);
6164 ir->coverage_func = func->ir_func->value;
6168 bool parser_finish(parser_t *parser, const char *output)
6173 if (compile_errors) {
6174 con_out("*** there were compile errors\n");
6178 ir = ir_builder_new("gmqcc_out");
6180 con_out("failed to allocate builder\n");
6184 for (auto &it : parser->fields) {
6186 if (!ast_istype(it, ast_value))
6188 ast_value *field = (ast_value*)it;
6189 hasvalue = field->hasvalue;
6190 field->hasvalue = false;
6191 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6192 con_out("failed to generate field %s\n", field->name);
6193 ir_builder_delete(ir);
6198 ast_expression *subtype;
6199 field->hasvalue = true;
6200 subtype = field->expression.next;
6201 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6202 if (subtype->vtype == TYPE_FIELD)
6203 ifld->fieldtype = subtype->next->vtype;
6204 else if (subtype->vtype == TYPE_FUNCTION)
6205 ifld->outtype = subtype->next->vtype;
6206 (void)!ir_value_set_field(field->ir_v, ifld);
6209 for (auto &it : parser->globals) {
6211 if (!ast_istype(it, ast_value))
6213 asvalue = (ast_value*)it;
6214 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6215 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6216 "unused global: `%s`", asvalue->name);
6218 if (!ast_global_codegen(asvalue, ir, false)) {
6219 con_out("failed to generate global %s\n", asvalue->name);
6220 ir_builder_delete(ir);
6224 /* Build function vararg accessor ast tree now before generating
6225 * immediates, because the accessors may add new immediates
6227 for (auto &f : parser->functions) {
6229 if (parser->max_param_count > f->function_type->expression.type_params.size()) {
6230 f->varargs->expression.count = parser->max_param_count - f->function_type->expression.type_params.size();
6231 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6232 con_out("failed to generate vararg setter for %s\n", f->name);
6233 ir_builder_delete(ir);
6236 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6237 con_out("failed to generate vararg getter for %s\n", f->name);
6238 ir_builder_delete(ir);
6242 ast_delete(f->varargs);
6243 f->varargs = nullptr;
6247 /* Now we can generate immediates */
6248 if (!parser->m_fold.generate(ir))
6251 /* before generating any functions we need to set the coverage_func */
6252 if (!parser_set_coverage_func(parser, ir))
6254 for (auto &it : parser->globals) {
6255 if (!ast_istype(it, ast_value))
6257 ast_value *asvalue = (ast_value*)it;
6258 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6260 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6261 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6262 "uninitialized constant: `%s`",
6264 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6265 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6266 "uninitialized global: `%s`",
6269 if (!ast_generate_accessors(asvalue, ir)) {
6270 ir_builder_delete(ir);
6274 for (auto &it : parser->fields) {
6275 ast_value *asvalue = (ast_value*)it->next;
6276 if (!ast_istype((ast_expression*)asvalue, ast_value))
6278 if (asvalue->expression.vtype != TYPE_ARRAY)
6280 if (!ast_generate_accessors(asvalue, ir)) {
6281 ir_builder_delete(ir);
6285 if (parser->reserved_version &&
6286 !ast_global_codegen(parser->reserved_version, ir, false))
6288 con_out("failed to generate reserved::version");
6289 ir_builder_delete(ir);
6292 for (auto &f : parser->functions) {
6293 if (!ast_function_codegen(f, ir)) {
6294 con_out("failed to generate function %s\n", f->name);
6295 ir_builder_delete(ir);
6300 generate_checksum(parser, ir);
6302 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6303 ir_builder_dump(ir, con_out);
6304 for (auto &it : parser->functions) {
6305 if (!ir_function_finalize(it->ir_func)) {
6306 con_out("failed to finalize function %s\n", it->name);
6307 ir_builder_delete(ir);
6311 parser_remove_ast(parser);
6313 if (compile_Werrors) {
6314 con_out("*** there were warnings treated as errors\n");
6315 compile_show_werrors();
6320 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6321 ir_builder_dump(ir, con_out);
6323 if (!ir_builder_generate(ir, output)) {
6324 con_out("*** failed to generate output file\n");
6325 ir_builder_delete(ir);
6329 ir_builder_delete(ir);