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_addlocal(parser_t *parser, const std::string &name, ast_expression *e);
17 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
18 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e);
19 static bool parse_typedef(parser_t *parser);
20 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);
21 static ast_block* parse_block(parser_t *parser);
22 static bool parse_block_into(parser_t *parser, ast_block *block);
23 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
24 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
25 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
26 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
27 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
28 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
29 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
31 static void parseerror_(parser_t *parser, const char *fmt, ...)
35 vcompile_error(parser->lex->tok.ctx, fmt, ap);
39 template<typename... Ts>
40 static inline void parseerror(parser_t *parser, const char *fmt, const Ts&... ts) {
41 return parseerror_(parser, fmt, formatNormalize(ts)...);
44 // returns true if it counts as an error
45 static bool GMQCC_WARN parsewarning_(parser_t *parser, int warntype, const char *fmt, ...)
50 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
55 template<typename... Ts>
56 static inline bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, const Ts&... ts) {
57 return parsewarning_(parser, warntype, fmt, formatNormalize(ts)...);
60 /**********************************************************************
64 static bool parser_next(parser_t *parser)
66 /* lex_do kills the previous token */
67 parser->tok = lex_do(parser->lex);
68 if (parser->tok == TOKEN_EOF)
70 if (parser->tok >= TOKEN_ERROR) {
71 parseerror(parser, "lex error");
77 #define parser_tokval(p) ((p)->lex->tok.value)
78 #define parser_token(p) (&((p)->lex->tok))
80 char *parser_strdup(const char *str)
83 /* actually dup empty strings */
84 char *out = (char*)mem_a(1);
88 return util_strdup(str);
91 static ast_expression* parser_find_field(parser_t *parser, const char *name) {
92 return (ast_expression*)util_htget(parser->htfields, name);
94 static ast_expression* parser_find_field(parser_t *parser, const std::string &name) {
95 return parser_find_field(parser, name.c_str());
98 static ast_expression* parser_find_label(parser_t *parser, const char *name)
100 for (auto &it : parser->labels)
101 if (it->m_name == name)
105 static inline ast_expression* parser_find_label(parser_t *parser, const std::string &name) {
106 return parser_find_label(parser, name.c_str());
109 ast_expression* parser_find_global(parser_t *parser, const char *name)
111 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
114 return (ast_expression*)util_htget(parser->htglobals, name);
117 ast_expression* parser_find_global(parser_t *parser, const std::string &name) {
118 return parser_find_global(parser, name.c_str());
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->m_function_type;
127 for (auto &it : fun->m_type_params) {
128 if (it->m_name == name)
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = parser->variables.size(); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_local(parser_t *parser, const std::string &name, size_t upto, bool *isparam) {
152 return parser_find_local(parser, name.c_str(), upto, isparam);
155 static ast_expression* parser_find_var(parser_t *parser, const char *name)
159 v = parser_find_local(parser, name, 0, &dummy);
160 if (!v) v = parser_find_global(parser, name);
164 static inline ast_expression* parser_find_var(parser_t *parser, const std::string &name) {
165 return parser_find_var(parser, name.c_str());
168 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
172 hash = util_hthash(parser->typedefs[0], name);
174 for (i = parser->typedefs.size(); i > upto;) {
176 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
182 static ast_value* parser_find_typedef(parser_t *parser, const std::string &name, size_t upto) {
183 return parser_find_typedef(parser, name.c_str(), upto);
187 size_t etype; /* 0 = expression, others are operators */
191 ast_block *block; /* for commas and function calls */
204 std::vector<sy_elem> out;
205 std::vector<sy_elem> ops;
206 std::vector<size_t> argc;
207 std::vector<unsigned int> paren;
210 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
221 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
232 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
234 e.etype = 1 + (op - operators);
243 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
254 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
255 * so we need to rotate it to become ent.(foo[n]).
257 static bool rotate_entfield_array_index_nodes(ast_expression **out)
259 ast_array_index *index, *oldindex;
260 ast_entfield *entfield;
264 ast_expression *entity;
266 lex_ctx_t ctx = (*out)->m_context;
268 if (!ast_istype(*out, ast_array_index))
270 index = (ast_array_index*)*out;
272 if (!ast_istype(index->m_array, ast_entfield))
274 entfield = (ast_entfield*)index->m_array;
276 if (!ast_istype(entfield->m_field, ast_value))
278 field = (ast_value*)entfield->m_field;
280 sub = index->m_index;
281 entity = entfield->m_entity;
285 index = ast_array_index::make(ctx, field, sub);
286 entfield = new ast_entfield(ctx, entity, index);
289 oldindex->m_array = nullptr;
290 oldindex->m_index = nullptr;
296 static int store_op_for(ast_expression* expr)
298 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) && expr->m_vtype == TYPE_FIELD && expr->m_next->m_vtype == TYPE_VECTOR) {
299 return type_storep_instr[TYPE_VECTOR];
302 if (ast_istype(expr, ast_member) && ast_istype(((ast_member*)expr)->m_owner, ast_entfield)) {
303 return type_storep_instr[expr->m_vtype];
306 if (ast_istype(expr, ast_entfield)) {
307 return type_storep_instr[expr->m_vtype];
310 return type_store_instr[expr->m_vtype];
313 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
315 if (ast_istype(expr, ast_value)) {
316 ast_value *val = (ast_value*)expr;
317 if (val->m_cvq == CV_CONST) {
318 if (val->m_name[0] == '#') {
319 compile_error(ctx, "invalid assignment to a literal constant");
323 * To work around quakeworld we must elide the error and make it
326 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
327 compile_error(ctx, "assignment to constant `%s`", val->m_name);
329 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
336 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
340 ast_expression *out = nullptr;
341 ast_expression *exprs[3];
342 ast_block *blocks[3];
343 ast_binstore *asbinstore;
344 size_t i, assignop, addop, subop;
345 qcint_t generated_op = 0;
350 if (sy->ops.empty()) {
351 parseerror(parser, "internal error: missing operator");
355 if (sy->ops.back().isparen) {
356 parseerror(parser, "unmatched parenthesis");
360 op = &operators[sy->ops.back().etype - 1];
361 ctx = sy->ops.back().ctx;
363 if (sy->out.size() < op->operands) {
364 if (op->flags & OP_PREFIX)
365 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
366 else /* this should have errored previously already */
367 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
373 /* op(:?) has no input and no output */
377 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
378 for (i = 0; i < op->operands; ++i) {
379 exprs[i] = sy->out[sy->out.size()+i].out;
380 blocks[i] = sy->out[sy->out.size()+i].block;
382 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
383 !(i != 0 && op->id == opid2('?',':')) &&
384 !(i == 1 && op->id == opid1('.')))
386 if (ast_istype(exprs[i], ast_label))
387 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
389 compile_error(exprs[i]->m_context, "not an expression");
390 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
394 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
395 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
399 #define NotSameType(T) \
400 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
401 exprs[0]->m_vtype != T)
406 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
410 if (exprs[0]->m_vtype == TYPE_VECTOR &&
411 exprs[1]->m_vtype == TYPE_NOEXPR)
413 if (exprs[1] == parser->const_vec[0])
414 out = ast_member::make(ctx, exprs[0], 0, "");
415 else if (exprs[1] == parser->const_vec[1])
416 out = ast_member::make(ctx, exprs[0], 1, "");
417 else if (exprs[1] == parser->const_vec[2])
418 out = ast_member::make(ctx, exprs[0], 2, "");
420 compile_error(ctx, "access to invalid vector component");
424 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
425 if (exprs[1]->m_vtype != TYPE_FIELD) {
426 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
429 out = new ast_entfield(ctx, exprs[0], exprs[1]);
431 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
432 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
436 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
442 if (exprs[0]->m_vtype != TYPE_ARRAY &&
443 !(exprs[0]->m_vtype == TYPE_FIELD &&
444 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
446 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
447 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
450 if (exprs[1]->m_vtype != TYPE_FLOAT) {
451 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
452 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
455 out = ast_array_index::make(ctx, exprs[0], exprs[1]);
456 rotate_entfield_array_index_nodes(&out);
460 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
461 sy->out.push_back(syexp(ctx, exprs[0]));
462 sy->out.push_back(syexp(ctx, exprs[1]));
467 if (!blocks[0]->addExpr(exprs[1]))
470 blocks[0] = new ast_block(ctx);
471 if (!blocks[0]->addExpr(exprs[0]) ||
472 !blocks[0]->addExpr(exprs[1]))
477 blocks[0]->setType(*exprs[1]);
479 sy->out.push_back(syblock(ctx, blocks[0]));
486 if ((out = parser->m_fold.op(op, exprs)))
489 if (exprs[0]->m_vtype != TYPE_FLOAT &&
490 exprs[0]->m_vtype != TYPE_VECTOR) {
491 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
492 type_name[exprs[0]->m_vtype]);
495 if (exprs[0]->m_vtype == TYPE_FLOAT)
496 out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]);
498 out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]);
502 if (!(out = parser->m_fold.op(op, exprs))) {
503 switch (exprs[0]->m_vtype) {
505 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
508 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]);
511 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
512 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
514 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]);
516 /* we don't constant-fold NOT for these types */
518 out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]);
521 out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]);
524 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
525 type_name[exprs[0]->m_vtype]);
532 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
533 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
535 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
536 type_name[exprs[0]->m_vtype],
537 type_name[exprs[1]->m_vtype]);
540 if (!(out = parser->m_fold.op(op, exprs))) {
541 switch (exprs[0]->m_vtype) {
543 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
546 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
549 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
550 type_name[exprs[0]->m_vtype],
551 type_name[exprs[1]->m_vtype]);
557 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
558 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
560 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
561 type_name[exprs[1]->m_vtype],
562 type_name[exprs[0]->m_vtype]);
565 if (!(out = parser->m_fold.op(op, exprs))) {
566 switch (exprs[0]->m_vtype) {
568 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
571 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
574 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
575 type_name[exprs[1]->m_vtype],
576 type_name[exprs[0]->m_vtype]);
582 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
583 !(exprs[0]->m_vtype == TYPE_VECTOR &&
584 exprs[1]->m_vtype == TYPE_FLOAT) &&
585 !(exprs[1]->m_vtype == TYPE_VECTOR &&
586 exprs[0]->m_vtype == TYPE_FLOAT)
589 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
590 type_name[exprs[1]->m_vtype],
591 type_name[exprs[0]->m_vtype]);
594 if (!(out = parser->m_fold.op(op, exprs))) {
595 switch (exprs[0]->m_vtype) {
597 if (exprs[1]->m_vtype == TYPE_VECTOR)
598 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
600 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
603 if (exprs[1]->m_vtype == TYPE_FLOAT)
604 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
606 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
609 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
610 type_name[exprs[1]->m_vtype],
611 type_name[exprs[0]->m_vtype]);
618 if (exprs[1]->m_vtype != TYPE_FLOAT) {
619 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
620 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
621 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
624 if (!(out = parser->m_fold.op(op, exprs))) {
625 if (exprs[0]->m_vtype == TYPE_FLOAT)
626 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
628 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
629 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
630 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
637 if (NotSameType(TYPE_FLOAT)) {
638 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
639 type_name[exprs[0]->m_vtype],
640 type_name[exprs[1]->m_vtype]);
642 } else if (!(out = parser->m_fold.op(op, exprs))) {
643 /* generate a call to __builtin_mod */
644 ast_expression *mod = parser->m_intrin.func("mod");
645 ast_call *call = nullptr;
646 if (!mod) return false; /* can return null for missing floor */
648 call = ast_call::make(parser_ctx(parser), mod);
649 call->m_params.push_back(exprs[0]);
650 call->m_params.push_back(exprs[1]);
657 compile_error(ctx, "%= is unimplemented");
663 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
664 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
665 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
667 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
668 type_name[exprs[0]->m_vtype],
669 type_name[exprs[1]->m_vtype]);
673 if (!(out = parser->m_fold.op(op, exprs))) {
675 * IF the first expression is float, the following will be too
676 * since scalar ^ vector is not allowed.
678 if (exprs[0]->m_vtype == TYPE_FLOAT) {
679 out = fold::binary(ctx,
680 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
684 * The first is a vector: vector is allowed to bitop with vector and
685 * with scalar, branch here for the second operand.
687 if (exprs[1]->m_vtype == TYPE_VECTOR) {
689 * Bitop all the values of the vector components against the
690 * vectors components in question.
692 out = fold::binary(ctx,
693 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
696 out = fold::binary(ctx,
697 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
706 if (NotSameType(TYPE_FLOAT)) {
707 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
708 type_name[exprs[0]->m_vtype],
709 type_name[exprs[1]->m_vtype]);
713 if (!(out = parser->m_fold.op(op, exprs))) {
714 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
715 ast_call *call = ast_call::make(parser_ctx(parser), shift);
716 call->m_params.push_back(exprs[0]);
717 call->m_params.push_back(exprs[1]);
722 case opid3('<','<','='):
723 case opid3('>','>','='):
724 if (NotSameType(TYPE_FLOAT)) {
725 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
726 type_name[exprs[0]->m_vtype],
727 type_name[exprs[1]->m_vtype]);
731 if(!(out = parser->m_fold.op(op, exprs))) {
732 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
733 ast_call *call = ast_call::make(parser_ctx(parser), shift);
734 call->m_params.push_back(exprs[0]);
735 call->m_params.push_back(exprs[1]);
747 generated_op += 1; /* INSTR_OR */
750 generated_op += INSTR_AND;
751 if (!(out = parser->m_fold.op(op, exprs))) {
752 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
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 for logical operation with -fperl-logic: %s and %s", ty1, ty2);
758 for (i = 0; i < 2; ++i) {
759 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
760 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
762 out = ast_unary::make(ctx, INSTR_NOT_F, out);
764 exprs[i] = out; out = nullptr;
765 if (OPTS_FLAG(PERL_LOGIC)) {
766 /* here we want to keep the right expressions' type */
770 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
771 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
773 out = ast_unary::make(ctx, INSTR_NOT_F, out);
775 exprs[i] = out; out = nullptr;
776 if (OPTS_FLAG(PERL_LOGIC)) {
777 /* here we want to keep the right expressions' type */
782 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
787 if (sy->paren.back() != PAREN_TERNARY2) {
788 compile_error(ctx, "mismatched parenthesis/ternary");
791 sy->paren.pop_back();
792 if (!exprs[1]->compareType(*exprs[2])) {
793 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
794 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
795 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
798 if (!(out = parser->m_fold.op(op, exprs)))
799 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
802 case opid2('*', '*'):
803 if (NotSameType(TYPE_FLOAT)) {
804 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
805 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
806 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
811 if (!(out = parser->m_fold.op(op, exprs))) {
812 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
813 gencall->m_params.push_back(exprs[0]);
814 gencall->m_params.push_back(exprs[1]);
819 case opid2('>', '<'):
820 if (NotSameType(TYPE_VECTOR)) {
821 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
822 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
823 compile_error(ctx, "invalid types used in cross product: %s and %s",
828 if (!(out = parser->m_fold.op(op, exprs))) {
839 case opid3('<','=','>'): /* -1, 0, or 1 */
840 if (NotSameType(TYPE_FLOAT)) {
841 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
842 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
843 compile_error(ctx, "invalid types used in comparision: %s and %s",
849 if (!(out = parser->m_fold.op(op, exprs))) {
850 /* This whole block is NOT fold_binary safe */
851 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
853 eq->m_refs = AST_REF_NONE;
856 out = new ast_ternary(ctx,
857 new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
859 parser->m_fold.imm_float(2),
862 new ast_ternary(ctx, eq,
864 parser->m_fold.imm_float(0),
867 parser->m_fold.imm_float(1)
877 generated_op += 1; /* INSTR_GT */
880 generated_op += 1; /* INSTR_LT */
882 case opid2('>', '='):
883 generated_op += 1; /* INSTR_GE */
885 case opid2('<', '='):
886 generated_op += INSTR_LE;
887 if (NotSameType(TYPE_FLOAT)) {
888 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
889 type_name[exprs[0]->m_vtype],
890 type_name[exprs[1]->m_vtype]);
893 if (!(out = parser->m_fold.op(op, exprs)))
894 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
896 case opid2('!', '='):
897 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
898 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
899 type_name[exprs[0]->m_vtype],
900 type_name[exprs[1]->m_vtype]);
903 if (!(out = parser->m_fold.op(op, exprs)))
904 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
906 case opid2('=', '='):
907 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
908 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
909 type_name[exprs[0]->m_vtype],
910 type_name[exprs[1]->m_vtype]);
913 if (!(out = parser->m_fold.op(op, exprs)))
914 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
918 if (ast_istype(exprs[0], ast_entfield)) {
919 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
920 assignop = store_op_for(exprs[0]);
921 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
923 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
924 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
926 field->m_next->m_vtype == TYPE_FUNCTION &&
927 exprs[1]->m_vtype == TYPE_FUNCTION)
929 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
930 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
933 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
938 assignop = store_op_for(exprs[0]);
940 if (assignop == VINSTR_END) {
941 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
942 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
943 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
945 else if (!exprs[0]->compareType(*exprs[1]))
947 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
948 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
949 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
950 exprs[0]->m_vtype == TYPE_FUNCTION &&
951 exprs[1]->m_vtype == TYPE_FUNCTION)
953 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
954 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
957 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
960 (void)check_write_to(ctx, exprs[0]);
961 /* When we're a vector of part of an entity field we use STOREP */
962 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
963 assignop = INSTR_STOREP_F;
964 out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
966 case opid3('+','+','P'):
967 case opid3('-','-','P'):
969 if (exprs[0]->m_vtype != TYPE_FLOAT) {
970 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
971 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
974 if (op->id == opid3('+','+','P'))
978 (void)check_write_to(exprs[0]->m_context, exprs[0]);
979 if (ast_istype(exprs[0], ast_entfield)) {
980 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
982 parser->m_fold.imm_float(1));
984 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
986 parser->m_fold.imm_float(1));
989 case opid3('S','+','+'):
990 case opid3('S','-','-'):
992 if (exprs[0]->m_vtype != TYPE_FLOAT) {
993 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
994 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
997 if (op->id == opid3('S','+','+')) {
1001 addop = INSTR_SUB_F;
1002 subop = INSTR_ADD_F;
1004 (void)check_write_to(exprs[0]->m_context, exprs[0]);
1005 if (ast_istype(exprs[0], ast_entfield)) {
1006 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1008 parser->m_fold.imm_float(1));
1010 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1012 parser->m_fold.imm_float(1));
1016 out = fold::binary(ctx, subop,
1018 parser->m_fold.imm_float(1));
1021 case opid2('+','='):
1022 case opid2('-','='):
1023 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1024 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1026 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1027 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1028 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1032 (void)check_write_to(ctx, exprs[0]);
1033 assignop = store_op_for(exprs[0]);
1034 switch (exprs[0]->m_vtype) {
1036 out = new ast_binstore(ctx, assignop,
1037 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1038 exprs[0], exprs[1]);
1041 out = new ast_binstore(ctx, assignop,
1042 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1043 exprs[0], exprs[1]);
1046 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1047 type_name[exprs[0]->m_vtype],
1048 type_name[exprs[1]->m_vtype]);
1052 case opid2('*','='):
1053 case opid2('/','='):
1054 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1055 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1056 exprs[0]->m_vtype == TYPE_VECTOR))
1058 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1059 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1060 compile_error(ctx, "invalid types used in expression: %s and %s",
1064 (void)check_write_to(ctx, exprs[0]);
1065 assignop = store_op_for(exprs[0]);
1066 switch (exprs[0]->m_vtype) {
1068 out = new ast_binstore(ctx, assignop,
1069 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1070 exprs[0], exprs[1]);
1073 if (op->id == opid2('*','=')) {
1074 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1075 exprs[0], exprs[1]);
1077 out = fold::binary(ctx, INSTR_DIV_F,
1078 parser->m_fold.imm_float(1),
1081 compile_error(ctx, "internal error: failed to generate division");
1084 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1089 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1090 type_name[exprs[0]->m_vtype],
1091 type_name[exprs[1]->m_vtype]);
1095 case opid2('&','='):
1096 case opid2('|','='):
1097 case opid2('^','='):
1098 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1099 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1100 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1101 compile_error(ctx, "invalid types used in expression: %s and %s",
1105 (void)check_write_to(ctx, exprs[0]);
1106 assignop = store_op_for(exprs[0]);
1107 if (exprs[0]->m_vtype == TYPE_FLOAT)
1108 out = new ast_binstore(ctx, assignop,
1109 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1110 exprs[0], exprs[1]);
1112 out = new ast_binstore(ctx, assignop,
1113 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1114 exprs[0], exprs[1]);
1116 case opid3('&','~','='):
1117 /* This is like: a &= ~(b);
1118 * But QC has no bitwise-not, so we implement it as
1121 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1122 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124 compile_error(ctx, "invalid types used in expression: %s and %s",
1128 assignop = store_op_for(exprs[0]);
1129 if (exprs[0]->m_vtype == TYPE_FLOAT)
1130 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1132 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1135 (void)check_write_to(ctx, exprs[0]);
1136 if (exprs[0]->m_vtype == TYPE_FLOAT)
1137 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1139 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1140 asbinstore->m_keep_dest = true;
1144 case opid3('l', 'e', 'n'):
1145 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1146 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1147 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1150 /* strings must be const, arrays are statically sized */
1151 if (exprs[0]->m_vtype == TYPE_STRING &&
1152 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1154 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1157 out = parser->m_fold.op(op, exprs);
1160 case opid2('~', 'P'):
1161 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1162 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1163 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1166 if (!(out = parser->m_fold.op(op, exprs))) {
1167 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1168 out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1170 out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1177 compile_error(ctx, "failed to apply operator %s", op->op);
1181 sy->out.push_back(syexp(ctx, out));
1185 static bool parser_close_call(parser_t *parser, shunt *sy)
1187 /* was a function call */
1188 ast_expression *fun;
1189 ast_value *funval = nullptr;
1193 size_t paramcount, i;
1196 fid = sy->ops.back().off;
1199 /* out[fid] is the function
1200 * everything above is parameters...
1202 if (sy->argc.empty()) {
1203 parseerror(parser, "internal error: no argument counter available");
1207 paramcount = sy->argc.back();
1208 sy->argc.pop_back();
1210 if (sy->out.size() < fid) {
1211 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1219 * TODO handle this at the intrinsic level with an ast_intrinsic
1222 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1224 if (fid+2 != sy->out.size() || sy->out.back().block) {
1225 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1228 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1229 ast_unref(sy->out.back().out);
1230 sy->out[fid] = syexp(sy->out.back().out->m_context,
1231 parser->m_fold.constgen_string(ty, false));
1237 * Now we need to determine if the function that is being called is
1238 * an intrinsic so we can evaluate if the arguments to it are constant
1239 * and than fruitfully fold them.
1241 #define fold_can_1(X) \
1242 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1243 ((X))->m_vtype != TYPE_FUNCTION)
1245 if (fid + 1 < sy->out.size())
1248 for (i = 0; i < paramcount; ++i) {
1249 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1256 * All is well which ends well, if we make it into here we can ignore the
1257 * intrinsic call and just evaluate it i.e constant fold it.
1259 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1260 std::vector<ast_expression*> exprs;
1261 ast_expression *foldval = nullptr;
1263 exprs.reserve(paramcount);
1264 for (i = 0; i < paramcount; i++)
1265 exprs.push_back(sy->out[fid+1 + i].out);
1267 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs.data()))) {
1272 * Blub: what sorts of unreffing and resizing of
1273 * sy->out should I be doing here?
1275 sy->out[fid] = syexp(foldval->m_context, foldval);
1276 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1282 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1287 if (fid+1 + paramcount != sy->out.size()) {
1288 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1295 for (i = 0; i < paramcount; ++i)
1296 call->m_params.push_back(sy->out[fid+1 + i].out);
1297 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1298 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1299 if (parser->max_param_count < paramcount)
1300 parser->max_param_count = paramcount;
1302 if (ast_istype(fun, ast_value)) {
1303 funval = (ast_value*)fun;
1304 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1305 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1307 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1311 /* overwrite fid, the function, with a call */
1312 sy->out[fid] = syexp(call->m_context, call);
1314 if (fun->m_vtype != TYPE_FUNCTION) {
1315 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1320 parseerror(parser, "could not determine function return type");
1323 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1325 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1327 return !parsewarning(parser, WARN_DEPRECATED,
1328 "call to function (which is marked deprecated)\n",
1329 "-> it has been declared here: %s:%i",
1330 fun->m_context.file, fun->m_context.line);
1332 if (!fval->m_desc.length()) {
1333 return !parsewarning(parser, WARN_DEPRECATED,
1334 "call to `%s` (which is marked deprecated)\n"
1335 "-> `%s` declared here: %s:%i",
1336 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1338 return !parsewarning(parser, WARN_DEPRECATED,
1339 "call to `%s` (deprecated: %s)\n"
1340 "-> `%s` declared here: %s:%i",
1341 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1342 fun->m_context.line);
1345 if (fun->m_type_params.size() != paramcount &&
1346 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1347 fun->m_type_params.size() < paramcount))
1349 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1351 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1352 "too %s parameters for call to %s: expected %i, got %i\n"
1353 " -> `%s` has been declared here: %s:%i",
1354 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1355 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1357 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1358 "too %s parameters for function call: expected %i, got %i\n"
1359 " -> it has been declared here: %s:%i",
1360 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1361 fun->m_context.file, (int)fun->m_context.line);
1368 static bool parser_close_paren(parser_t *parser, shunt *sy)
1370 if (sy->ops.empty()) {
1371 parseerror(parser, "unmatched closing paren");
1375 while (sy->ops.size()) {
1376 if (sy->ops.back().isparen) {
1377 if (sy->paren.back() == PAREN_FUNC) {
1378 sy->paren.pop_back();
1379 if (!parser_close_call(parser, sy))
1383 if (sy->paren.back() == PAREN_EXPR) {
1384 sy->paren.pop_back();
1385 if (sy->out.empty()) {
1386 compile_error(sy->ops.back().ctx, "empty paren expression");
1393 if (sy->paren.back() == PAREN_INDEX) {
1394 sy->paren.pop_back();
1395 // pop off the parenthesis
1397 /* then apply the index operator */
1398 if (!parser_sy_apply_operator(parser, sy))
1402 if (sy->paren.back() == PAREN_TERNARY1) {
1403 sy->paren.back() = PAREN_TERNARY2;
1404 // pop off the parenthesis
1408 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1411 if (!parser_sy_apply_operator(parser, sy))
1417 static void parser_reclassify_token(parser_t *parser)
1420 if (parser->tok >= TOKEN_START)
1422 for (i = 0; i < operator_count; ++i) {
1423 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1424 parser->tok = TOKEN_OPERATOR;
1430 static ast_expression* parse_vararg_do(parser_t *parser)
1432 ast_expression *idx, *out;
1434 ast_value *funtype = parser->function->m_function_type;
1435 lex_ctx_t ctx = parser_ctx(parser);
1437 if (!parser->function->m_varargs) {
1438 parseerror(parser, "function has no variable argument list");
1442 if (!parser_next(parser) || parser->tok != '(') {
1443 parseerror(parser, "expected parameter index and type in parenthesis");
1446 if (!parser_next(parser)) {
1447 parseerror(parser, "error parsing parameter index");
1451 idx = parse_expression_leave(parser, true, false, false);
1455 if (parser->tok != ',') {
1456 if (parser->tok != ')') {
1458 parseerror(parser, "expected comma after parameter index");
1461 // vararg piping: ...(start)
1462 out = new ast_argpipe(ctx, idx);
1466 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1468 parseerror(parser, "expected typename for vararg");
1472 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1478 if (parser->tok != ')') {
1481 parseerror(parser, "expected closing paren");
1485 if (funtype->m_varparam &&
1486 !typevar->compareType(*funtype->m_varparam))
1490 ast_type_to_string(typevar, ty1, sizeof(ty1));
1491 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1492 compile_error(typevar->m_context,
1493 "function was declared to take varargs of type `%s`, requested type is: %s",
1497 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1498 out->adoptType(*typevar);
1503 static ast_expression* parse_vararg(parser_t *parser)
1505 bool old_noops = parser->lex->flags.noops;
1507 ast_expression *out;
1509 parser->lex->flags.noops = true;
1510 out = parse_vararg_do(parser);
1512 parser->lex->flags.noops = old_noops;
1516 /* not to be exposed */
1517 bool ftepp_predef_exists(const char *name);
1518 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1520 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1521 parser->tok == TOKEN_IDENT &&
1522 !strcmp(parser_tokval(parser), "_"))
1524 /* a translatable string */
1527 parser->lex->flags.noops = true;
1528 if (!parser_next(parser) || parser->tok != '(') {
1529 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1532 parser->lex->flags.noops = false;
1533 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1534 parseerror(parser, "expected a constant string in translatable-string extension");
1537 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1540 sy->out.push_back(syexp(parser_ctx(parser), val));
1542 if (!parser_next(parser) || parser->tok != ')') {
1543 parseerror(parser, "expected closing paren after translatable string");
1548 else if (parser->tok == TOKEN_DOTS)
1551 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1552 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1555 va = parse_vararg(parser);
1558 sy->out.push_back(syexp(parser_ctx(parser), va));
1561 else if (parser->tok == TOKEN_FLOATCONST) {
1562 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1565 sy->out.push_back(syexp(parser_ctx(parser), val));
1568 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1569 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1572 sy->out.push_back(syexp(parser_ctx(parser), val));
1575 else if (parser->tok == TOKEN_STRINGCONST) {
1576 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1579 sy->out.push_back(syexp(parser_ctx(parser), val));
1582 else if (parser->tok == TOKEN_VECTORCONST) {
1583 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1586 sy->out.push_back(syexp(parser_ctx(parser), val));
1589 else if (parser->tok == TOKEN_IDENT)
1591 const char *ctoken = parser_tokval(parser);
1592 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1593 ast_expression *var;
1594 /* a_vector.{x,y,z} */
1595 if (sy->ops.empty() ||
1596 !sy->ops.back().etype ||
1597 operators[sy->ops.back().etype-1].id != opid1('.'))
1599 /* When adding more intrinsics, fix the above condition */
1602 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1604 var = parser->const_vec[ctoken[0]-'x'];
1606 var = parser_find_var(parser, parser_tokval(parser));
1608 var = parser_find_field(parser, parser_tokval(parser));
1610 if (!var && with_labels) {
1611 var = parser_find_label(parser, parser_tokval(parser));
1613 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1615 parser->labels.push_back(lbl);
1618 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1619 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1622 * now we try for the real intrinsic hashtable. If the string
1623 * begins with __builtin, we simply skip past it, otherwise we
1624 * use the identifier as is.
1626 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1627 var = parser->m_intrin.func(parser_tokval(parser));
1631 * Try it again, intrin_func deals with the alias method as well
1632 * the first one masks for __builtin though, we emit warning here.
1635 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1636 (void)!compile_warning(
1639 "using implicitly defined builtin `__builtin_%s' for `%s'",
1640 parser_tokval(parser),
1641 parser_tokval(parser)
1649 * sometimes people use preprocessing predefs without enabling them
1650 * i've done this thousands of times already myself. Lets check for
1651 * it in the predef table. And diagnose it better :)
1653 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1654 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1658 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1664 // promote these to norefs
1665 if (ast_istype(var, ast_value))
1667 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1669 else if (ast_istype(var, ast_member))
1671 ast_member *mem = (ast_member *)var;
1672 if (ast_istype(mem->m_owner, ast_value))
1673 ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1676 sy->out.push_back(syexp(parser_ctx(parser), var));
1679 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1683 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1685 ast_expression *expr = nullptr;
1687 bool wantop = false;
1688 /* only warn once about an assignment in a truth value because the current code
1689 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1691 bool warn_parenthesis = true;
1693 /* count the parens because an if starts with one, so the
1694 * end of a condition is an unmatched closing paren
1698 memset(&sy, 0, sizeof(sy));
1700 parser->lex->flags.noops = false;
1702 parser_reclassify_token(parser);
1706 if (parser->tok == TOKEN_TYPENAME) {
1707 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1711 if (parser->tok == TOKEN_OPERATOR)
1713 /* classify the operator */
1714 const oper_info *op;
1715 const oper_info *olast = nullptr;
1717 for (o = 0; o < operator_count; ++o) {
1718 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1719 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1720 !strcmp(parser_tokval(parser), operators[o].op))
1725 if (o == operator_count) {
1726 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1729 /* found an operator */
1732 /* when declaring variables, a comma starts a new variable */
1733 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1734 /* fixup the token */
1739 /* a colon without a pervious question mark cannot be a ternary */
1740 if (!ternaries && op->id == opid2(':','?')) {
1745 if (op->id == opid1(',')) {
1746 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1747 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1751 if (sy.ops.size() && !sy.ops.back().isparen)
1752 olast = &operators[sy.ops.back().etype-1];
1754 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1755 while (olast && op->prec < olast->prec)
1757 if (!parser_sy_apply_operator(parser, &sy))
1759 if (sy.ops.size() && !sy.ops.back().isparen)
1760 olast = &operators[sy.ops.back().etype-1];
1765 #define IsAssignOp(x) (\
1766 (x) == opid1('=') || \
1767 (x) == opid2('+','=') || \
1768 (x) == opid2('-','=') || \
1769 (x) == opid2('*','=') || \
1770 (x) == opid2('/','=') || \
1771 (x) == opid2('%','=') || \
1772 (x) == opid2('&','=') || \
1773 (x) == opid2('|','=') || \
1774 (x) == opid3('&','~','=') \
1776 if (warn_parenthesis) {
1777 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1778 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1779 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1782 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1783 warn_parenthesis = false;
1786 if (olast && olast->id != op->id) {
1787 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1788 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1790 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1791 warn_parenthesis = false;
1793 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1794 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1796 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1797 warn_parenthesis = false;
1803 (op->prec < olast->prec) ||
1804 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1806 if (!parser_sy_apply_operator(parser, &sy))
1808 if (sy.ops.size() && !sy.ops.back().isparen)
1809 olast = &operators[sy.ops.back().etype-1];
1814 if (op->id == opid1('(')) {
1816 size_t sycount = sy.out.size();
1817 /* we expected an operator, this is the function-call operator */
1818 sy.paren.push_back(PAREN_FUNC);
1819 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1820 sy.argc.push_back(0);
1822 sy.paren.push_back(PAREN_EXPR);
1823 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1826 } else if (op->id == opid1('[')) {
1828 parseerror(parser, "unexpected array subscript");
1831 sy.paren.push_back(PAREN_INDEX);
1832 /* push both the operator and the paren, this makes life easier */
1833 sy.ops.push_back(syop(parser_ctx(parser), op));
1834 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1836 } else if (op->id == opid2('?',':')) {
1837 sy.ops.push_back(syop(parser_ctx(parser), op));
1838 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1841 sy.paren.push_back(PAREN_TERNARY1);
1842 } else if (op->id == opid2(':','?')) {
1843 if (sy.paren.empty()) {
1844 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1847 if (sy.paren.back() != PAREN_TERNARY1) {
1848 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1851 if (!parser_close_paren(parser, &sy))
1853 sy.ops.push_back(syop(parser_ctx(parser), op));
1857 sy.ops.push_back(syop(parser_ctx(parser), op));
1858 wantop = !!(op->flags & OP_SUFFIX);
1861 else if (parser->tok == ')') {
1862 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1863 if (!parser_sy_apply_operator(parser, &sy))
1866 if (sy.paren.empty())
1869 if (sy.paren.back() == PAREN_TERNARY1) {
1870 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1873 if (!parser_close_paren(parser, &sy))
1876 /* must be a function call without parameters */
1877 if (sy.paren.back() != PAREN_FUNC) {
1878 parseerror(parser, "closing paren in invalid position");
1881 if (!parser_close_paren(parser, &sy))
1886 else if (parser->tok == '(') {
1887 parseerror(parser, "internal error: '(' should be classified as operator");
1890 else if (parser->tok == '[') {
1891 parseerror(parser, "internal error: '[' should be classified as operator");
1894 else if (parser->tok == ']') {
1895 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1896 if (!parser_sy_apply_operator(parser, &sy))
1899 if (sy.paren.empty())
1901 if (sy.paren.back() != PAREN_INDEX) {
1902 parseerror(parser, "mismatched parentheses, unexpected ']'");
1905 if (!parser_close_paren(parser, &sy))
1910 if (!parse_sya_operand(parser, &sy, with_labels))
1915 /* in this case we might want to allow constant string concatenation */
1916 bool concatenated = false;
1917 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1918 ast_expression *lexpr = sy.out.back().out;
1919 if (ast_istype(lexpr, ast_value)) {
1920 ast_value *last = (ast_value*)lexpr;
1921 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1922 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1924 char *newstr = nullptr;
1925 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1926 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1928 concatenated = true;
1932 if (!concatenated) {
1933 parseerror(parser, "expected operator or end of statement");
1938 if (!parser_next(parser)) {
1941 if (parser->tok == ';' ||
1942 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1943 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1949 while (sy.ops.size()) {
1950 if (!parser_sy_apply_operator(parser, &sy))
1954 parser->lex->flags.noops = true;
1955 if (sy.out.size() != 1) {
1956 parseerror(parser, "expression expected");
1959 expr = sy.out[0].out;
1960 if (sy.paren.size()) {
1961 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1967 parser->lex->flags.noops = true;
1968 for (auto &it : sy.out)
1969 if (it.out) ast_unref(it.out);
1973 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1975 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1978 if (parser->tok != ';') {
1979 parseerror(parser, "semicolon expected after expression");
1983 if (!parser_next(parser)) {
1990 static void parser_enterblock(parser_t *parser)
1992 parser->variables.push_back(util_htnew(PARSER_HT_SIZE));
1993 parser->_blocklocals.push_back(parser->_locals.size());
1994 parser->typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
1995 parser->_blocktypedefs.push_back(parser->_typedefs.size());
1996 parser->_block_ctx.push_back(parser_ctx(parser));
1999 static bool parser_leaveblock(parser_t *parser)
2002 size_t locals, typedefs;
2004 if (parser->variables.size() <= PARSER_HT_LOCALS) {
2005 parseerror(parser, "internal error: parser_leaveblock with no block");
2009 util_htdel(parser->variables.back());
2011 parser->variables.pop_back();
2012 if (!parser->_blocklocals.size()) {
2013 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2017 locals = parser->_blocklocals.back();
2018 parser->_blocklocals.pop_back();
2019 parser->_locals.resize(locals);
2021 typedefs = parser->_blocktypedefs.back();
2022 parser->_typedefs.resize(typedefs);
2023 util_htdel(parser->typedefs.back());
2024 parser->typedefs.pop_back();
2026 parser->_block_ctx.pop_back();
2031 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2033 parser->_locals.push_back(e);
2034 util_htset(parser->variables.back(), name, (void*)e);
2036 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2037 return parser_addlocal(parser, name.c_str(), e);
2040 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2042 parser->globals.push_back(e);
2043 util_htset(parser->htglobals, name, e);
2045 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2046 return parser_addglobal(parser, name.c_str(), e);
2049 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2053 ast_expression *prev;
2055 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2057 ast_type_to_string(cond, ty, sizeof(ty));
2058 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2061 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2064 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2067 parseerror(parser, "internal error: failed to process condition");
2072 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2074 /* vector types need to be cast to true booleans */
2075 ast_binary *bin = (ast_binary*)cond;
2076 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2078 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2080 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2083 parseerror(parser, "internal error: failed to process condition");
2090 unary = (ast_unary*)cond;
2091 /* ast_istype dereferences cond, should test here for safety */
2092 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2094 cond = unary->m_operand;
2095 unary->m_operand = nullptr;
2098 unary = (ast_unary*)cond;
2102 parseerror(parser, "internal error: failed to process condition");
2104 if (ifnot) *_ifnot = !*_ifnot;
2108 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2111 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2114 lex_ctx_t ctx = parser_ctx(parser);
2116 (void)block; /* not touching */
2118 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2119 if (!parser_next(parser)) {
2120 parseerror(parser, "expected condition or 'not'");
2123 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2125 if (!parser_next(parser)) {
2126 parseerror(parser, "expected condition in parenthesis");
2130 if (parser->tok != '(') {
2131 parseerror(parser, "expected 'if' condition in parenthesis");
2134 /* parse into the expression */
2135 if (!parser_next(parser)) {
2136 parseerror(parser, "expected 'if' condition after opening paren");
2139 /* parse the condition */
2140 cond = parse_expression_leave(parser, false, true, false);
2144 if (parser->tok != ')') {
2145 parseerror(parser, "expected closing paren after 'if' condition");
2149 /* parse into the 'then' branch */
2150 if (!parser_next(parser)) {
2151 parseerror(parser, "expected statement for on-true branch of 'if'");
2155 if (!parse_statement_or_block(parser, &ontrue)) {
2160 ontrue = new ast_block(parser_ctx(parser));
2161 /* check for an else */
2162 if (!strcmp(parser_tokval(parser), "else")) {
2163 /* parse into the 'else' branch */
2164 if (!parser_next(parser)) {
2165 parseerror(parser, "expected on-false branch after 'else'");
2170 if (!parse_statement_or_block(parser, &onfalse)) {
2177 cond = process_condition(parser, cond, &ifnot);
2179 if (ontrue) delete ontrue;
2180 if (onfalse) delete onfalse;
2185 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2187 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2192 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2193 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2196 char *label = nullptr;
2198 /* skip the 'while' and get the body */
2199 if (!parser_next(parser)) {
2200 if (OPTS_FLAG(LOOP_LABELS))
2201 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2203 parseerror(parser, "expected 'while' condition in parenthesis");
2207 if (parser->tok == ':') {
2208 if (!OPTS_FLAG(LOOP_LABELS))
2209 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2210 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2211 parseerror(parser, "expected loop label");
2214 label = util_strdup(parser_tokval(parser));
2215 if (!parser_next(parser)) {
2217 parseerror(parser, "expected 'while' condition in parenthesis");
2222 if (parser->tok != '(') {
2223 parseerror(parser, "expected 'while' condition in parenthesis");
2227 parser->breaks.push_back(label);
2228 parser->continues.push_back(label);
2230 rv = parse_while_go(parser, block, out);
2233 if (parser->breaks.back() != label || parser->continues.back() != label) {
2234 parseerror(parser, "internal error: label stack corrupted");
2240 parser->breaks.pop_back();
2241 parser->continues.pop_back();
2246 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2249 ast_expression *cond, *ontrue;
2253 lex_ctx_t ctx = parser_ctx(parser);
2255 (void)block; /* not touching */
2257 /* parse into the expression */
2258 if (!parser_next(parser)) {
2259 parseerror(parser, "expected 'while' condition after opening paren");
2262 /* parse the condition */
2263 cond = parse_expression_leave(parser, false, true, false);
2267 if (parser->tok != ')') {
2268 parseerror(parser, "expected closing paren after 'while' condition");
2272 /* parse into the 'then' branch */
2273 if (!parser_next(parser)) {
2274 parseerror(parser, "expected while-loop body");
2278 if (!parse_statement_or_block(parser, &ontrue)) {
2283 cond = process_condition(parser, cond, &ifnot);
2288 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2293 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2294 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2297 char *label = nullptr;
2299 /* skip the 'do' and get the body */
2300 if (!parser_next(parser)) {
2301 if (OPTS_FLAG(LOOP_LABELS))
2302 parseerror(parser, "expected loop label or body");
2304 parseerror(parser, "expected loop body");
2308 if (parser->tok == ':') {
2309 if (!OPTS_FLAG(LOOP_LABELS))
2310 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2311 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2312 parseerror(parser, "expected loop label");
2315 label = util_strdup(parser_tokval(parser));
2316 if (!parser_next(parser)) {
2318 parseerror(parser, "expected loop body");
2323 parser->breaks.push_back(label);
2324 parser->continues.push_back(label);
2326 rv = parse_dowhile_go(parser, block, out);
2329 if (parser->breaks.back() != label || parser->continues.back() != label) {
2330 parseerror(parser, "internal error: label stack corrupted");
2336 parser->breaks.pop_back();
2337 parser->continues.pop_back();
2342 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2345 ast_expression *cond, *ontrue;
2349 lex_ctx_t ctx = parser_ctx(parser);
2351 (void)block; /* not touching */
2353 if (!parse_statement_or_block(parser, &ontrue))
2356 /* expect the "while" */
2357 if (parser->tok != TOKEN_KEYWORD ||
2358 strcmp(parser_tokval(parser), "while"))
2360 parseerror(parser, "expected 'while' and condition");
2365 /* skip the 'while' and check for opening paren */
2366 if (!parser_next(parser) || parser->tok != '(') {
2367 parseerror(parser, "expected 'while' condition in parenthesis");
2371 /* parse into the expression */
2372 if (!parser_next(parser)) {
2373 parseerror(parser, "expected 'while' condition after opening paren");
2377 /* parse the condition */
2378 cond = parse_expression_leave(parser, false, true, false);
2382 if (parser->tok != ')') {
2383 parseerror(parser, "expected closing paren after 'while' condition");
2389 if (!parser_next(parser) || parser->tok != ';') {
2390 parseerror(parser, "expected semicolon after condition");
2396 if (!parser_next(parser)) {
2397 parseerror(parser, "parse error");
2403 cond = process_condition(parser, cond, &ifnot);
2408 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2413 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2414 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2417 char *label = nullptr;
2419 /* skip the 'for' and check for opening paren */
2420 if (!parser_next(parser)) {
2421 if (OPTS_FLAG(LOOP_LABELS))
2422 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2424 parseerror(parser, "expected 'for' expressions in parenthesis");
2428 if (parser->tok == ':') {
2429 if (!OPTS_FLAG(LOOP_LABELS))
2430 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2431 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2432 parseerror(parser, "expected loop label");
2435 label = util_strdup(parser_tokval(parser));
2436 if (!parser_next(parser)) {
2438 parseerror(parser, "expected 'for' expressions in parenthesis");
2443 if (parser->tok != '(') {
2444 parseerror(parser, "expected 'for' expressions in parenthesis");
2448 parser->breaks.push_back(label);
2449 parser->continues.push_back(label);
2451 rv = parse_for_go(parser, block, out);
2454 if (parser->breaks.back() != label || parser->continues.back() != label) {
2455 parseerror(parser, "internal error: label stack corrupted");
2461 parser->breaks.pop_back();
2462 parser->continues.pop_back();
2466 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2469 ast_expression *initexpr, *cond, *increment, *ontrue;
2474 lex_ctx_t ctx = parser_ctx(parser);
2476 parser_enterblock(parser);
2480 increment = nullptr;
2483 /* parse into the expression */
2484 if (!parser_next(parser)) {
2485 parseerror(parser, "expected 'for' initializer after opening paren");
2490 if (parser->tok == TOKEN_IDENT)
2491 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2493 if (typevar || parser->tok == TOKEN_TYPENAME) {
2494 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2497 else if (parser->tok != ';')
2499 initexpr = parse_expression_leave(parser, false, false, false);
2502 /* move on to condition */
2503 if (parser->tok != ';') {
2504 parseerror(parser, "expected semicolon after for-loop initializer");
2507 if (!parser_next(parser)) {
2508 parseerror(parser, "expected for-loop condition");
2511 } else if (!parser_next(parser)) {
2512 parseerror(parser, "expected for-loop condition");
2516 /* parse the condition */
2517 if (parser->tok != ';') {
2518 cond = parse_expression_leave(parser, false, true, false);
2522 /* move on to incrementor */
2523 if (parser->tok != ';') {
2524 parseerror(parser, "expected semicolon after for-loop initializer");
2527 if (!parser_next(parser)) {
2528 parseerror(parser, "expected for-loop condition");
2532 /* parse the incrementor */
2533 if (parser->tok != ')') {
2534 lex_ctx_t condctx = parser_ctx(parser);
2535 increment = parse_expression_leave(parser, false, false, false);
2538 if (!increment->m_side_effects) {
2539 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2545 if (parser->tok != ')') {
2546 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2549 /* parse into the 'then' branch */
2550 if (!parser_next(parser)) {
2551 parseerror(parser, "expected for-loop body");
2554 if (!parse_statement_or_block(parser, &ontrue))
2558 cond = process_condition(parser, cond, &ifnot);
2562 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2565 if (!parser_leaveblock(parser)) {
2571 if (initexpr) ast_unref(initexpr);
2572 if (cond) ast_unref(cond);
2573 if (increment) ast_unref(increment);
2574 (void)!parser_leaveblock(parser);
2578 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2580 ast_expression *exp = nullptr;
2581 ast_expression *var = nullptr;
2582 ast_return *ret = nullptr;
2583 ast_value *retval = parser->function->m_return_value;
2584 ast_value *expected = parser->function->m_function_type;
2586 lex_ctx_t ctx = parser_ctx(parser);
2588 (void)block; /* not touching */
2590 if (!parser_next(parser)) {
2591 parseerror(parser, "expected return expression");
2595 /* return assignments */
2596 if (parser->tok == '=') {
2597 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2598 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2602 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2604 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2605 parseerror(parser, "invalid return type: `%s'", ty1);
2609 if (!parser_next(parser)) {
2610 parseerror(parser, "expected return assignment expression");
2614 if (!(exp = parse_expression_leave(parser, false, false, false)))
2617 /* prepare the return value */
2619 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2620 retval->adoptType(*expected->m_next);
2621 parser->function->m_return_value = retval;
2622 parser->function->m_return_value->m_flags |= AST_FLAG_NOREF;
2625 if (!exp->compareType(*retval)) {
2626 char ty1[1024], ty2[1024];
2627 ast_type_to_string(exp, ty1, sizeof(ty1));
2628 ast_type_to_string(retval, ty2, sizeof(ty2));
2629 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2632 /* store to 'return' local variable */
2633 var = new ast_store(
2635 type_store_instr[expected->m_next->m_vtype],
2643 if (parser->tok != ';')
2644 parseerror(parser, "missing semicolon after return assignment");
2645 else if (!parser_next(parser))
2646 parseerror(parser, "parse error after return assignment");
2652 if (parser->tok != ';') {
2653 exp = parse_expression(parser, false, false);
2657 if (exp->m_vtype != TYPE_NIL &&
2658 exp->m_vtype != (expected)->m_next->m_vtype)
2660 parseerror(parser, "return with invalid expression");
2663 ret = new ast_return(ctx, exp);
2669 if (!parser_next(parser))
2670 parseerror(parser, "parse error");
2672 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2674 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2676 ret = new ast_return(ctx, retval);
2682 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2685 unsigned int levels = 0;
2686 lex_ctx_t ctx = parser_ctx(parser);
2687 auto &loops = (is_continue ? parser->continues : parser->breaks);
2689 (void)block; /* not touching */
2690 if (!parser_next(parser)) {
2691 parseerror(parser, "expected semicolon or loop label");
2695 if (loops.empty()) {
2697 parseerror(parser, "`continue` can only be used inside loops");
2699 parseerror(parser, "`break` can only be used inside loops or switches");
2702 if (parser->tok == TOKEN_IDENT) {
2703 if (!OPTS_FLAG(LOOP_LABELS))
2704 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2707 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2710 parseerror(parser, "no such loop to %s: `%s`",
2711 (is_continue ? "continue" : "break out of"),
2712 parser_tokval(parser));
2717 if (!parser_next(parser)) {
2718 parseerror(parser, "expected semicolon");
2723 if (parser->tok != ';') {
2724 parseerror(parser, "expected semicolon");
2728 if (!parser_next(parser))
2729 parseerror(parser, "parse error");
2731 *out = new ast_breakcont(ctx, is_continue, levels);
2735 /* returns true when it was a variable qualifier, false otherwise!
2736 * on error, cvq is set to CV_WRONG
2738 struct attribute_t {
2743 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2745 bool had_const = false;
2746 bool had_var = false;
2747 bool had_noref = false;
2748 bool had_attrib = false;
2749 bool had_static = false;
2752 static attribute_t attributes[] = {
2753 { "noreturn", AST_FLAG_NORETURN },
2754 { "inline", AST_FLAG_INLINE },
2755 { "eraseable", AST_FLAG_ERASEABLE },
2756 { "accumulate", AST_FLAG_ACCUMULATE },
2757 { "last", AST_FLAG_FINAL_DECL }
2764 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2766 /* parse an attribute */
2767 if (!parser_next(parser)) {
2768 parseerror(parser, "expected attribute after `[[`");
2773 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2774 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2775 flags |= attributes[i].flag;
2776 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2777 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2778 attributes[i].name);
2786 if (i != GMQCC_ARRAY_COUNT(attributes))
2790 if (!strcmp(parser_tokval(parser), "noref")) {
2792 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2793 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2798 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2799 flags |= AST_FLAG_ALIAS;
2802 if (!parser_next(parser)) {
2803 parseerror(parser, "parse error in attribute");
2807 if (parser->tok == '(') {
2808 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2809 parseerror(parser, "`alias` attribute missing parameter");
2813 *message = util_strdup(parser_tokval(parser));
2815 if (!parser_next(parser)) {
2816 parseerror(parser, "parse error in attribute");
2820 if (parser->tok != ')') {
2821 parseerror(parser, "`alias` attribute expected `)` after parameter");
2825 if (!parser_next(parser)) {
2826 parseerror(parser, "parse error in attribute");
2831 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2832 parseerror(parser, "`alias` attribute expected `]]`");
2836 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2837 flags |= AST_FLAG_DEPRECATED;
2840 if (!parser_next(parser)) {
2841 parseerror(parser, "parse error in attribute");
2845 if (parser->tok == '(') {
2846 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2847 parseerror(parser, "`deprecated` attribute missing parameter");
2851 *message = util_strdup(parser_tokval(parser));
2853 if (!parser_next(parser)) {
2854 parseerror(parser, "parse error in attribute");
2858 if(parser->tok != ')') {
2859 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2863 if (!parser_next(parser)) {
2864 parseerror(parser, "parse error in attribute");
2869 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2870 parseerror(parser, "`deprecated` attribute expected `]]`");
2873 if (*message) mem_d(*message);
2879 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2880 flags |= AST_FLAG_COVERAGE;
2881 if (!parser_next(parser)) {
2883 parseerror(parser, "parse error in coverage attribute");
2887 if (parser->tok == '(') {
2888 if (!parser_next(parser)) {
2890 parseerror(parser, "invalid parameter for coverage() attribute\n"
2891 "valid are: block");
2895 if (parser->tok != ')') {
2897 if (parser->tok != TOKEN_IDENT)
2898 goto bad_coverage_arg;
2899 if (!strcmp(parser_tokval(parser), "block"))
2900 flags |= AST_FLAG_BLOCK_COVERAGE;
2901 else if (!strcmp(parser_tokval(parser), "none"))
2902 flags &= ~(AST_FLAG_COVERAGE_MASK);
2904 goto bad_coverage_arg;
2905 if (!parser_next(parser))
2906 goto error_in_coverage;
2907 if (parser->tok == ',') {
2908 if (!parser_next(parser))
2909 goto error_in_coverage;
2911 } while (parser->tok != ')');
2913 if (parser->tok != ')' || !parser_next(parser))
2914 goto error_in_coverage;
2916 /* without parameter [[coverage]] equals [[coverage(block)]] */
2917 flags |= AST_FLAG_BLOCK_COVERAGE;
2922 /* Skip tokens until we hit a ]] */
2923 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2924 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2925 if (!parser_next(parser)) {
2926 parseerror(parser, "error inside attribute");
2933 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2935 else if (!strcmp(parser_tokval(parser), "const"))
2937 else if (!strcmp(parser_tokval(parser), "var"))
2939 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2941 else if (!strcmp(parser_tokval(parser), "noref"))
2943 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2950 if (!parser_next(parser))
2960 *is_static = had_static;
2964 parseerror(parser, "parse error after variable qualifier");
2969 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2970 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2973 char *label = nullptr;
2975 /* skip the 'while' and get the body */
2976 if (!parser_next(parser)) {
2977 if (OPTS_FLAG(LOOP_LABELS))
2978 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2980 parseerror(parser, "expected 'switch' operand in parenthesis");
2984 if (parser->tok == ':') {
2985 if (!OPTS_FLAG(LOOP_LABELS))
2986 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2987 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2988 parseerror(parser, "expected loop label");
2991 label = util_strdup(parser_tokval(parser));
2992 if (!parser_next(parser)) {
2994 parseerror(parser, "expected 'switch' operand in parenthesis");
2999 if (parser->tok != '(') {
3000 parseerror(parser, "expected 'switch' operand in parenthesis");
3004 parser->breaks.push_back(label);
3006 rv = parse_switch_go(parser, block, out);
3009 if (parser->breaks.back() != label) {
3010 parseerror(parser, "internal error: label stack corrupted");
3016 parser->breaks.pop_back();
3021 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3023 ast_expression *operand;
3026 ast_switch *switchnode;
3027 ast_switch_case swcase;
3030 bool noref, is_static;
3031 uint32_t qflags = 0;
3033 lex_ctx_t ctx = parser_ctx(parser);
3035 (void)block; /* not touching */
3038 /* parse into the expression */
3039 if (!parser_next(parser)) {
3040 parseerror(parser, "expected switch operand");
3043 /* parse the operand */
3044 operand = parse_expression_leave(parser, false, false, false);
3048 switchnode = new ast_switch(ctx, operand);
3051 if (parser->tok != ')') {
3053 parseerror(parser, "expected closing paren after 'switch' operand");
3057 /* parse over the opening paren */
3058 if (!parser_next(parser) || parser->tok != '{') {
3060 parseerror(parser, "expected list of cases");
3064 if (!parser_next(parser)) {
3066 parseerror(parser, "expected 'case' or 'default'");
3070 /* new block; allow some variables to be declared here */
3071 parser_enterblock(parser);
3074 if (parser->tok == TOKEN_IDENT)
3075 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3076 if (typevar || parser->tok == TOKEN_TYPENAME) {
3077 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3083 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3085 if (cvq == CV_WRONG) {
3089 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3099 while (parser->tok != '}') {
3100 ast_block *caseblock;
3102 if (!strcmp(parser_tokval(parser), "case")) {
3103 if (!parser_next(parser)) {
3105 parseerror(parser, "expected expression for case");
3108 swcase.m_value = parse_expression_leave(parser, false, false, false);
3110 if (!operand->compareType(*swcase.m_value)) {
3114 ast_type_to_string(swcase.m_value, ty1, sizeof ty1);
3115 ast_type_to_string(operand, ty2, sizeof ty2);
3117 auto fnLiteral = [](ast_expression *expression) -> char* {
3118 if (!ast_istype(expression, ast_value))
3120 ast_value *value = (ast_value *)expression;
3121 if (!value->m_hasvalue)
3123 char *string = nullptr;
3124 basic_value_t *constval = &value->m_constval;
3125 switch (value->m_vtype)
3128 util_asprintf(&string, "%.2f", constval->vfloat);
3131 util_asprintf(&string, "'%.2f %.2f %.2f'",
3137 util_asprintf(&string, "\"%s\"", constval->vstring);
3145 char *literal = fnLiteral(swcase.m_value);
3147 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case `%s` expected `%s`", ty1, literal, ty2);
3149 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case expected `%s`", ty1, ty2);
3155 if (!swcase.m_value) {
3157 parseerror(parser, "expected expression for case");
3160 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3161 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3162 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3168 else if (!strcmp(parser_tokval(parser), "default")) {
3169 swcase.m_value = nullptr;
3170 if (!parser_next(parser)) {
3172 parseerror(parser, "expected colon");
3178 parseerror(parser, "expected 'case' or 'default'");
3182 /* Now the colon and body */
3183 if (parser->tok != ':') {
3184 if (swcase.m_value) ast_unref(swcase.m_value);
3186 parseerror(parser, "expected colon");
3190 if (!parser_next(parser)) {
3191 if (swcase.m_value) ast_unref(swcase.m_value);
3193 parseerror(parser, "expected statements or case");
3196 caseblock = new ast_block(parser_ctx(parser));
3198 if (swcase.m_value) ast_unref(swcase.m_value);
3202 swcase.m_code = caseblock;
3203 switchnode->m_cases.push_back(swcase);
3205 ast_expression *expr;
3206 if (parser->tok == '}')
3208 if (parser->tok == TOKEN_KEYWORD) {
3209 if (!strcmp(parser_tokval(parser), "case") ||
3210 !strcmp(parser_tokval(parser), "default"))
3215 if (!parse_statement(parser, caseblock, &expr, true)) {
3221 if (!caseblock->addExpr(expr)) {
3228 parser_leaveblock(parser);
3231 if (parser->tok != '}') {
3233 parseerror(parser, "expected closing paren of case list");
3236 if (!parser_next(parser)) {
3238 parseerror(parser, "parse error after switch");
3245 /* parse computed goto sides */
3246 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3247 ast_expression *on_true;
3248 ast_expression *on_false;
3249 ast_expression *cond;
3254 if (ast_istype(*side, ast_ternary)) {
3255 ast_ternary *tern = (ast_ternary*)*side;
3256 on_true = parse_goto_computed(parser, &tern->m_on_true);
3257 on_false = parse_goto_computed(parser, &tern->m_on_false);
3259 if (!on_true || !on_false) {
3260 parseerror(parser, "expected label or expression in ternary");
3261 if (on_true) ast_unref(on_true);
3262 if (on_false) ast_unref(on_false);
3266 cond = tern->m_cond;
3267 tern->m_cond = nullptr;
3270 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3271 } else if (ast_istype(*side, ast_label)) {
3272 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3273 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3280 static bool parse_goto(parser_t *parser, ast_expression **out)
3282 ast_goto *gt = nullptr;
3283 ast_expression *lbl;
3285 if (!parser_next(parser))
3288 if (parser->tok != TOKEN_IDENT) {
3289 ast_expression *expression;
3291 /* could be an expression i.e computed goto :-) */
3292 if (parser->tok != '(') {
3293 parseerror(parser, "expected label name after `goto`");
3297 /* failed to parse expression for goto */
3298 if (!(expression = parse_expression(parser, false, true)) ||
3299 !(*out = parse_goto_computed(parser, &expression))) {
3300 parseerror(parser, "invalid goto expression");
3302 ast_unref(expression);
3309 /* not computed goto */
3310 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3311 lbl = parser_find_label(parser, gt->m_name);
3313 if (!ast_istype(lbl, ast_label)) {
3314 parseerror(parser, "internal error: label is not an ast_label");
3318 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3321 parser->gotos.push_back(gt);
3323 if (!parser_next(parser) || parser->tok != ';') {
3324 parseerror(parser, "semicolon expected after goto label");
3327 if (!parser_next(parser)) {
3328 parseerror(parser, "parse error after goto");
3336 static bool parse_skipwhite(parser_t *parser)
3339 if (!parser_next(parser))
3341 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3342 return parser->tok < TOKEN_ERROR;
3345 static bool parse_eol(parser_t *parser)
3347 if (!parse_skipwhite(parser))
3349 return parser->tok == TOKEN_EOL;
3352 static bool parse_pragma_do(parser_t *parser)
3354 if (!parser_next(parser) ||
3355 parser->tok != TOKEN_IDENT ||
3356 strcmp(parser_tokval(parser), "pragma"))
3358 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3361 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3362 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3366 if (!strcmp(parser_tokval(parser), "noref")) {
3367 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3368 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3371 parser->noref = !!parser_token(parser)->constval.i;
3372 if (!parse_eol(parser)) {
3373 parseerror(parser, "parse error after `noref` pragma");
3379 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3382 while (!parse_eol(parser)) {
3383 parser_next(parser);
3392 static bool parse_pragma(parser_t *parser)
3395 parser->lex->flags.preprocessing = true;
3396 parser->lex->flags.mergelines = true;
3397 rv = parse_pragma_do(parser);
3398 if (parser->tok != TOKEN_EOL) {
3399 parseerror(parser, "junk after pragma");
3402 parser->lex->flags.preprocessing = false;
3403 parser->lex->flags.mergelines = false;
3404 if (!parser_next(parser)) {
3405 parseerror(parser, "parse error after pragma");
3411 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3413 bool noref, is_static;
3415 uint32_t qflags = 0;
3416 ast_value *typevar = nullptr;
3417 char *vstring = nullptr;
3421 if (parser->tok == TOKEN_IDENT)
3422 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3424 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3426 /* local variable */
3428 parseerror(parser, "cannot declare a variable from here");
3431 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3432 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3435 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3439 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3441 if (cvq == CV_WRONG)
3443 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3445 else if (parser->tok == TOKEN_KEYWORD)
3447 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3452 if (!parser_next(parser)) {
3453 parseerror(parser, "parse error after __builtin_debug_printtype");
3457 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3459 ast_type_to_string(tdef, ty, sizeof(ty));
3460 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3461 if (!parser_next(parser)) {
3462 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3468 if (!parse_statement(parser, block, out, allow_cases))
3471 con_out("__builtin_debug_printtype: got no output node\n");
3474 ast_type_to_string(*out, ty, sizeof(ty));
3475 con_out("__builtin_debug_printtype: `%s`\n", ty);
3480 else if (!strcmp(parser_tokval(parser), "return"))
3482 return parse_return(parser, block, out);
3484 else if (!strcmp(parser_tokval(parser), "if"))
3486 return parse_if(parser, block, out);
3488 else if (!strcmp(parser_tokval(parser), "while"))
3490 return parse_while(parser, block, out);
3492 else if (!strcmp(parser_tokval(parser), "do"))
3494 return parse_dowhile(parser, block, out);
3496 else if (!strcmp(parser_tokval(parser), "for"))
3498 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3499 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3502 return parse_for(parser, block, out);
3504 else if (!strcmp(parser_tokval(parser), "break"))
3506 return parse_break_continue(parser, block, out, false);
3508 else if (!strcmp(parser_tokval(parser), "continue"))
3510 return parse_break_continue(parser, block, out, true);
3512 else if (!strcmp(parser_tokval(parser), "switch"))
3514 return parse_switch(parser, block, out);
3516 else if (!strcmp(parser_tokval(parser), "case") ||
3517 !strcmp(parser_tokval(parser), "default"))
3520 parseerror(parser, "unexpected 'case' label");
3525 else if (!strcmp(parser_tokval(parser), "goto"))
3527 return parse_goto(parser, out);
3529 else if (!strcmp(parser_tokval(parser), "typedef"))
3531 if (!parser_next(parser)) {
3532 parseerror(parser, "expected type definition after 'typedef'");
3535 return parse_typedef(parser);
3537 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3540 else if (parser->tok == '{')
3543 inner = parse_block(parser);
3549 else if (parser->tok == ':')
3553 if (!parser_next(parser)) {
3554 parseerror(parser, "expected label name");
3557 if (parser->tok != TOKEN_IDENT) {
3558 parseerror(parser, "label must be an identifier");
3561 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3563 if (!label->m_undefined) {
3564 parseerror(parser, "label `%s` already defined", label->m_name);
3567 label->m_undefined = false;
3570 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3571 parser->labels.push_back(label);
3574 if (!parser_next(parser)) {
3575 parseerror(parser, "parse error after label");
3578 for (i = 0; i < parser->gotos.size(); ++i) {
3579 if (parser->gotos[i]->m_name == label->m_name) {
3580 parser->gotos[i]->setLabel(label);
3581 parser->gotos.erase(parser->gotos.begin() + i);
3587 else if (parser->tok == ';')
3589 if (!parser_next(parser)) {
3590 parseerror(parser, "parse error after empty statement");
3597 lex_ctx_t ctx = parser_ctx(parser);
3598 ast_expression *exp = parse_expression(parser, false, false);
3602 if (!exp->m_side_effects) {
3603 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3610 static bool parse_enum(parser_t *parser)
3613 bool reverse = false;
3615 ast_value *var = nullptr;
3617 std::vector<ast_value*> values;
3619 ast_expression *old;
3621 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3622 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3626 /* enumeration attributes (can add more later) */
3627 if (parser->tok == ':') {
3628 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3629 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3634 if (!strcmp(parser_tokval(parser), "flag")) {
3638 else if (!strcmp(parser_tokval(parser), "reverse")) {
3642 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3646 if (!parser_next(parser) || parser->tok != '{') {
3647 parseerror(parser, "expected `{` after enum attribute ");
3653 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3654 if (parser->tok == '}') {
3655 /* allow an empty enum */
3658 parseerror(parser, "expected identifier or `}`");
3662 old = parser_find_field(parser, parser_tokval(parser));
3664 old = parser_find_global(parser, parser_tokval(parser));
3666 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3667 parser_tokval(parser), old->m_context.file, old->m_context.line);
3671 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3672 values.push_back(var);
3673 var->m_cvq = CV_CONST;
3674 var->m_hasvalue = true;
3676 /* for flagged enumerations increment in POTs of TWO */
3677 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3678 parser_addglobal(parser, var->m_name, var);
3680 if (!parser_next(parser)) {
3681 parseerror(parser, "expected `=`, `}` or comma after identifier");
3685 if (parser->tok == ',')
3687 if (parser->tok == '}')
3689 if (parser->tok != '=') {
3690 parseerror(parser, "expected `=`, `}` or comma after identifier");
3694 if (!parser_next(parser)) {
3695 parseerror(parser, "expected expression after `=`");
3699 /* We got a value! */
3700 old = parse_expression_leave(parser, true, false, false);
3701 asvalue = (ast_value*)old;
3702 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3703 compile_error(var->m_context, "constant value or expression expected");
3706 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3708 if (parser->tok == '}')
3710 if (parser->tok != ',') {
3711 parseerror(parser, "expected `}` or comma after expression");
3716 /* patch them all (for reversed attribute) */
3719 for (i = 0; i < values.size(); i++)
3720 values[i]->m_constval.vfloat = values.size() - i - 1;
3723 if (parser->tok != '}') {
3724 parseerror(parser, "internal error: breaking without `}`");
3728 if (!parser_next(parser) || parser->tok != ';') {
3729 parseerror(parser, "expected semicolon after enumeration");
3733 if (!parser_next(parser)) {
3734 parseerror(parser, "parse error after enumeration");
3741 static bool parse_block_into(parser_t *parser, ast_block *block)
3745 parser_enterblock(parser);
3747 if (!parser_next(parser)) { /* skip the '{' */
3748 parseerror(parser, "expected function body");
3752 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3754 ast_expression *expr = nullptr;
3755 if (parser->tok == '}')
3758 if (!parse_statement(parser, block, &expr, false)) {
3759 /* parseerror(parser, "parse error"); */
3765 if (!block->addExpr(expr)) {
3772 if (parser->tok != '}') {
3775 (void)parser_next(parser);
3779 if (!parser_leaveblock(parser))
3781 return retval && !!block;
3784 static ast_block* parse_block(parser_t *parser)
3787 block = new ast_block(parser_ctx(parser));
3790 if (!parse_block_into(parser, block)) {
3797 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3799 if (parser->tok == '{') {
3800 *out = parse_block(parser);
3803 return parse_statement(parser, nullptr, out, false);
3806 static bool create_vector_members(ast_value *var, ast_member **me)
3809 size_t len = var->m_name.length();
3811 for (i = 0; i < 3; ++i) {
3812 char *name = (char*)mem_a(len+3);
3813 memcpy(name, var->m_name.c_str(), len);
3815 name[len+1] = 'x'+i;
3817 me[i] = ast_member::make(var->m_context, var, i, name);
3826 do { delete me[--i]; } while(i);
3830 static bool parse_function_body(parser_t *parser, ast_value *var)
3832 ast_block *block = nullptr;
3836 ast_expression *framenum = nullptr;
3837 ast_expression *nextthink = nullptr;
3838 /* None of the following have to be deleted */
3839 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3840 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3841 bool has_frame_think;
3845 has_frame_think = false;
3846 old = parser->function;
3848 if (var->m_flags & AST_FLAG_ALIAS) {
3849 parseerror(parser, "function aliases cannot have bodies");
3853 if (parser->gotos.size() || parser->labels.size()) {
3854 parseerror(parser, "gotos/labels leaking");
3858 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3859 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3860 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3866 if (parser->tok == '[') {
3867 /* got a frame definition: [ framenum, nextthink ]
3868 * this translates to:
3869 * self.frame = framenum;
3870 * self.nextthink = time + 0.1;
3871 * self.think = nextthink;
3873 nextthink = nullptr;
3875 fld_think = parser_find_field(parser, "think");
3876 fld_nextthink = parser_find_field(parser, "nextthink");
3877 fld_frame = parser_find_field(parser, "frame");
3878 if (!fld_think || !fld_nextthink || !fld_frame) {
3879 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3880 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3883 gbl_time = parser_find_global(parser, "time");
3884 gbl_self = parser_find_global(parser, "self");
3885 if (!gbl_time || !gbl_self) {
3886 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3887 parseerror(parser, "please declare the following globals: `time`, `self`");
3891 if (!parser_next(parser))
3894 framenum = parse_expression_leave(parser, true, false, false);
3896 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3899 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3900 ast_unref(framenum);
3901 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3905 if (parser->tok != ',') {
3906 ast_unref(framenum);
3907 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3908 parseerror(parser, "Got a %i\n", parser->tok);
3912 if (!parser_next(parser)) {
3913 ast_unref(framenum);
3917 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3919 /* qc allows the use of not-yet-declared functions here
3920 * - this automatically creates a prototype */
3921 ast_value *thinkfunc;
3922 ast_expression *functype = fld_think->m_next;
3924 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3925 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3926 ast_unref(framenum);
3927 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3930 thinkfunc->adoptType(*functype);
3932 if (!parser_next(parser)) {
3933 ast_unref(framenum);
3938 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3940 nextthink = thinkfunc;
3943 nextthink = parse_expression_leave(parser, true, false, false);
3945 ast_unref(framenum);
3946 parseerror(parser, "expected a think-function in [frame,think] notation");
3951 if (!ast_istype(nextthink, ast_value)) {
3952 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3956 if (retval && parser->tok != ']') {
3957 parseerror(parser, "expected closing `]` for [frame,think] notation");
3961 if (retval && !parser_next(parser)) {
3965 if (retval && parser->tok != '{') {
3966 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3971 ast_unref(nextthink);
3972 ast_unref(framenum);
3976 has_frame_think = true;
3979 block = new ast_block(parser_ctx(parser));
3981 parseerror(parser, "failed to allocate block");
3982 if (has_frame_think) {
3983 ast_unref(nextthink);
3984 ast_unref(framenum);
3989 if (has_frame_think) {
3990 if (!OPTS_FLAG(EMULATE_STATE)) {
3991 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
3992 if (!block->addExpr(state_op)) {
3993 parseerror(parser, "failed to generate state op for [frame,think]");
3994 ast_unref(nextthink);
3995 ast_unref(framenum);
4000 /* emulate OP_STATE in code: */
4002 ast_expression *self_frame;
4003 ast_expression *self_nextthink;
4004 ast_expression *self_think;
4005 ast_expression *time_plus_1;
4006 ast_store *store_frame;
4007 ast_store *store_nextthink;
4008 ast_store *store_think;
4010 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4012 ctx = parser_ctx(parser);
4013 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
4014 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4015 self_think = new ast_entfield(ctx, gbl_self, fld_think);
4017 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
4018 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4020 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4021 if (self_frame) delete self_frame;
4022 if (self_nextthink) delete self_nextthink;
4023 if (self_think) delete self_think;
4024 if (time_plus_1) delete time_plus_1;
4030 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4031 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4032 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4038 if (!store_nextthink) {
4039 delete self_nextthink;
4047 if (store_frame) delete store_frame;
4048 if (store_nextthink) delete store_nextthink;
4049 if (store_think) delete store_think;
4052 if (!block->addExpr(store_frame) ||
4053 !block->addExpr(store_nextthink) ||
4054 !block->addExpr(store_think))
4061 parseerror(parser, "failed to generate code for [frame,think]");
4062 ast_unref(nextthink);
4063 ast_unref(framenum);
4070 if (var->m_hasvalue) {
4071 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4072 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4076 func = var->m_constval.vfunc;
4079 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4084 func = ast_function::make(var->m_context, var->m_name, var);
4087 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4091 parser->functions.push_back(func);
4094 parser_enterblock(parser);
4096 for (auto &it : var->m_type_params) {
4100 if (it->m_vtype != TYPE_VECTOR &&
4101 (it->m_vtype != TYPE_FIELD ||
4102 it->m_next->m_vtype != TYPE_VECTOR))
4107 if (!create_vector_members(it.get(), me)) {
4112 for (e = 0; e < 3; ++e) {
4113 parser_addlocal(parser, me[e]->m_name, me[e]);
4114 block->collect(me[e]);
4118 if (var->m_argcounter && !func->m_argc) {
4119 ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT);
4120 parser_addlocal(parser, argc->m_name, argc);
4121 func->m_argc.reset(argc);
4124 if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4126 ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY);
4127 varargs->m_flags |= AST_FLAG_IS_VARARG;
4128 varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR);
4129 varargs->m_count = 0;
4130 util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str());
4131 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4136 util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str());
4137 if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4142 func->m_varargs.reset(varargs);
4143 func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4146 parser->function = func;
4147 if (!parse_block_into(parser, block)) {
4152 func->m_blocks.emplace_back(block);
4154 parser->function = old;
4155 if (!parser_leaveblock(parser))
4157 if (parser->variables.size() != PARSER_HT_LOCALS) {
4158 parseerror(parser, "internal error: local scopes left");
4162 if (parser->tok == ';')
4163 return parser_next(parser);
4164 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4165 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4169 (void)!parser_leaveblock(parser);
4170 parser->functions.pop_back();
4172 var->m_constval.vfunc = nullptr;
4175 parser->function = old;
4179 static ast_expression *array_accessor_split(
4184 ast_expression *left,
4185 ast_expression *right
4191 lex_ctx_t ctx = array->m_context;
4193 if (!left || !right) {
4194 if (left) delete left;
4195 if (right) delete right;
4199 cmp = new ast_binary(ctx, INSTR_LT,
4201 parser->m_fold.constgen_float(middle, false));
4205 parseerror(parser, "internal error: failed to create comparison for array setter");
4209 ifthen = new ast_ifthen(ctx, cmp, left, right);
4211 delete cmp; /* will delete left and right */
4212 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4219 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4221 lex_ctx_t ctx = array->m_context;
4223 if (from+1 == afterend) {
4224 /* set this value */
4227 ast_array_index *subscript;
4229 int assignop = type_store_instr[value->m_vtype];
4231 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4232 assignop = INSTR_STORE_V;
4234 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4238 st = new ast_store(ctx, assignop, subscript, value);
4244 block = new ast_block(ctx);
4250 if (!block->addExpr(st)) {
4255 ret = new ast_return(ctx, nullptr);
4261 if (!block->addExpr(ret)) {
4268 ast_expression *left, *right;
4269 size_t diff = afterend - from;
4270 size_t middle = from + diff/2;
4271 left = array_setter_node(parser, array, index, value, from, middle);
4272 right = array_setter_node(parser, array, index, value, middle, afterend);
4273 return array_accessor_split(parser, array, index, middle, left, right);
4277 static ast_expression *array_field_setter_node(
4286 lex_ctx_t ctx = array->m_context;
4288 if (from+1 == afterend) {
4289 /* set this value */
4292 ast_entfield *entfield;
4293 ast_array_index *subscript;
4295 int assignop = type_storep_instr[value->m_vtype];
4297 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4298 assignop = INSTR_STOREP_V;
4300 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4304 subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript);
4305 subscript->m_vtype = TYPE_FIELD;
4307 entfield = new ast_entfield(ctx, entity, subscript, subscript);
4313 st = new ast_store(ctx, assignop, entfield, value);
4319 block = new ast_block(ctx);
4325 if (!block->addExpr(st)) {
4330 ret = new ast_return(ctx, nullptr);
4336 if (!block->addExpr(ret)) {
4343 ast_expression *left, *right;
4344 size_t diff = afterend - from;
4345 size_t middle = from + diff/2;
4346 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4347 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4348 return array_accessor_split(parser, array, index, middle, left, right);
4352 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4354 lex_ctx_t ctx = array->m_context;
4356 if (from+1 == afterend) {
4358 ast_array_index *subscript;
4360 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4364 ret = new ast_return(ctx, subscript);
4372 ast_expression *left, *right;
4373 size_t diff = afterend - from;
4374 size_t middle = from + diff/2;
4375 left = array_getter_node(parser, array, index, from, middle);
4376 right = array_getter_node(parser, array, index, middle, afterend);
4377 return array_accessor_split(parser, array, index, middle, left, right);
4381 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4383 ast_function *func = nullptr;
4384 ast_value *fval = nullptr;
4385 ast_block *body = nullptr;
4387 fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION);
4389 parseerror(parser, "failed to create accessor function value");
4392 fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4394 func = ast_function::make(array->m_context, funcname, fval);
4397 parseerror(parser, "failed to create accessor function node");
4401 body = new ast_block(array->m_context);
4403 parseerror(parser, "failed to create block for array accessor");
4409 func->m_blocks.emplace_back(body);
4412 parser->accessors.push_back(fval);
4417 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4419 ast_value *index = nullptr;
4420 ast_value *value = nullptr;
4424 if (!ast_istype(array->m_next, ast_value)) {
4425 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4429 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4431 func = fval->m_constval.vfunc;
4432 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4434 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4435 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4437 if (!index || !value) {
4438 parseerror(parser, "failed to create locals for array accessor");
4441 value->m_name = "value"; // not important
4442 fval->m_type_params.emplace_back(index);
4443 fval->m_type_params.emplace_back(value);
4445 array->m_setter = fval;
4448 if (index) delete index;
4449 if (value) delete value;
4455 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4457 ast_expression *root = nullptr;
4458 root = array_setter_node(parser, array,
4459 array->m_setter->m_type_params[0].get(),
4460 array->m_setter->m_type_params[1].get(),
4463 parseerror(parser, "failed to build accessor search tree");
4466 if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4473 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4475 if (!parser_create_array_setter_proto(parser, array, funcname))
4477 return parser_create_array_setter_impl(parser, array);
4480 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4482 ast_expression *root = nullptr;
4483 ast_value *entity = nullptr;
4484 ast_value *index = nullptr;
4485 ast_value *value = nullptr;
4489 if (!ast_istype(array->m_next, ast_value)) {
4490 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4494 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4496 func = fval->m_constval.vfunc;
4497 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4499 entity = new ast_value(array->m_context, "entity", TYPE_ENTITY);
4500 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4501 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4502 if (!entity || !index || !value) {
4503 parseerror(parser, "failed to create locals for array accessor");
4506 value->m_name = "value"; // not important
4507 fval->m_type_params.emplace_back(entity);
4508 fval->m_type_params.emplace_back(index);
4509 fval->m_type_params.emplace_back(value);
4511 root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4513 parseerror(parser, "failed to build accessor search tree");
4517 array->m_setter = fval;
4518 return func->m_blocks[0].get()->addExpr(root);
4520 if (entity) delete entity;
4521 if (index) delete index;
4522 if (value) delete value;
4523 if (root) delete root;
4529 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4531 ast_value *index = nullptr;
4535 /* NOTE: checking array->m_next rather than elemtype since
4536 * for fields elemtype is a temporary fieldtype.
4538 if (!ast_istype(array->m_next, ast_value)) {
4539 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4543 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4545 func = fval->m_constval.vfunc;
4546 fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype);
4548 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4551 parseerror(parser, "failed to create locals for array accessor");
4554 fval->m_type_params.emplace_back(index);
4556 array->m_getter = fval;
4559 if (index) delete index;
4565 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4567 ast_expression *root = nullptr;
4569 root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count);
4571 parseerror(parser, "failed to build accessor search tree");
4574 if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4581 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4583 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4585 return parser_create_array_getter_impl(parser, array);
4588 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4590 lex_ctx_t ctx = parser_ctx(parser);
4591 std::vector<std::unique_ptr<ast_value>> params;
4594 bool variadic = false;
4595 ast_value *varparam = nullptr;
4596 char *argcounter = nullptr;
4598 /* for the sake of less code we parse-in in this function */
4599 if (!parser_next(parser)) {
4601 parseerror(parser, "expected parameter list");
4605 /* parse variables until we hit a closing paren */
4606 while (parser->tok != ')') {
4607 bool is_varargs = false;
4610 /* there must be commas between them */
4611 if (parser->tok != ',') {
4612 parseerror(parser, "expected comma or end of parameter list");
4615 if (!parser_next(parser)) {
4616 parseerror(parser, "expected parameter");
4622 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4623 if (!param && !is_varargs)
4626 /* '...' indicates a varargs function */
4628 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4629 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4632 if (parser->tok == TOKEN_IDENT) {
4633 argcounter = util_strdup(parser_tokval(parser));
4634 if (!parser_next(parser) || parser->tok != ')') {
4635 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4640 params.emplace_back(param);
4641 if (param->m_vtype >= TYPE_VARIANT) {
4642 char tname[1024]; /* typename is reserved in C++ */
4643 ast_type_to_string(param, tname, sizeof(tname));
4644 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4647 /* type-restricted varargs */
4648 if (parser->tok == TOKEN_DOTS) {
4650 varparam = params.back().release();
4652 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4653 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4656 if (parser->tok == TOKEN_IDENT) {
4657 argcounter = util_strdup(parser_tokval(parser));
4658 param->m_name = argcounter;
4659 if (!parser_next(parser) || parser->tok != ')') {
4660 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4665 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4666 parseerror(parser, "parameter name omitted");
4672 if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4676 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4677 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4680 if (!parser_next(parser)) {
4681 parseerror(parser, "parse error after typename");
4685 /* now turn 'var' into a function type */
4686 fval = new ast_value(ctx, "<type()>", TYPE_FUNCTION);
4689 fval->m_flags |= AST_FLAG_VARIADIC;
4692 var->m_type_params = move(params);
4693 var->m_varparam = varparam;
4694 var->m_argcounter = argcounter;
4707 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4709 ast_expression *cexp;
4710 ast_value *cval, *tmp;
4713 ctx = parser_ctx(parser);
4715 if (!parser_next(parser)) {
4717 parseerror(parser, "expected array-size");
4721 if (parser->tok != ']') {
4722 cexp = parse_expression_leave(parser, true, false, false);
4724 if (!cexp || !ast_istype(cexp, ast_value)) {
4728 parseerror(parser, "expected array-size as constant positive integer");
4731 cval = (ast_value*)cexp;
4738 tmp = new ast_value(ctx, "<type[]>", TYPE_ARRAY);
4743 if (cval->m_vtype == TYPE_INTEGER)
4744 tmp->m_count = cval->m_constval.vint;
4745 else if (cval->m_vtype == TYPE_FLOAT)
4746 tmp->m_count = cval->m_constval.vfloat;
4750 parseerror(parser, "array-size must be a positive integer constant");
4757 var->m_flags |= AST_FLAG_ARRAY_INIT;
4760 if (parser->tok != ']') {
4762 parseerror(parser, "expected ']' after array-size");
4765 if (!parser_next(parser)) {
4767 parseerror(parser, "error after parsing array size");
4773 /* Parse a complete typename.
4774 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4775 * but when parsing variables separated by comma
4776 * 'storebase' should point to where the base-type should be kept.
4777 * The base type makes up every bit of type information which comes *before* the
4780 * NOTE: The value must either be named, have a nullptr name, or a name starting
4781 * with '<'. In the first case, this will be the actual variable or type
4782 * name, in the other cases it is assumed that the name will appear
4783 * later, and an error is generated otherwise.
4785 * The following will be parsed in its entirety:
4787 * The 'basetype' in this case is 'void()'
4788 * and if there's a comma after it, say:
4790 * then the type-information 'void()' can be stored in 'storebase'
4792 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4794 ast_value *var, *tmp;
4797 const char *name = nullptr;
4798 bool isfield = false;
4799 bool wasarray = false;
4800 size_t morefields = 0;
4802 bool vararg = (parser->tok == TOKEN_DOTS);
4804 ctx = parser_ctx(parser);
4806 /* types may start with a dot */
4807 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4809 if (parser->tok == TOKEN_DOTS)
4811 /* if we parsed a dot we need a typename now */
4812 if (!parser_next(parser)) {
4813 parseerror(parser, "expected typename for field definition");
4817 /* Further dots are handled seperately because they won't be part of the
4821 if (parser->tok == '.')
4823 else if (parser->tok == TOKEN_DOTS)
4828 if (!parser_next(parser)) {
4829 parseerror(parser, "expected typename for field definition");
4834 if (parser->tok == TOKEN_IDENT)
4835 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4836 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4837 if (vararg && is_vararg) {
4841 parseerror(parser, "expected typename");
4845 /* generate the basic type value */
4846 if (cached_typedef) {
4847 var = new ast_value(ast_copy_type, *cached_typedef);
4848 var->m_name = "<type(from_def)>";
4850 var = new ast_value(ctx, "<type>", parser_token(parser)->constval.t);
4852 for (; morefields; --morefields) {
4853 tmp = new ast_value(ctx, "<.type>", TYPE_FIELD);
4858 /* do not yet turn into a field - remember:
4859 * .void() foo; is a field too
4860 * .void()() foo; is a function
4864 if (!parser_next(parser)) {
4866 parseerror(parser, "parse error after typename");
4870 /* an opening paren now starts the parameter-list of a function
4871 * this is where original-QC has parameter lists.
4872 * We allow a single parameter list here.
4873 * Much like fteqcc we don't allow `float()() x`
4875 if (parser->tok == '(') {
4876 var = parse_parameter_list(parser, var);
4881 /* store the base if requested */
4883 *storebase = new ast_value(ast_copy_type, *var);
4885 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4886 tmp->m_next = *storebase;
4891 /* there may be a name now */
4892 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4893 if (!strcmp(parser_tokval(parser), "break"))
4894 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4895 else if (parser->tok == TOKEN_KEYWORD)
4898 name = util_strdup(parser_tokval(parser));
4901 if (!parser_next(parser)) {
4904 parseerror(parser, "error after variable or field declaration");
4910 /* now this may be an array */
4911 if (parser->tok == '[') {
4913 var = parse_arraysize(parser, var);
4915 if (name) mem_d(name);
4920 /* This is the point where we can turn it into a field */
4922 /* turn it into a field if desired */
4923 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4928 /* now there may be function parens again */
4929 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4930 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4931 if (parser->tok == '(' && wasarray)
4932 parseerror(parser, "arrays as part of a return type is not supported");
4933 while (parser->tok == '(') {
4934 var = parse_parameter_list(parser, var);
4936 if (name) mem_d(name);
4941 /* finally name it */
4944 // free the name, ast_value_set_name duplicates
4951 static bool parse_typedef(parser_t *parser)
4953 ast_value *typevar, *oldtype;
4954 ast_expression *old;
4956 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4961 // while parsing types, the ast_value's get named '<something>'
4962 if (!typevar->m_name.length() || typevar->m_name[0] == '<') {
4963 parseerror(parser, "missing name in typedef");
4968 if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4969 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4970 " -> `%s` has been declared here: %s:%i",
4971 typevar->m_name, old->m_context.file, old->m_context.line);
4976 if ( (oldtype = parser_find_typedef(parser, typevar->m_name, parser->_blocktypedefs.back())) ) {
4977 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4978 typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
4983 parser->_typedefs.emplace_back(typevar);
4984 util_htset(parser->typedefs.back(), typevar->m_name.c_str(), typevar);
4986 if (parser->tok != ';') {
4987 parseerror(parser, "expected semicolon after typedef");
4990 if (!parser_next(parser)) {
4991 parseerror(parser, "parse error after typedef");
4998 static const char *cvq_to_str(int cvq) {
5000 case CV_NONE: return "none";
5001 case CV_VAR: return "`var`";
5002 case CV_CONST: return "`const`";
5003 default: return "<INVALID>";
5007 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5010 if (proto->m_cvq != var->m_cvq) {
5011 if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
5012 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5013 parser->tok == '='))
5015 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5016 "`%s` declared with different qualifiers: %s\n"
5017 " -> previous declaration here: %s:%i uses %s",
5018 var->m_name, cvq_to_str(var->m_cvq),
5019 proto->m_context.file, proto->m_context.line,
5020 cvq_to_str(proto->m_cvq));
5023 av = (var ->m_flags & AST_FLAG_NORETURN);
5024 ao = (proto->m_flags & AST_FLAG_NORETURN);
5026 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5027 "`%s` declared with different attributes%s\n"
5028 " -> previous declaration here: %s:%i",
5029 var->m_name, (av ? ": noreturn" : ""),
5030 proto->m_context.file, proto->m_context.line,
5031 (ao ? ": noreturn" : ""));
5036 static bool create_array_accessors(parser_t *parser, ast_value *var)
5039 util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str());
5040 if (!parser_create_array_setter(parser, var, name))
5042 util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str());
5043 if (!parser_create_array_getter(parser, var, var->m_next, name))
5048 static bool parse_array(parser_t *parser, ast_value *array)
5051 if (array->m_initlist.size()) {
5052 parseerror(parser, "array already initialized elsewhere");
5055 if (!parser_next(parser)) {
5056 parseerror(parser, "parse error in array initializer");
5060 while (parser->tok != '}') {
5061 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5064 if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5066 parseerror(parser, "initializing element must be a compile time constant");
5069 array->m_initlist.push_back(v->m_constval);
5070 if (v->m_vtype == TYPE_STRING) {
5071 array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5075 if (parser->tok == '}')
5077 if (parser->tok != ',' || !parser_next(parser)) {
5078 parseerror(parser, "expected comma or '}' in element list");
5082 if (!parser_next(parser) || parser->tok != ';') {
5083 parseerror(parser, "expected semicolon after initializer, got %s");
5087 if (!parser_next(parser)) {
5088 parseerror(parser, "parse error after initializer");
5093 if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5094 if (array->m_count != (size_t)-1) {
5095 parseerror(parser, "array `%s' has already been initialized with %u elements",
5096 array->m_name, (unsigned)array->m_count);
5098 array->m_count = array->m_initlist.size();
5099 if (!create_array_accessors(parser, array))
5105 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)
5109 ast_expression *old;
5113 ast_value *basetype = nullptr;
5115 bool isparam = false;
5116 bool isvector = false;
5117 bool cleanvar = true;
5118 bool wasarray = false;
5120 ast_member *me[3] = { nullptr, nullptr, nullptr };
5121 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5123 if (!localblock && is_static)
5124 parseerror(parser, "`static` qualifier is not supported in global scope");
5126 /* get the first complete variable */
5127 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5134 /* while parsing types, the ast_value's get named '<something>' */
5135 if (!var->m_name.length() || var->m_name[0] == '<') {
5136 parseerror(parser, "declaration does not declare anything");
5146 /* Part 0: finish the type */
5147 if (parser->tok == '(') {
5148 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5149 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5150 var = parse_parameter_list(parser, var);
5156 /* we only allow 1-dimensional arrays */
5157 if (parser->tok == '[') {
5159 var = parse_arraysize(parser, var);
5165 if (parser->tok == '(' && wasarray) {
5166 parseerror(parser, "arrays as part of a return type is not supported");
5167 /* we'll still parse the type completely for now */
5169 /* for functions returning functions */
5170 while (parser->tok == '(') {
5171 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5172 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5173 var = parse_parameter_list(parser, var);
5180 var->m_cvq = qualifier;
5181 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5182 var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5183 var->m_flags |= qflags;
5186 * store the vstring back to var for alias and
5187 * deprecation messages.
5189 if (var->m_flags & AST_FLAG_DEPRECATED ||
5190 var->m_flags & AST_FLAG_ALIAS)
5191 var->m_desc = vstring;
5193 if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5194 parseerror(parser, "function aliases cannot be forward declared");
5201 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5202 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5203 * is then filled with the previous definition and the parameter-names replaced.
5205 if (var->m_name == "nil") {
5206 if (OPTS_FLAG(UNTYPED_NIL)) {
5207 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5208 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5210 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5213 /* Deal with end_sys_ vars */
5215 if (var->m_name == "end_sys_globals") {
5216 var->m_flags |= AST_FLAG_NOREF;
5217 parser->crc_globals = parser->globals.size();
5220 else if (var->m_name == "end_sys_fields") {
5221 var->m_flags |= AST_FLAG_NOREF;
5222 parser->crc_fields = parser->fields.size();
5225 if (was_end && var->m_vtype == TYPE_FIELD) {
5226 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5227 "global '%s' hint should not be a field",
5228 parser_tokval(parser)))
5235 if (!nofields && var->m_vtype == TYPE_FIELD)
5237 /* deal with field declarations */
5238 old = parser_find_field(parser, var->m_name);
5240 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5241 var->m_name, old->m_context.file, (int)old->m_context.line))
5250 parseerror(parser, "field `%s` already declared here: %s:%i",
5251 var->m_name, old->m_context.file, old->m_context.line);
5256 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5257 (old = parser_find_global(parser, var->m_name)))
5259 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5260 parseerror(parser, "field `%s` already declared here: %s:%i",
5261 var->m_name, old->m_context.file, old->m_context.line);
5268 /* deal with other globals */
5269 old = parser_find_global(parser, var->m_name);
5270 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5272 /* This is a function which had a prototype */
5273 if (!ast_istype(old, ast_value)) {
5274 parseerror(parser, "internal error: prototype is not an ast_value");
5278 proto = (ast_value*)old;
5279 proto->m_desc = var->m_desc;
5280 if (!proto->compareType(*var)) {
5281 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5283 proto->m_context.file, proto->m_context.line);
5287 /* we need the new parameter-names */
5288 for (i = 0; i < proto->m_type_params.size(); ++i)
5289 proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name;
5290 if (!parser_check_qualifiers(parser, var, proto)) {
5295 proto->m_flags |= var->m_flags;
5303 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5304 "global `%s` already declared here: %s:%i",
5305 var->m_name, old->m_context.file, old->m_context.line))
5310 if (old->m_flags & AST_FLAG_FINAL_DECL) {
5311 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5312 var->m_name, old->m_context.file, old->m_context.line);
5316 proto = (ast_value*)old;
5317 if (!ast_istype(old, ast_value)) {
5318 parseerror(parser, "internal error: not an ast_value");
5323 if (!parser_check_qualifiers(parser, var, proto)) {
5328 proto->m_flags |= var->m_flags;
5329 /* copy the context for finals,
5330 * so the error can show where it was actually made 'final'
5332 if (proto->m_flags & AST_FLAG_FINAL_DECL)
5333 old->m_context = var->m_context;
5337 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5338 (old = parser_find_field(parser, var->m_name)))
5340 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5341 parseerror(parser, "global `%s` already declared here: %s:%i",
5342 var->m_name, old->m_context.file, old->m_context.line);
5349 else /* it's not a global */
5351 old = parser_find_local(parser, var->m_name, parser->variables.size()-1, &isparam);
5352 if (old && !isparam) {
5353 parseerror(parser, "local `%s` already declared here: %s:%i",
5354 var->m_name, old->m_context.file, (int)old->m_context.line);
5358 /* doing this here as the above is just for a single scope */
5359 old = parser_find_local(parser, var->m_name, 0, &isparam);
5360 if (old && isparam) {
5361 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5362 "local `%s` is shadowing a parameter", var->m_name))
5364 parseerror(parser, "local `%s` already declared here: %s:%i",
5365 var->m_name, old->m_context.file, (int)old->m_context.line);
5369 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5371 if (ast_istype(old, ast_value))
5372 var = proto = (ast_value*)old;
5381 if (noref || parser->noref)
5382 var->m_flags |= AST_FLAG_NOREF;
5385 * Create the global/local, and deal with vector types.
5388 if (var->m_vtype == TYPE_VECTOR)
5390 else if (var->m_vtype == TYPE_FIELD &&
5391 var->m_next->m_vtype == TYPE_VECTOR)
5395 if (!create_vector_members(var, me)) {
5402 /* deal with global variables, fields, functions */
5403 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5404 var->m_isfield = true;
5405 parser->fields.push_back(var);
5406 util_htset(parser->htfields, var->m_name.c_str(), var);
5408 for (i = 0; i < 3; ++i) {
5409 parser->fields.push_back(me[i]);
5410 util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]);
5415 if (!(var->m_flags & AST_FLAG_ALIAS)) {
5416 parser_addglobal(parser, var->m_name, var);
5418 for (i = 0; i < 3; ++i) {
5419 parser_addglobal(parser, me[i]->m_name.c_str(), me[i]);
5423 ast_expression *find = parser_find_global(parser, var->m_desc);
5426 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5430 if (!var->compareType(*find)) {
5434 ast_type_to_string(find, ty1, sizeof(ty1));
5435 ast_type_to_string(var, ty2, sizeof(ty2));
5437 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5438 ty1, ty2, var->m_name
5443 util_htset(parser->aliases, var->m_name.c_str(), find);
5445 /* generate aliases for vector components */
5449 util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str());
5450 util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str());
5451 util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str());
5453 util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0]));
5454 util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1]));
5455 util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2]));
5465 // a static adds itself to be generated like any other global
5466 // but is added to the local namespace instead
5467 std::string defname;
5471 defname = parser->function->m_name;
5472 defname.append(2, ':');
5474 // remember the length up to here
5475 prefix_len = defname.length();
5477 // Add it to the local scope
5478 util_htset(parser->variables.back(), var->m_name.c_str(), (void*)var);
5480 // now rename the global
5481 defname.append(var->m_name);
5482 // if a variable of that name already existed, add the
5484 // The counter is incremented either way.
5485 sn_size = parser->function->m_static_names.size();
5486 for (sn = 0; sn != sn_size; ++sn) {
5487 if (parser->function->m_static_names[sn] == var->m_name.c_str())
5490 if (sn != sn_size) {
5491 char *num = nullptr;
5492 int len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5493 defname.append(num, 0, len);
5497 parser->function->m_static_names.emplace_back(var->m_name);
5498 parser->function->m_static_count++;
5499 var->m_name = defname;
5501 // push it to the to-be-generated globals
5502 parser->globals.push_back(var);
5504 // same game for the vector members
5506 defname.erase(prefix_len);
5507 for (i = 0; i < 3; ++i) {
5508 util_htset(parser->variables.back(), me[i]->m_name.c_str(), (void*)(me[i]));
5509 me[i]->m_name = defname + me[i]->m_name;
5510 parser->globals.push_back(me[i]);
5514 localblock->m_locals.push_back(var);
5515 parser_addlocal(parser, var->m_name, var);
5517 for (i = 0; i < 3; ++i) {
5518 parser_addlocal(parser, me[i]->m_name, me[i]);
5519 localblock->collect(me[i]);
5525 memcpy(last_me, me, sizeof(me));
5526 me[0] = me[1] = me[2] = nullptr;
5531 if (var->m_vtype == TYPE_ARRAY) {
5532 if (var->m_count != (size_t)-1) {
5533 if (!create_array_accessors(parser, var))
5537 else if (!localblock && !nofields &&
5538 var->m_vtype == TYPE_FIELD &&
5539 var->m_next->m_vtype == TYPE_ARRAY)
5542 ast_expression *telem;
5544 ast_value *array = (ast_value*)var->m_next;
5546 if (!ast_istype(var->m_next, ast_value)) {
5547 parseerror(parser, "internal error: field element type must be an ast_value");
5551 util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str());
5552 if (!parser_create_array_field_setter(parser, array, name))
5555 telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next);
5556 tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD);
5557 tfield->m_next = telem;
5558 util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str());
5559 if (!parser_create_array_getter(parser, array, tfield, name)) {
5567 if (parser->tok == ';') {
5569 if (!parser_next(parser)) {
5570 parseerror(parser, "error after variable declaration");
5576 if (parser->tok == ',')
5580 if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5583 parseerror(parser, "missing comma or semicolon while parsing variables");
5587 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5588 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5589 "initializing expression turns variable `%s` into a constant in this standard",
5596 if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) {
5597 if (parser->tok != '=') {
5598 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5602 if (!parser_next(parser)) {
5603 parseerror(parser, "error parsing initializer");
5607 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5608 parseerror(parser, "expected '=' before function body in this standard");
5611 if (parser->tok == '#') {
5612 ast_function *func = nullptr;
5613 ast_value *number = nullptr;
5619 parseerror(parser, "cannot declare builtins within functions");
5622 if (var->m_vtype != TYPE_FUNCTION) {
5623 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5626 if (!parser_next(parser)) {
5627 parseerror(parser, "expected builtin number");
5631 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5632 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5634 parseerror(parser, "builtin number expected");
5637 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5640 parseerror(parser, "builtin number must be a compile time constant");
5643 if (number->m_vtype == TYPE_INTEGER)
5644 builtin_num = number->m_constval.vint;
5645 else if (number->m_vtype == TYPE_FLOAT)
5646 builtin_num = number->m_constval.vfloat;
5649 parseerror(parser, "builtin number must be an integer constant");
5654 fractional = modff(builtin_num, &integral);
5655 if (builtin_num < 0 || fractional != 0) {
5656 parseerror(parser, "builtin number must be an integer greater than zero");
5660 /* we only want the integral part anyways */
5661 builtin_num = integral;
5662 } else if (parser->tok == TOKEN_INTCONST) {
5663 builtin_num = parser_token(parser)->constval.i;
5665 parseerror(parser, "builtin number must be a compile time constant");
5669 if (var->m_hasvalue) {
5670 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5671 "builtin `%s` has already been defined\n"
5672 " -> previous declaration here: %s:%i",
5673 var->m_name, var->m_context.file, (int)var->m_context.line);
5677 func = ast_function::make(var->m_context, var->m_name, var);
5679 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5682 parser->functions.push_back(func);
5684 func->m_builtin = -builtin_num-1;
5687 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5688 ? (parser->tok != ',' && parser->tok != ';')
5689 : (!parser_next(parser)))
5691 parseerror(parser, "expected comma or semicolon");
5693 var->m_constval.vfunc = nullptr;
5697 else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5700 /* Note that fteqcc and most others don't even *have*
5701 * local arrays, so this is not a high priority.
5703 parseerror(parser, "TODO: initializers for local arrays");
5707 var->m_hasvalue = true;
5708 if (!parse_array(parser, var))
5711 else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5714 parseerror(parser, "cannot declare functions within functions");
5719 proto->m_context = parser_ctx(parser);
5721 if (!parse_function_body(parser, var))
5724 for (auto &it : parser->gotos)
5725 parseerror(parser, "undefined label: `%s`", it->m_name);
5726 parser->gotos.clear();
5727 parser->labels.clear();
5730 ast_expression *cexp;
5732 bool folded_const = false;
5734 cexp = parse_expression_leave(parser, true, false, false);
5737 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5739 /* deal with foldable constants: */
5741 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5743 /* remove it from the current locals */
5745 for (i = 0; i < 3; ++i) {
5746 parser->_locals.pop_back();
5747 localblock->m_collect.pop_back();
5750 /* do sanity checking, this function really needs refactoring */
5751 if (parser->_locals.back() != var)
5752 parseerror(parser, "internal error: unexpected change in local variable handling");
5754 parser->_locals.pop_back();
5755 if (localblock->m_locals.back() != var)
5756 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5758 localblock->m_locals.pop_back();
5759 /* push it to the to-be-generated globals */
5760 parser->globals.push_back(var);
5762 for (i = 0; i < 3; ++i)
5763 parser->globals.push_back(last_me[i]);
5764 folded_const = true;
5767 if (folded_const || !localblock || is_static) {
5768 if (cval != parser->nil &&
5769 (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5772 parseerror(parser, "initializer is non constant");
5777 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5778 qualifier != CV_VAR)
5780 var->m_cvq = CV_CONST;
5782 if (cval == parser->nil)
5784 var->m_flags |= AST_FLAG_INITIALIZED;
5785 var->m_flags |= AST_FLAG_NOREF;
5789 var->m_hasvalue = true;
5790 if (cval->m_vtype == TYPE_STRING)
5791 var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5792 else if (cval->m_vtype == TYPE_FIELD)
5793 var->m_constval.vfield = cval;
5795 memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5803 var->m_cvq = CV_NONE;
5804 sy.out.push_back(syexp(var->m_context, var));
5805 sy.out.push_back(syexp(cexp->m_context, cexp));
5806 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5807 if (!parser_sy_apply_operator(parser, &sy))
5810 if (sy.out.size() != 1 && sy.ops.size() != 0)
5811 parseerror(parser, "internal error: leaked operands");
5812 if (!localblock->addExpr(sy.out[0].out))
5817 /* a constant initialized to an inexact value should be marked inexact:
5818 * const float x = <inexact>; should propagate the inexact flag
5820 if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5821 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5822 var->m_inexact = cval->m_inexact;
5827 if (parser->tok == ',') {
5828 if (!parser_next(parser)) {
5829 parseerror(parser, "expected another variable");
5833 if (parser->tok != TOKEN_IDENT) {
5834 parseerror(parser, "expected another variable");
5837 var = new ast_value(ast_copy_type, *basetype);
5839 var->m_name = parser_tokval(parser);
5840 if (!parser_next(parser)) {
5841 parseerror(parser, "error parsing variable declaration");
5847 if (parser->tok != ';') {
5848 parseerror(parser, "missing semicolon after variables");
5852 if (!parser_next(parser)) {
5853 parseerror(parser, "parse error after variable declaration");
5861 if (cleanvar && var)
5868 if (cleanvar && var)
5876 static bool parser_global_statement(parser_t *parser)
5880 bool is_static = false;
5881 uint32_t qflags = 0;
5882 ast_value *istype = nullptr;
5883 char *vstring = nullptr;
5885 if (parser->tok == TOKEN_IDENT)
5886 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5888 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5890 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5892 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5894 if (cvq == CV_WRONG)
5896 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5898 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5900 return parse_enum(parser);
5902 else if (parser->tok == TOKEN_KEYWORD)
5904 if (!strcmp(parser_tokval(parser), "typedef")) {
5905 if (!parser_next(parser)) {
5906 parseerror(parser, "expected type definition after 'typedef'");
5909 return parse_typedef(parser);
5911 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5914 else if (parser->tok == '#')
5916 return parse_pragma(parser);
5918 else if (parser->tok == '$')
5920 if (!parser_next(parser)) {
5921 parseerror(parser, "parse error");
5927 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5933 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5935 return util_crc16(old, str, strlen(str));
5938 static void progdefs_crc_file(const char *str)
5940 /* write to progdefs.h here */
5944 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5946 old = progdefs_crc_sum(old, str);
5947 progdefs_crc_file(str);
5951 static void generate_checksum(parser_t *parser, ir_builder *ir)
5953 uint16_t crc = 0xFFFF;
5957 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5958 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5960 progdefs_crc_file("\tint\tpad;\n");
5961 progdefs_crc_file("\tint\tofs_return[3];\n");
5962 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5963 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5964 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5965 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5966 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5967 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5968 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5969 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5971 for (i = 0; i < parser->crc_globals; ++i) {
5972 if (!ast_istype(parser->globals[i], ast_value))
5974 value = (ast_value*)(parser->globals[i]);
5975 switch (value->m_vtype) {
5976 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5977 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5978 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5979 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5981 crc = progdefs_crc_both(crc, "\tint\t");
5984 crc = progdefs_crc_both(crc, value->m_name.c_str());
5985 crc = progdefs_crc_both(crc, ";\n");
5987 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5988 for (i = 0; i < parser->crc_fields; ++i) {
5989 if (!ast_istype(parser->fields[i], ast_value))
5991 value = (ast_value*)(parser->fields[i]);
5992 switch (value->m_next->m_vtype) {
5993 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5994 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5995 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5996 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5998 crc = progdefs_crc_both(crc, "\tint\t");
6001 crc = progdefs_crc_both(crc, value->m_name.c_str());
6002 crc = progdefs_crc_both(crc, ";\n");
6004 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6005 ir->m_code->crc = crc;
6008 parser_t::parser_t()
6011 , ast_cleaned(false)
6016 , aliases(util_htnew(PARSER_HT_SIZE))
6017 , htfields(util_htnew(PARSER_HT_SIZE))
6018 , htglobals(util_htnew(PARSER_HT_SIZE))
6019 , assign_op(nullptr)
6021 , max_param_count(1)
6022 // finish initializing the rest of the parser before initializing
6023 // m_fold and m_intrin with the parser passed along
6027 variables.push_back(htfields);
6028 variables.push_back(htglobals);
6029 typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
6030 _blocktypedefs.push_back(0);
6032 lex_ctx_t empty_ctx;
6033 empty_ctx.file = "<internal>";
6035 empty_ctx.column = 0;
6036 nil = new ast_value(empty_ctx, "nil", TYPE_NIL);
6037 nil->m_cvq = CV_CONST;
6038 if (OPTS_FLAG(UNTYPED_NIL))
6039 util_htset(htglobals, "nil", (void*)nil);
6041 const_vec[0] = new ast_value(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6042 const_vec[1] = new ast_value(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6043 const_vec[2] = new ast_value(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6045 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6046 reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING);
6047 reserved_version->m_cvq = CV_CONST;
6048 reserved_version->m_hasvalue = true;
6049 reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6050 reserved_version->m_flags |= AST_FLAG_NOREF;
6051 reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6053 reserved_version = nullptr;
6056 m_fold = fold(this);
6057 m_intrin = intrin(this);
6060 parser_t::~parser_t()
6065 parser_t *parser_create()
6070 parser = new parser_t;
6074 for (i = 0; i < operator_count; ++i) {
6075 if (operators[i].id == opid1('=')) {
6076 parser->assign_op = operators+i;
6080 if (!parser->assign_op) {
6081 con_err("internal error: initializing parser: failed to find assign operator\n");
6089 static bool parser_compile(parser_t *parser)
6091 /* initial lexer/parser state */
6092 parser->lex->flags.noops = true;
6094 if (parser_next(parser))
6096 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6098 if (!parser_global_statement(parser)) {
6099 if (parser->tok == TOKEN_EOF)
6100 parseerror(parser, "unexpected end of file");
6101 else if (compile_errors)
6102 parseerror(parser, "there have been errors, bailing out");
6103 lex_close(parser->lex);
6104 parser->lex = nullptr;
6109 parseerror(parser, "parse error");
6110 lex_close(parser->lex);
6111 parser->lex = nullptr;
6115 lex_close(parser->lex);
6116 parser->lex = nullptr;
6118 return !compile_errors;
6121 bool parser_compile_file(parser_t *parser, const char *filename)
6123 parser->lex = lex_open(filename);
6125 con_err("failed to open file \"%s\"\n", filename);
6128 return parser_compile(parser);
6131 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6133 parser->lex = lex_open_string(str, len, name);
6135 con_err("failed to create lexer for string \"%s\"\n", name);
6138 return parser_compile(parser);
6141 void parser_t::remove_ast()
6146 for (auto &it : accessors) {
6147 delete it->m_constval.vfunc;
6148 it->m_constval.vfunc = nullptr;
6151 for (auto &it : functions) delete it;
6152 for (auto &it : globals) delete it;
6153 for (auto &it : fields) delete it;
6155 for (auto &it : variables) util_htdel(it);
6157 _blocklocals.clear();
6161 for (auto &it : typedefs) util_htdel(it);
6163 _blocktypedefs.clear();
6169 delete const_vec[0];
6170 delete const_vec[1];
6171 delete const_vec[2];
6173 if (reserved_version)
6174 delete reserved_version;
6176 util_htdel(aliases);
6179 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6180 ast_expression *expr;
6184 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6188 for (auto &it : parser->functions) {
6189 if (it->m_name == "coverage") {
6195 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6196 con_out("coverage support requested but no coverage() builtin declared\n");
6203 cov = func->m_function_type;
6206 if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) {
6208 ast_type_to_string(expr, ty, sizeof(ty));
6209 con_out("invalid type for coverage(): %s\n", ty);
6214 ir->m_coverage_func = func->m_ir_func->m_value;
6218 bool parser_finish(parser_t *parser, const char *output)
6223 if (compile_errors) {
6224 con_out("*** there were compile errors\n");
6228 ir = new ir_builder("gmqcc_out");
6230 con_out("failed to allocate builder\n");
6234 for (auto &it : parser->fields) {
6236 if (!ast_istype(it, ast_value))
6238 ast_value *field = (ast_value*)it;
6239 hasvalue = field->m_hasvalue;
6240 field->m_hasvalue = false;
6241 if (!reinterpret_cast<ast_value*>(field)->generateGlobal(ir, true)) {
6242 con_out("failed to generate field %s\n", field->m_name.c_str());
6248 ast_expression *subtype;
6249 field->m_hasvalue = true;
6250 subtype = field->m_next;
6251 ifld = ir->createField(field->m_name, subtype->m_vtype);
6252 if (subtype->m_vtype == TYPE_FIELD)
6253 ifld->m_fieldtype = subtype->m_next->m_vtype;
6254 else if (subtype->m_vtype == TYPE_FUNCTION)
6255 ifld->m_outtype = subtype->m_next->m_vtype;
6256 (void)!field->m_ir_v->setField(ifld);
6259 for (auto &it : parser->globals) {
6261 if (!ast_istype(it, ast_value))
6263 asvalue = (ast_value*)it;
6264 if (!(asvalue->m_flags & AST_FLAG_NOREF) && asvalue->m_cvq != CV_CONST && asvalue->m_vtype != TYPE_FUNCTION) {
6265 retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE,
6266 "unused global: `%s`", asvalue->m_name);
6268 if (!asvalue->generateGlobal(ir, false)) {
6269 con_out("failed to generate global %s\n", asvalue->m_name.c_str());
6274 /* Build function vararg accessor ast tree now before generating
6275 * immediates, because the accessors may add new immediates
6277 for (auto &f : parser->functions) {
6279 if (parser->max_param_count > f->m_function_type->m_type_params.size()) {
6280 f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size();
6281 if (!parser_create_array_setter_impl(parser, f->m_varargs.get())) {
6282 con_out("failed to generate vararg setter for %s\n", f->m_name.c_str());
6286 if (!parser_create_array_getter_impl(parser, f->m_varargs.get())) {
6287 con_out("failed to generate vararg getter for %s\n", f->m_name.c_str());
6292 f->m_varargs = nullptr;
6296 /* Now we can generate immediates */
6297 if (!parser->m_fold.generate(ir))
6300 /* before generating any functions we need to set the coverage_func */
6301 if (!parser_set_coverage_func(parser, ir))
6303 for (auto &it : parser->globals) {
6304 if (!ast_istype(it, ast_value))
6306 ast_value *asvalue = (ast_value*)it;
6307 if (!(asvalue->m_flags & AST_FLAG_INITIALIZED))
6309 if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue)
6310 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT,
6311 "uninitialized constant: `%s`",
6313 else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue)
6314 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL,
6315 "uninitialized global: `%s`",
6318 if (!asvalue->generateAccessors(ir)) {
6323 for (auto &it : parser->fields) {
6324 ast_value *asvalue = (ast_value*)it->m_next;
6325 if (!ast_istype(asvalue, ast_value))
6327 if (asvalue->m_vtype != TYPE_ARRAY)
6329 if (!asvalue->generateAccessors(ir)) {
6334 if (parser->reserved_version &&
6335 !parser->reserved_version->generateGlobal(ir, false))
6337 con_out("failed to generate reserved::version");
6341 for (auto &f : parser->functions) {
6342 if (!f->generateFunction(ir)) {
6343 con_out("failed to generate function %s\n", f->m_name.c_str());
6349 generate_checksum(parser, ir);
6351 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6353 for (auto &it : parser->functions) {
6354 if (!ir_function_finalize(it->m_ir_func)) {
6355 con_out("failed to finalize function %s\n", it->m_name.c_str());
6360 parser->remove_ast();
6362 auto fnCheckWErrors = [&retval]() {
6363 if (compile_Werrors) {
6364 con_out("*** there were warnings treated as errors\n");
6365 compile_show_werrors();
6373 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6376 if (!ir->generate(output)) {
6377 con_out("*** failed to generate output file\n");
6382 // ir->generate can generate compiler warnings