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 = vec_size(parser->variables); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_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 = vec_size(parser->typedefs); 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 bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
298 if (ast_istype(expr, ast_value)) {
299 ast_value *val = (ast_value*)expr;
300 if (val->m_cvq == CV_CONST) {
301 if (val->m_name[0] == '#') {
302 compile_error(ctx, "invalid assignment to a literal constant");
306 * To work around quakeworld we must elide the error and make it
309 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
310 compile_error(ctx, "assignment to constant `%s`", val->m_name);
312 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
319 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
323 ast_expression *out = nullptr;
324 ast_expression *exprs[3];
325 ast_block *blocks[3];
326 ast_binstore *asbinstore;
327 size_t i, assignop, addop, subop;
328 qcint_t generated_op = 0;
333 if (sy->ops.empty()) {
334 parseerror(parser, "internal error: missing operator");
338 if (sy->ops.back().isparen) {
339 parseerror(parser, "unmatched parenthesis");
343 op = &operators[sy->ops.back().etype - 1];
344 ctx = sy->ops.back().ctx;
346 if (sy->out.size() < op->operands) {
347 if (op->flags & OP_PREFIX)
348 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
349 else /* this should have errored previously already */
350 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
356 /* op(:?) has no input and no output */
360 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
361 for (i = 0; i < op->operands; ++i) {
362 exprs[i] = sy->out[sy->out.size()+i].out;
363 blocks[i] = sy->out[sy->out.size()+i].block;
365 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
366 !(i != 0 && op->id == opid2('?',':')) &&
367 !(i == 1 && op->id == opid1('.')))
369 if (ast_istype(exprs[i], ast_label))
370 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
372 compile_error(exprs[i]->m_context, "not an expression");
373 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
377 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
378 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
382 #define NotSameType(T) \
383 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
384 exprs[0]->m_vtype != T)
389 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
393 if (exprs[0]->m_vtype == TYPE_VECTOR &&
394 exprs[1]->m_vtype == TYPE_NOEXPR)
396 if (exprs[1] == parser->const_vec[0])
397 out = ast_member::make(ctx, exprs[0], 0, "");
398 else if (exprs[1] == parser->const_vec[1])
399 out = ast_member::make(ctx, exprs[0], 1, "");
400 else if (exprs[1] == parser->const_vec[2])
401 out = ast_member::make(ctx, exprs[0], 2, "");
403 compile_error(ctx, "access to invalid vector component");
407 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
408 if (exprs[1]->m_vtype != TYPE_FIELD) {
409 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
412 out = new ast_entfield(ctx, exprs[0], exprs[1]);
414 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
415 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
419 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
425 if (exprs[0]->m_vtype != TYPE_ARRAY &&
426 !(exprs[0]->m_vtype == TYPE_FIELD &&
427 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
429 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
430 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
433 if (exprs[1]->m_vtype != TYPE_FLOAT) {
434 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
435 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
438 out = ast_array_index::make(ctx, exprs[0], exprs[1]);
439 rotate_entfield_array_index_nodes(&out);
443 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
444 sy->out.push_back(syexp(ctx, exprs[0]));
445 sy->out.push_back(syexp(ctx, exprs[1]));
450 if (!blocks[0]->addExpr(exprs[1]))
453 blocks[0] = new ast_block(ctx);
454 if (!blocks[0]->addExpr(exprs[0]) ||
455 !blocks[0]->addExpr(exprs[1]))
460 blocks[0]->setType(*exprs[1]);
462 sy->out.push_back(syblock(ctx, blocks[0]));
469 if ((out = parser->m_fold.op(op, exprs)))
472 if (exprs[0]->m_vtype != TYPE_FLOAT &&
473 exprs[0]->m_vtype != TYPE_VECTOR) {
474 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
475 type_name[exprs[0]->m_vtype]);
478 if (exprs[0]->m_vtype == TYPE_FLOAT)
479 out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]);
481 out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]);
485 if (!(out = parser->m_fold.op(op, exprs))) {
486 switch (exprs[0]->m_vtype) {
488 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
491 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]);
494 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
495 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
497 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]);
499 /* we don't constant-fold NOT for these types */
501 out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]);
504 out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]);
507 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
508 type_name[exprs[0]->m_vtype]);
515 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
516 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
518 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
519 type_name[exprs[0]->m_vtype],
520 type_name[exprs[1]->m_vtype]);
523 if (!(out = parser->m_fold.op(op, exprs))) {
524 switch (exprs[0]->m_vtype) {
526 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
529 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
532 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
533 type_name[exprs[0]->m_vtype],
534 type_name[exprs[1]->m_vtype]);
540 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
541 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
543 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
544 type_name[exprs[1]->m_vtype],
545 type_name[exprs[0]->m_vtype]);
548 if (!(out = parser->m_fold.op(op, exprs))) {
549 switch (exprs[0]->m_vtype) {
551 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
554 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
557 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
558 type_name[exprs[1]->m_vtype],
559 type_name[exprs[0]->m_vtype]);
565 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
566 !(exprs[0]->m_vtype == TYPE_VECTOR &&
567 exprs[1]->m_vtype == TYPE_FLOAT) &&
568 !(exprs[1]->m_vtype == TYPE_VECTOR &&
569 exprs[0]->m_vtype == TYPE_FLOAT)
572 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
573 type_name[exprs[1]->m_vtype],
574 type_name[exprs[0]->m_vtype]);
577 if (!(out = parser->m_fold.op(op, exprs))) {
578 switch (exprs[0]->m_vtype) {
580 if (exprs[1]->m_vtype == TYPE_VECTOR)
581 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
583 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
586 if (exprs[1]->m_vtype == TYPE_FLOAT)
587 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
589 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
592 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
593 type_name[exprs[1]->m_vtype],
594 type_name[exprs[0]->m_vtype]);
601 if (exprs[1]->m_vtype != TYPE_FLOAT) {
602 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
603 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
604 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
607 if (!(out = parser->m_fold.op(op, exprs))) {
608 if (exprs[0]->m_vtype == TYPE_FLOAT)
609 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
611 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
612 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
613 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
620 if (NotSameType(TYPE_FLOAT)) {
621 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
622 type_name[exprs[0]->m_vtype],
623 type_name[exprs[1]->m_vtype]);
625 } else if (!(out = parser->m_fold.op(op, exprs))) {
626 /* generate a call to __builtin_mod */
627 ast_expression *mod = parser->m_intrin.func("mod");
628 ast_call *call = nullptr;
629 if (!mod) return false; /* can return null for missing floor */
631 call = ast_call::make(parser_ctx(parser), mod);
632 call->m_params.push_back(exprs[0]);
633 call->m_params.push_back(exprs[1]);
640 compile_error(ctx, "%= is unimplemented");
646 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
647 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
648 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
650 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
651 type_name[exprs[0]->m_vtype],
652 type_name[exprs[1]->m_vtype]);
656 if (!(out = parser->m_fold.op(op, exprs))) {
658 * IF the first expression is float, the following will be too
659 * since scalar ^ vector is not allowed.
661 if (exprs[0]->m_vtype == TYPE_FLOAT) {
662 out = fold::binary(ctx,
663 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
667 * The first is a vector: vector is allowed to bitop with vector and
668 * with scalar, branch here for the second operand.
670 if (exprs[1]->m_vtype == TYPE_VECTOR) {
672 * Bitop all the values of the vector components against the
673 * vectors components in question.
675 out = fold::binary(ctx,
676 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
679 out = fold::binary(ctx,
680 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
689 if (NotSameType(TYPE_FLOAT)) {
690 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
691 type_name[exprs[0]->m_vtype],
692 type_name[exprs[1]->m_vtype]);
696 if (!(out = parser->m_fold.op(op, exprs))) {
697 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
698 ast_call *call = ast_call::make(parser_ctx(parser), shift);
699 call->m_params.push_back(exprs[0]);
700 call->m_params.push_back(exprs[1]);
705 case opid3('<','<','='):
706 case opid3('>','>','='):
707 if (NotSameType(TYPE_FLOAT)) {
708 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
709 type_name[exprs[0]->m_vtype],
710 type_name[exprs[1]->m_vtype]);
714 if(!(out = parser->m_fold.op(op, exprs))) {
715 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
716 ast_call *call = ast_call::make(parser_ctx(parser), shift);
717 call->m_params.push_back(exprs[0]);
718 call->m_params.push_back(exprs[1]);
730 generated_op += 1; /* INSTR_OR */
732 generated_op += INSTR_AND;
733 if (!(out = parser->m_fold.op(op, exprs))) {
734 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
735 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
736 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
737 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
740 for (i = 0; i < 2; ++i) {
741 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
742 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
744 out = ast_unary::make(ctx, INSTR_NOT_F, out);
746 exprs[i] = out; out = nullptr;
747 if (OPTS_FLAG(PERL_LOGIC)) {
748 /* here we want to keep the right expressions' type */
752 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
753 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
755 out = ast_unary::make(ctx, INSTR_NOT_F, out);
757 exprs[i] = out; out = nullptr;
758 if (OPTS_FLAG(PERL_LOGIC)) {
759 /* here we want to keep the right expressions' type */
764 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
769 if (sy->paren.back() != PAREN_TERNARY2) {
770 compile_error(ctx, "mismatched parenthesis/ternary");
773 sy->paren.pop_back();
774 if (!exprs[1]->compareType(*exprs[2])) {
775 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
776 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
777 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
780 if (!(out = parser->m_fold.op(op, exprs)))
781 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
784 case opid2('*', '*'):
785 if (NotSameType(TYPE_FLOAT)) {
786 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
787 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
788 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
793 if (!(out = parser->m_fold.op(op, exprs))) {
794 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
795 gencall->m_params.push_back(exprs[0]);
796 gencall->m_params.push_back(exprs[1]);
801 case opid2('>', '<'):
802 if (NotSameType(TYPE_VECTOR)) {
803 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
804 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
805 compile_error(ctx, "invalid types used in cross product: %s and %s",
810 if (!(out = parser->m_fold.op(op, exprs))) {
821 case opid3('<','=','>'): /* -1, 0, or 1 */
822 if (NotSameType(TYPE_FLOAT)) {
823 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
824 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
825 compile_error(ctx, "invalid types used in comparision: %s and %s",
831 if (!(out = parser->m_fold.op(op, exprs))) {
832 /* This whole block is NOT fold_binary safe */
833 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
835 eq->m_refs = AST_REF_NONE;
838 out = new ast_ternary(ctx,
839 new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
841 parser->m_fold.imm_float(2),
844 new ast_ternary(ctx, eq,
846 parser->m_fold.imm_float(0),
849 parser->m_fold.imm_float(1)
859 generated_op += 1; /* INSTR_GT */
861 generated_op += 1; /* INSTR_LT */
862 case opid2('>', '='):
863 generated_op += 1; /* INSTR_GE */
864 case opid2('<', '='):
865 generated_op += INSTR_LE;
866 if (NotSameType(TYPE_FLOAT)) {
867 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
868 type_name[exprs[0]->m_vtype],
869 type_name[exprs[1]->m_vtype]);
872 if (!(out = parser->m_fold.op(op, exprs)))
873 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
875 case opid2('!', '='):
876 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
877 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
878 type_name[exprs[0]->m_vtype],
879 type_name[exprs[1]->m_vtype]);
882 if (!(out = parser->m_fold.op(op, exprs)))
883 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
885 case opid2('=', '='):
886 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
887 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
888 type_name[exprs[0]->m_vtype],
889 type_name[exprs[1]->m_vtype]);
892 if (!(out = parser->m_fold.op(op, exprs)))
893 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
897 if (ast_istype(exprs[0], ast_entfield)) {
898 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
899 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
900 exprs[0]->m_vtype == TYPE_FIELD &&
901 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
903 assignop = type_storep_instr[TYPE_VECTOR];
906 assignop = type_storep_instr[exprs[0]->m_vtype];
907 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
909 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
910 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
911 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
912 field->m_next->m_vtype == TYPE_FUNCTION &&
913 exprs[1]->m_vtype == TYPE_FUNCTION)
915 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
916 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
919 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
924 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
925 exprs[0]->m_vtype == TYPE_FIELD &&
926 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
928 assignop = type_store_instr[TYPE_VECTOR];
931 assignop = type_store_instr[exprs[0]->m_vtype];
934 if (assignop == VINSTR_END) {
935 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
936 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
937 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
939 else if (!exprs[0]->compareType(*exprs[1]))
941 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
942 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
943 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
944 exprs[0]->m_vtype == TYPE_FUNCTION &&
945 exprs[1]->m_vtype == TYPE_FUNCTION)
947 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
948 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
951 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
954 (void)check_write_to(ctx, exprs[0]);
955 /* When we're a vector of part of an entity field we use STOREP */
956 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
957 assignop = INSTR_STOREP_F;
958 out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
960 case opid3('+','+','P'):
961 case opid3('-','-','P'):
963 if (exprs[0]->m_vtype != TYPE_FLOAT) {
964 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
965 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
968 if (op->id == opid3('+','+','P'))
972 (void)check_write_to(exprs[0]->m_context, exprs[0]);
973 if (ast_istype(exprs[0], ast_entfield)) {
974 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
976 parser->m_fold.imm_float(1));
978 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
980 parser->m_fold.imm_float(1));
983 case opid3('S','+','+'):
984 case opid3('S','-','-'):
986 if (exprs[0]->m_vtype != TYPE_FLOAT) {
987 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
988 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
991 if (op->id == opid3('S','+','+')) {
998 (void)check_write_to(exprs[0]->m_context, exprs[0]);
999 if (ast_istype(exprs[0], ast_entfield)) {
1000 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1002 parser->m_fold.imm_float(1));
1004 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1006 parser->m_fold.imm_float(1));
1010 out = fold::binary(ctx, subop,
1012 parser->m_fold.imm_float(1));
1015 case opid2('+','='):
1016 case opid2('-','='):
1017 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1018 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1020 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1021 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1022 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1026 (void)check_write_to(ctx, exprs[0]);
1027 if (ast_istype(exprs[0], ast_entfield))
1028 assignop = type_storep_instr[exprs[0]->m_vtype];
1030 assignop = type_store_instr[exprs[0]->m_vtype];
1031 switch (exprs[0]->m_vtype) {
1033 out = new ast_binstore(ctx, assignop,
1034 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1035 exprs[0], exprs[1]);
1038 out = new ast_binstore(ctx, assignop,
1039 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1040 exprs[0], exprs[1]);
1043 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1044 type_name[exprs[0]->m_vtype],
1045 type_name[exprs[1]->m_vtype]);
1049 case opid2('*','='):
1050 case opid2('/','='):
1051 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1052 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1053 exprs[0]->m_vtype == TYPE_VECTOR))
1055 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1056 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1057 compile_error(ctx, "invalid types used in expression: %s and %s",
1061 (void)check_write_to(ctx, exprs[0]);
1062 if (ast_istype(exprs[0], ast_entfield))
1063 assignop = type_storep_instr[exprs[0]->m_vtype];
1065 assignop = type_store_instr[exprs[0]->m_vtype];
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 if (ast_istype(exprs[0], ast_entfield))
1107 assignop = type_storep_instr[exprs[0]->m_vtype];
1109 assignop = type_store_instr[exprs[0]->m_vtype];
1110 if (exprs[0]->m_vtype == TYPE_FLOAT)
1111 out = new ast_binstore(ctx, assignop,
1112 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1113 exprs[0], exprs[1]);
1115 out = new ast_binstore(ctx, assignop,
1116 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1117 exprs[0], exprs[1]);
1119 case opid3('&','~','='):
1120 /* This is like: a &= ~(b);
1121 * But QC has no bitwise-not, so we implement it as
1124 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1125 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1126 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1127 compile_error(ctx, "invalid types used in expression: %s and %s",
1131 if (ast_istype(exprs[0], ast_entfield))
1132 assignop = type_storep_instr[exprs[0]->m_vtype];
1134 assignop = type_store_instr[exprs[0]->m_vtype];
1135 if (exprs[0]->m_vtype == TYPE_FLOAT)
1136 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1138 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1141 (void)check_write_to(ctx, exprs[0]);
1142 if (exprs[0]->m_vtype == TYPE_FLOAT)
1143 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1145 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1146 asbinstore->m_keep_dest = true;
1150 case opid3('l', 'e', 'n'):
1151 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1152 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1153 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1156 /* strings must be const, arrays are statically sized */
1157 if (exprs[0]->m_vtype == TYPE_STRING &&
1158 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1160 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1163 out = parser->m_fold.op(op, exprs);
1166 case opid2('~', 'P'):
1167 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1168 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1169 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1172 if (!(out = parser->m_fold.op(op, exprs))) {
1173 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1174 out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1176 out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1183 compile_error(ctx, "failed to apply operator %s", op->op);
1187 sy->out.push_back(syexp(ctx, out));
1191 static bool parser_close_call(parser_t *parser, shunt *sy)
1193 /* was a function call */
1194 ast_expression *fun;
1195 ast_value *funval = nullptr;
1199 size_t paramcount, i;
1202 fid = sy->ops.back().off;
1205 /* out[fid] is the function
1206 * everything above is parameters...
1208 if (sy->argc.empty()) {
1209 parseerror(parser, "internal error: no argument counter available");
1213 paramcount = sy->argc.back();
1214 sy->argc.pop_back();
1216 if (sy->out.size() < fid) {
1217 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1225 * TODO handle this at the intrinsic level with an ast_intrinsic
1228 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1230 if (fid+2 != sy->out.size() || sy->out.back().block) {
1231 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1234 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1235 ast_unref(sy->out.back().out);
1236 sy->out[fid] = syexp(sy->out.back().out->m_context,
1237 parser->m_fold.constgen_string(ty, false));
1243 * Now we need to determine if the function that is being called is
1244 * an intrinsic so we can evaluate if the arguments to it are constant
1245 * and than fruitfully fold them.
1247 #define fold_can_1(X) \
1248 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1249 ((X))->m_vtype != TYPE_FUNCTION)
1251 if (fid + 1 < sy->out.size())
1254 for (i = 0; i < paramcount; ++i) {
1255 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1262 * All is well which ends well, if we make it into here we can ignore the
1263 * intrinsic call and just evaluate it i.e constant fold it.
1265 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1266 ast_expression **exprs = nullptr;
1267 ast_expression *foldval = nullptr;
1269 for (i = 0; i < paramcount; i++)
1270 vec_push(exprs, sy->out[fid+1 + i].out);
1272 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs))) {
1278 * Blub: what sorts of unreffing and resizing of
1279 * sy->out should I be doing here?
1281 sy->out[fid] = syexp(foldval->m_context, foldval);
1282 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1289 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1294 if (fid+1 + paramcount != sy->out.size()) {
1295 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1302 for (i = 0; i < paramcount; ++i)
1303 call->m_params.push_back(sy->out[fid+1 + i].out);
1304 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1305 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1306 if (parser->max_param_count < paramcount)
1307 parser->max_param_count = paramcount;
1309 if (ast_istype(fun, ast_value)) {
1310 funval = (ast_value*)fun;
1311 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1312 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1314 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1318 /* overwrite fid, the function, with a call */
1319 sy->out[fid] = syexp(call->m_context, call);
1321 if (fun->m_vtype != TYPE_FUNCTION) {
1322 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1327 parseerror(parser, "could not determine function return type");
1330 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1332 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1334 return !parsewarning(parser, WARN_DEPRECATED,
1335 "call to function (which is marked deprecated)\n",
1336 "-> it has been declared here: %s:%i",
1337 fun->m_context.file, fun->m_context.line);
1339 if (!fval->m_desc.length()) {
1340 return !parsewarning(parser, WARN_DEPRECATED,
1341 "call to `%s` (which is marked deprecated)\n"
1342 "-> `%s` declared here: %s:%i",
1343 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1345 return !parsewarning(parser, WARN_DEPRECATED,
1346 "call to `%s` (deprecated: %s)\n"
1347 "-> `%s` declared here: %s:%i",
1348 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1349 fun->m_context.line);
1352 if (fun->m_type_params.size() != paramcount &&
1353 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1354 fun->m_type_params.size() < paramcount))
1356 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1358 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1359 "too %s parameters for call to %s: expected %i, got %i\n"
1360 " -> `%s` has been declared here: %s:%i",
1361 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1362 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1364 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1365 "too %s parameters for function call: expected %i, got %i\n"
1366 " -> it has been declared here: %s:%i",
1367 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1368 fun->m_context.file, (int)fun->m_context.line);
1375 static bool parser_close_paren(parser_t *parser, shunt *sy)
1377 if (sy->ops.empty()) {
1378 parseerror(parser, "unmatched closing paren");
1382 while (sy->ops.size()) {
1383 if (sy->ops.back().isparen) {
1384 if (sy->paren.back() == PAREN_FUNC) {
1385 sy->paren.pop_back();
1386 if (!parser_close_call(parser, sy))
1390 if (sy->paren.back() == PAREN_EXPR) {
1391 sy->paren.pop_back();
1392 if (sy->out.empty()) {
1393 compile_error(sy->ops.back().ctx, "empty paren expression");
1400 if (sy->paren.back() == PAREN_INDEX) {
1401 sy->paren.pop_back();
1402 // pop off the parenthesis
1404 /* then apply the index operator */
1405 if (!parser_sy_apply_operator(parser, sy))
1409 if (sy->paren.back() == PAREN_TERNARY1) {
1410 sy->paren.back() = PAREN_TERNARY2;
1411 // pop off the parenthesis
1415 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1418 if (!parser_sy_apply_operator(parser, sy))
1424 static void parser_reclassify_token(parser_t *parser)
1427 if (parser->tok >= TOKEN_START)
1429 for (i = 0; i < operator_count; ++i) {
1430 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1431 parser->tok = TOKEN_OPERATOR;
1437 static ast_expression* parse_vararg_do(parser_t *parser)
1439 ast_expression *idx, *out;
1441 ast_value *funtype = parser->function->m_function_type;
1442 lex_ctx_t ctx = parser_ctx(parser);
1444 if (!parser->function->m_varargs) {
1445 parseerror(parser, "function has no variable argument list");
1449 if (!parser_next(parser) || parser->tok != '(') {
1450 parseerror(parser, "expected parameter index and type in parenthesis");
1453 if (!parser_next(parser)) {
1454 parseerror(parser, "error parsing parameter index");
1458 idx = parse_expression_leave(parser, true, false, false);
1462 if (parser->tok != ',') {
1463 if (parser->tok != ')') {
1465 parseerror(parser, "expected comma after parameter index");
1468 // vararg piping: ...(start)
1469 out = new ast_argpipe(ctx, idx);
1473 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1475 parseerror(parser, "expected typename for vararg");
1479 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1485 if (parser->tok != ')') {
1488 parseerror(parser, "expected closing paren");
1492 if (funtype->m_varparam &&
1493 !typevar->compareType(*funtype->m_varparam))
1497 ast_type_to_string(typevar, ty1, sizeof(ty1));
1498 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1499 compile_error(typevar->m_context,
1500 "function was declared to take varargs of type `%s`, requested type is: %s",
1504 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1505 out->adoptType(*typevar);
1510 static ast_expression* parse_vararg(parser_t *parser)
1512 bool old_noops = parser->lex->flags.noops;
1514 ast_expression *out;
1516 parser->lex->flags.noops = true;
1517 out = parse_vararg_do(parser);
1519 parser->lex->flags.noops = old_noops;
1523 /* not to be exposed */
1524 bool ftepp_predef_exists(const char *name);
1525 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1527 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1528 parser->tok == TOKEN_IDENT &&
1529 !strcmp(parser_tokval(parser), "_"))
1531 /* a translatable string */
1534 parser->lex->flags.noops = true;
1535 if (!parser_next(parser) || parser->tok != '(') {
1536 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1539 parser->lex->flags.noops = false;
1540 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1541 parseerror(parser, "expected a constant string in translatable-string extension");
1544 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1547 sy->out.push_back(syexp(parser_ctx(parser), val));
1549 if (!parser_next(parser) || parser->tok != ')') {
1550 parseerror(parser, "expected closing paren after translatable string");
1555 else if (parser->tok == TOKEN_DOTS)
1558 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1559 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1562 va = parse_vararg(parser);
1565 sy->out.push_back(syexp(parser_ctx(parser), va));
1568 else if (parser->tok == TOKEN_FLOATCONST) {
1569 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1572 sy->out.push_back(syexp(parser_ctx(parser), val));
1575 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1576 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1579 sy->out.push_back(syexp(parser_ctx(parser), val));
1582 else if (parser->tok == TOKEN_STRINGCONST) {
1583 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1586 sy->out.push_back(syexp(parser_ctx(parser), val));
1589 else if (parser->tok == TOKEN_VECTORCONST) {
1590 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1593 sy->out.push_back(syexp(parser_ctx(parser), val));
1596 else if (parser->tok == TOKEN_IDENT)
1598 const char *ctoken = parser_tokval(parser);
1599 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1600 ast_expression *var;
1601 /* a_vector.{x,y,z} */
1602 if (sy->ops.empty() ||
1603 !sy->ops.back().etype ||
1604 operators[sy->ops.back().etype-1].id != opid1('.'))
1606 /* When adding more intrinsics, fix the above condition */
1609 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1611 var = parser->const_vec[ctoken[0]-'x'];
1613 var = parser_find_var(parser, parser_tokval(parser));
1615 var = parser_find_field(parser, parser_tokval(parser));
1617 if (!var && with_labels) {
1618 var = parser_find_label(parser, parser_tokval(parser));
1620 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1622 parser->labels.push_back(lbl);
1625 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1626 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1629 * now we try for the real intrinsic hashtable. If the string
1630 * begins with __builtin, we simply skip past it, otherwise we
1631 * use the identifier as is.
1633 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1634 var = parser->m_intrin.func(parser_tokval(parser));
1638 * Try it again, intrin_func deals with the alias method as well
1639 * the first one masks for __builtin though, we emit warning here.
1642 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1643 (void)!compile_warning(
1646 "using implicitly defined builtin `__builtin_%s' for `%s'",
1647 parser_tokval(parser),
1648 parser_tokval(parser)
1656 * sometimes people use preprocessing predefs without enabling them
1657 * i've done this thousands of times already myself. Lets check for
1658 * it in the predef table. And diagnose it better :)
1660 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1661 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1665 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1671 if (ast_istype(var, ast_value)) {
1672 ((ast_value*)var)->m_uses++;
1674 else if (ast_istype(var, ast_member)) {
1675 ast_member *mem = (ast_member*)var;
1676 if (ast_istype(mem->m_owner, ast_value))
1677 ((ast_value*)(mem->m_owner))->m_uses++;
1680 sy->out.push_back(syexp(parser_ctx(parser), var));
1683 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1687 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1689 ast_expression *expr = nullptr;
1691 bool wantop = false;
1692 /* only warn once about an assignment in a truth value because the current code
1693 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1695 bool warn_parenthesis = true;
1697 /* count the parens because an if starts with one, so the
1698 * end of a condition is an unmatched closing paren
1702 memset(&sy, 0, sizeof(sy));
1704 parser->lex->flags.noops = false;
1706 parser_reclassify_token(parser);
1710 if (parser->tok == TOKEN_TYPENAME) {
1711 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1715 if (parser->tok == TOKEN_OPERATOR)
1717 /* classify the operator */
1718 const oper_info *op;
1719 const oper_info *olast = nullptr;
1721 for (o = 0; o < operator_count; ++o) {
1722 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1723 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1724 !strcmp(parser_tokval(parser), operators[o].op))
1729 if (o == operator_count) {
1730 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1733 /* found an operator */
1736 /* when declaring variables, a comma starts a new variable */
1737 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1738 /* fixup the token */
1743 /* a colon without a pervious question mark cannot be a ternary */
1744 if (!ternaries && op->id == opid2(':','?')) {
1749 if (op->id == opid1(',')) {
1750 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1751 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1755 if (sy.ops.size() && !sy.ops.back().isparen)
1756 olast = &operators[sy.ops.back().etype-1];
1758 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1759 while (olast && op->prec < olast->prec)
1761 if (!parser_sy_apply_operator(parser, &sy))
1763 if (sy.ops.size() && !sy.ops.back().isparen)
1764 olast = &operators[sy.ops.back().etype-1];
1769 #define IsAssignOp(x) (\
1770 (x) == opid1('=') || \
1771 (x) == opid2('+','=') || \
1772 (x) == opid2('-','=') || \
1773 (x) == opid2('*','=') || \
1774 (x) == opid2('/','=') || \
1775 (x) == opid2('%','=') || \
1776 (x) == opid2('&','=') || \
1777 (x) == opid2('|','=') || \
1778 (x) == opid3('&','~','=') \
1780 if (warn_parenthesis) {
1781 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1782 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1783 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1786 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1787 warn_parenthesis = false;
1790 if (olast && olast->id != op->id) {
1791 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1792 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1794 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1795 warn_parenthesis = false;
1797 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1798 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1800 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1801 warn_parenthesis = false;
1807 (op->prec < olast->prec) ||
1808 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1810 if (!parser_sy_apply_operator(parser, &sy))
1812 if (sy.ops.size() && !sy.ops.back().isparen)
1813 olast = &operators[sy.ops.back().etype-1];
1818 if (op->id == opid1('(')) {
1820 size_t sycount = sy.out.size();
1821 /* we expected an operator, this is the function-call operator */
1822 sy.paren.push_back(PAREN_FUNC);
1823 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1824 sy.argc.push_back(0);
1826 sy.paren.push_back(PAREN_EXPR);
1827 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1830 } else if (op->id == opid1('[')) {
1832 parseerror(parser, "unexpected array subscript");
1835 sy.paren.push_back(PAREN_INDEX);
1836 /* push both the operator and the paren, this makes life easier */
1837 sy.ops.push_back(syop(parser_ctx(parser), op));
1838 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1840 } else if (op->id == opid2('?',':')) {
1841 sy.ops.push_back(syop(parser_ctx(parser), op));
1842 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1845 sy.paren.push_back(PAREN_TERNARY1);
1846 } else if (op->id == opid2(':','?')) {
1847 if (sy.paren.empty()) {
1848 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1851 if (sy.paren.back() != PAREN_TERNARY1) {
1852 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1855 if (!parser_close_paren(parser, &sy))
1857 sy.ops.push_back(syop(parser_ctx(parser), op));
1861 sy.ops.push_back(syop(parser_ctx(parser), op));
1862 wantop = !!(op->flags & OP_SUFFIX);
1865 else if (parser->tok == ')') {
1866 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1867 if (!parser_sy_apply_operator(parser, &sy))
1870 if (sy.paren.empty())
1873 if (sy.paren.back() == PAREN_TERNARY1) {
1874 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1877 if (!parser_close_paren(parser, &sy))
1880 /* must be a function call without parameters */
1881 if (sy.paren.back() != PAREN_FUNC) {
1882 parseerror(parser, "closing paren in invalid position");
1885 if (!parser_close_paren(parser, &sy))
1890 else if (parser->tok == '(') {
1891 parseerror(parser, "internal error: '(' should be classified as operator");
1894 else if (parser->tok == '[') {
1895 parseerror(parser, "internal error: '[' should be classified as operator");
1898 else if (parser->tok == ']') {
1899 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1900 if (!parser_sy_apply_operator(parser, &sy))
1903 if (sy.paren.empty())
1905 if (sy.paren.back() != PAREN_INDEX) {
1906 parseerror(parser, "mismatched parentheses, unexpected ']'");
1909 if (!parser_close_paren(parser, &sy))
1914 if (!parse_sya_operand(parser, &sy, with_labels))
1919 /* in this case we might want to allow constant string concatenation */
1920 bool concatenated = false;
1921 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1922 ast_expression *lexpr = sy.out.back().out;
1923 if (ast_istype(lexpr, ast_value)) {
1924 ast_value *last = (ast_value*)lexpr;
1925 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1926 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1928 char *newstr = nullptr;
1929 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1930 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1932 concatenated = true;
1936 if (!concatenated) {
1937 parseerror(parser, "expected operator or end of statement");
1942 if (!parser_next(parser)) {
1945 if (parser->tok == ';' ||
1946 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1947 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1953 while (sy.ops.size()) {
1954 if (!parser_sy_apply_operator(parser, &sy))
1958 parser->lex->flags.noops = true;
1959 if (sy.out.size() != 1) {
1960 parseerror(parser, "expression expected");
1963 expr = sy.out[0].out;
1964 if (sy.paren.size()) {
1965 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1971 parser->lex->flags.noops = true;
1972 for (auto &it : sy.out)
1973 if (it.out) ast_unref(it.out);
1977 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1979 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1982 if (parser->tok != ';') {
1983 parseerror(parser, "semicolon expected after expression");
1987 if (!parser_next(parser)) {
1994 static void parser_enterblock(parser_t *parser)
1996 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1997 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1998 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1999 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2000 vec_push(parser->_block_ctx, parser_ctx(parser));
2003 static bool parser_leaveblock(parser_t *parser)
2006 size_t locals, typedefs;
2008 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2009 parseerror(parser, "internal error: parser_leaveblock with no block");
2013 util_htdel(vec_last(parser->variables));
2015 vec_pop(parser->variables);
2016 if (!vec_size(parser->_blocklocals)) {
2017 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2021 locals = vec_last(parser->_blocklocals);
2022 vec_pop(parser->_blocklocals);
2023 while (vec_size(parser->_locals) != locals) {
2024 ast_expression *e = vec_last(parser->_locals);
2025 ast_value *v = (ast_value*)e;
2026 vec_pop(parser->_locals);
2027 if (ast_istype(e, ast_value) && !v->m_uses) {
2028 if (compile_warning(v->m_context, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->m_name))
2033 typedefs = vec_last(parser->_blocktypedefs);
2034 while (vec_size(parser->_typedefs) != typedefs) {
2035 delete vec_last(parser->_typedefs);
2036 vec_pop(parser->_typedefs);
2038 util_htdel(vec_last(parser->typedefs));
2039 vec_pop(parser->typedefs);
2041 vec_pop(parser->_block_ctx);
2046 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2048 vec_push(parser->_locals, e);
2049 util_htset(vec_last(parser->variables), name, (void*)e);
2051 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2052 return parser_addlocal(parser, name.c_str(), e);
2055 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2057 parser->globals.push_back(e);
2058 util_htset(parser->htglobals, name, e);
2060 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2061 return parser_addglobal(parser, name.c_str(), e);
2064 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2068 ast_expression *prev;
2070 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2072 ast_type_to_string(cond, ty, sizeof(ty));
2073 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2076 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2079 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2082 parseerror(parser, "internal error: failed to process condition");
2087 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2089 /* vector types need to be cast to true booleans */
2090 ast_binary *bin = (ast_binary*)cond;
2091 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2093 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2095 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2098 parseerror(parser, "internal error: failed to process condition");
2105 unary = (ast_unary*)cond;
2106 /* ast_istype dereferences cond, should test here for safety */
2107 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2109 cond = unary->m_operand;
2110 unary->m_operand = nullptr;
2113 unary = (ast_unary*)cond;
2117 parseerror(parser, "internal error: failed to process condition");
2119 if (ifnot) *_ifnot = !*_ifnot;
2123 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2126 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2129 lex_ctx_t ctx = parser_ctx(parser);
2131 (void)block; /* not touching */
2133 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2134 if (!parser_next(parser)) {
2135 parseerror(parser, "expected condition or 'not'");
2138 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2140 if (!parser_next(parser)) {
2141 parseerror(parser, "expected condition in parenthesis");
2145 if (parser->tok != '(') {
2146 parseerror(parser, "expected 'if' condition in parenthesis");
2149 /* parse into the expression */
2150 if (!parser_next(parser)) {
2151 parseerror(parser, "expected 'if' condition after opening paren");
2154 /* parse the condition */
2155 cond = parse_expression_leave(parser, false, true, false);
2159 if (parser->tok != ')') {
2160 parseerror(parser, "expected closing paren after 'if' condition");
2164 /* parse into the 'then' branch */
2165 if (!parser_next(parser)) {
2166 parseerror(parser, "expected statement for on-true branch of 'if'");
2170 if (!parse_statement_or_block(parser, &ontrue)) {
2175 ontrue = new ast_block(parser_ctx(parser));
2176 /* check for an else */
2177 if (!strcmp(parser_tokval(parser), "else")) {
2178 /* parse into the 'else' branch */
2179 if (!parser_next(parser)) {
2180 parseerror(parser, "expected on-false branch after 'else'");
2185 if (!parse_statement_or_block(parser, &onfalse)) {
2192 cond = process_condition(parser, cond, &ifnot);
2194 if (ontrue) delete ontrue;
2195 if (onfalse) delete onfalse;
2200 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2202 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2207 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2208 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2211 char *label = nullptr;
2213 /* skip the 'while' and get the body */
2214 if (!parser_next(parser)) {
2215 if (OPTS_FLAG(LOOP_LABELS))
2216 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2218 parseerror(parser, "expected 'while' condition in parenthesis");
2222 if (parser->tok == ':') {
2223 if (!OPTS_FLAG(LOOP_LABELS))
2224 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2225 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2226 parseerror(parser, "expected loop label");
2229 label = util_strdup(parser_tokval(parser));
2230 if (!parser_next(parser)) {
2232 parseerror(parser, "expected 'while' condition in parenthesis");
2237 if (parser->tok != '(') {
2238 parseerror(parser, "expected 'while' condition in parenthesis");
2242 parser->breaks.push_back(label);
2243 parser->continues.push_back(label);
2245 rv = parse_while_go(parser, block, out);
2248 if (parser->breaks.back() != label || parser->continues.back() != label) {
2249 parseerror(parser, "internal error: label stack corrupted");
2255 parser->breaks.pop_back();
2256 parser->continues.pop_back();
2261 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2264 ast_expression *cond, *ontrue;
2268 lex_ctx_t ctx = parser_ctx(parser);
2270 (void)block; /* not touching */
2272 /* parse into the expression */
2273 if (!parser_next(parser)) {
2274 parseerror(parser, "expected 'while' condition after opening paren");
2277 /* parse the condition */
2278 cond = parse_expression_leave(parser, false, true, false);
2282 if (parser->tok != ')') {
2283 parseerror(parser, "expected closing paren after 'while' condition");
2287 /* parse into the 'then' branch */
2288 if (!parser_next(parser)) {
2289 parseerror(parser, "expected while-loop body");
2293 if (!parse_statement_or_block(parser, &ontrue)) {
2298 cond = process_condition(parser, cond, &ifnot);
2303 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2308 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2309 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2312 char *label = nullptr;
2314 /* skip the 'do' and get the body */
2315 if (!parser_next(parser)) {
2316 if (OPTS_FLAG(LOOP_LABELS))
2317 parseerror(parser, "expected loop label or body");
2319 parseerror(parser, "expected loop body");
2323 if (parser->tok == ':') {
2324 if (!OPTS_FLAG(LOOP_LABELS))
2325 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2326 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2327 parseerror(parser, "expected loop label");
2330 label = util_strdup(parser_tokval(parser));
2331 if (!parser_next(parser)) {
2333 parseerror(parser, "expected loop body");
2338 parser->breaks.push_back(label);
2339 parser->continues.push_back(label);
2341 rv = parse_dowhile_go(parser, block, out);
2344 if (parser->breaks.back() != label || parser->continues.back() != label) {
2345 parseerror(parser, "internal error: label stack corrupted");
2351 parser->breaks.pop_back();
2352 parser->continues.pop_back();
2357 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2360 ast_expression *cond, *ontrue;
2364 lex_ctx_t ctx = parser_ctx(parser);
2366 (void)block; /* not touching */
2368 if (!parse_statement_or_block(parser, &ontrue))
2371 /* expect the "while" */
2372 if (parser->tok != TOKEN_KEYWORD ||
2373 strcmp(parser_tokval(parser), "while"))
2375 parseerror(parser, "expected 'while' and condition");
2380 /* skip the 'while' and check for opening paren */
2381 if (!parser_next(parser) || parser->tok != '(') {
2382 parseerror(parser, "expected 'while' condition in parenthesis");
2386 /* parse into the expression */
2387 if (!parser_next(parser)) {
2388 parseerror(parser, "expected 'while' condition after opening paren");
2392 /* parse the condition */
2393 cond = parse_expression_leave(parser, false, true, false);
2397 if (parser->tok != ')') {
2398 parseerror(parser, "expected closing paren after 'while' condition");
2404 if (!parser_next(parser) || parser->tok != ';') {
2405 parseerror(parser, "expected semicolon after condition");
2411 if (!parser_next(parser)) {
2412 parseerror(parser, "parse error");
2418 cond = process_condition(parser, cond, &ifnot);
2423 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2428 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2429 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2432 char *label = nullptr;
2434 /* skip the 'for' and check for opening paren */
2435 if (!parser_next(parser)) {
2436 if (OPTS_FLAG(LOOP_LABELS))
2437 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2439 parseerror(parser, "expected 'for' expressions in parenthesis");
2443 if (parser->tok == ':') {
2444 if (!OPTS_FLAG(LOOP_LABELS))
2445 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2446 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2447 parseerror(parser, "expected loop label");
2450 label = util_strdup(parser_tokval(parser));
2451 if (!parser_next(parser)) {
2453 parseerror(parser, "expected 'for' expressions in parenthesis");
2458 if (parser->tok != '(') {
2459 parseerror(parser, "expected 'for' expressions in parenthesis");
2463 parser->breaks.push_back(label);
2464 parser->continues.push_back(label);
2466 rv = parse_for_go(parser, block, out);
2469 if (parser->breaks.back() != label || parser->continues.back() != label) {
2470 parseerror(parser, "internal error: label stack corrupted");
2476 parser->breaks.pop_back();
2477 parser->continues.pop_back();
2481 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2484 ast_expression *initexpr, *cond, *increment, *ontrue;
2489 lex_ctx_t ctx = parser_ctx(parser);
2491 parser_enterblock(parser);
2495 increment = nullptr;
2498 /* parse into the expression */
2499 if (!parser_next(parser)) {
2500 parseerror(parser, "expected 'for' initializer after opening paren");
2505 if (parser->tok == TOKEN_IDENT)
2506 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2508 if (typevar || parser->tok == TOKEN_TYPENAME) {
2509 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2512 else if (parser->tok != ';')
2514 initexpr = parse_expression_leave(parser, false, false, false);
2517 /* move on to condition */
2518 if (parser->tok != ';') {
2519 parseerror(parser, "expected semicolon after for-loop initializer");
2522 if (!parser_next(parser)) {
2523 parseerror(parser, "expected for-loop condition");
2527 else if (!parser_next(parser)) {
2528 parseerror(parser, "expected for-loop condition");
2532 /* parse the condition */
2533 if (parser->tok != ';') {
2534 cond = parse_expression_leave(parser, false, true, false);
2539 /* move on to incrementor */
2540 if (parser->tok != ';') {
2541 parseerror(parser, "expected semicolon after for-loop initializer");
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected for-loop condition");
2549 /* parse the incrementor */
2550 if (parser->tok != ')') {
2551 lex_ctx_t condctx = parser_ctx(parser);
2552 increment = parse_expression_leave(parser, false, false, false);
2555 if (!increment->m_side_effects) {
2556 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2562 if (parser->tok != ')') {
2563 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2566 /* parse into the 'then' branch */
2567 if (!parser_next(parser)) {
2568 parseerror(parser, "expected for-loop body");
2571 if (!parse_statement_or_block(parser, &ontrue))
2575 cond = process_condition(parser, cond, &ifnot);
2579 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2582 if (!parser_leaveblock(parser)) {
2588 if (initexpr) ast_unref(initexpr);
2589 if (cond) ast_unref(cond);
2590 if (increment) ast_unref(increment);
2591 (void)!parser_leaveblock(parser);
2595 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2597 ast_expression *exp = nullptr;
2598 ast_expression *var = nullptr;
2599 ast_return *ret = nullptr;
2600 ast_value *retval = parser->function->m_return_value;
2601 ast_value *expected = parser->function->m_function_type;
2603 lex_ctx_t ctx = parser_ctx(parser);
2605 (void)block; /* not touching */
2607 if (!parser_next(parser)) {
2608 parseerror(parser, "expected return expression");
2612 /* return assignments */
2613 if (parser->tok == '=') {
2614 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2615 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2619 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2621 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2622 parseerror(parser, "invalid return type: `%s'", ty1);
2626 if (!parser_next(parser)) {
2627 parseerror(parser, "expected return assignment expression");
2631 if (!(exp = parse_expression_leave(parser, false, false, false)))
2634 /* prepare the return value */
2636 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2637 retval->adoptType(*expected->m_next);
2638 parser->function->m_return_value = retval;
2641 if (!exp->compareType(*retval)) {
2642 char ty1[1024], ty2[1024];
2643 ast_type_to_string(exp, ty1, sizeof(ty1));
2644 ast_type_to_string(retval, ty2, sizeof(ty2));
2645 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2648 /* store to 'return' local variable */
2649 var = new ast_store(
2651 type_store_instr[expected->m_next->m_vtype],
2659 if (parser->tok != ';')
2660 parseerror(parser, "missing semicolon after return assignment");
2661 else if (!parser_next(parser))
2662 parseerror(parser, "parse error after return assignment");
2668 if (parser->tok != ';') {
2669 exp = parse_expression(parser, false, false);
2673 if (exp->m_vtype != TYPE_NIL &&
2674 exp->m_vtype != (expected)->m_next->m_vtype)
2676 parseerror(parser, "return with invalid expression");
2679 ret = new ast_return(ctx, exp);
2685 if (!parser_next(parser))
2686 parseerror(parser, "parse error");
2688 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2690 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2692 ret = new ast_return(ctx, retval);
2698 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2701 unsigned int levels = 0;
2702 lex_ctx_t ctx = parser_ctx(parser);
2703 auto &loops = (is_continue ? parser->continues : parser->breaks);
2705 (void)block; /* not touching */
2706 if (!parser_next(parser)) {
2707 parseerror(parser, "expected semicolon or loop label");
2711 if (loops.empty()) {
2713 parseerror(parser, "`continue` can only be used inside loops");
2715 parseerror(parser, "`break` can only be used inside loops or switches");
2718 if (parser->tok == TOKEN_IDENT) {
2719 if (!OPTS_FLAG(LOOP_LABELS))
2720 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2723 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2726 parseerror(parser, "no such loop to %s: `%s`",
2727 (is_continue ? "continue" : "break out of"),
2728 parser_tokval(parser));
2733 if (!parser_next(parser)) {
2734 parseerror(parser, "expected semicolon");
2739 if (parser->tok != ';') {
2740 parseerror(parser, "expected semicolon");
2744 if (!parser_next(parser))
2745 parseerror(parser, "parse error");
2747 *out = new ast_breakcont(ctx, is_continue, levels);
2751 /* returns true when it was a variable qualifier, false otherwise!
2752 * on error, cvq is set to CV_WRONG
2754 struct attribute_t {
2759 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2761 bool had_const = false;
2762 bool had_var = false;
2763 bool had_noref = false;
2764 bool had_attrib = false;
2765 bool had_static = false;
2768 static attribute_t attributes[] = {
2769 { "noreturn", AST_FLAG_NORETURN },
2770 { "inline", AST_FLAG_INLINE },
2771 { "eraseable", AST_FLAG_ERASEABLE },
2772 { "accumulate", AST_FLAG_ACCUMULATE },
2773 { "last", AST_FLAG_FINAL_DECL }
2780 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2782 /* parse an attribute */
2783 if (!parser_next(parser)) {
2784 parseerror(parser, "expected attribute after `[[`");
2789 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2790 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2791 flags |= attributes[i].flag;
2792 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2793 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2794 attributes[i].name);
2802 if (i != GMQCC_ARRAY_COUNT(attributes))
2806 if (!strcmp(parser_tokval(parser), "noref")) {
2808 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2809 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2814 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2815 flags |= AST_FLAG_ALIAS;
2818 if (!parser_next(parser)) {
2819 parseerror(parser, "parse error in attribute");
2823 if (parser->tok == '(') {
2824 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2825 parseerror(parser, "`alias` attribute missing parameter");
2829 *message = util_strdup(parser_tokval(parser));
2831 if (!parser_next(parser)) {
2832 parseerror(parser, "parse error in attribute");
2836 if (parser->tok != ')') {
2837 parseerror(parser, "`alias` attribute expected `)` after parameter");
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "parse error in attribute");
2847 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2848 parseerror(parser, "`alias` attribute expected `]]`");
2852 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2853 flags |= AST_FLAG_DEPRECATED;
2856 if (!parser_next(parser)) {
2857 parseerror(parser, "parse error in attribute");
2861 if (parser->tok == '(') {
2862 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2863 parseerror(parser, "`deprecated` attribute missing parameter");
2867 *message = util_strdup(parser_tokval(parser));
2869 if (!parser_next(parser)) {
2870 parseerror(parser, "parse error in attribute");
2874 if(parser->tok != ')') {
2875 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2879 if (!parser_next(parser)) {
2880 parseerror(parser, "parse error in attribute");
2885 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2886 parseerror(parser, "`deprecated` attribute expected `]]`");
2889 if (*message) mem_d(*message);
2895 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2896 flags |= AST_FLAG_COVERAGE;
2897 if (!parser_next(parser)) {
2899 parseerror(parser, "parse error in coverage attribute");
2903 if (parser->tok == '(') {
2904 if (!parser_next(parser)) {
2906 parseerror(parser, "invalid parameter for coverage() attribute\n"
2907 "valid are: block");
2911 if (parser->tok != ')') {
2913 if (parser->tok != TOKEN_IDENT)
2914 goto bad_coverage_arg;
2915 if (!strcmp(parser_tokval(parser), "block"))
2916 flags |= AST_FLAG_BLOCK_COVERAGE;
2917 else if (!strcmp(parser_tokval(parser), "none"))
2918 flags &= ~(AST_FLAG_COVERAGE_MASK);
2920 goto bad_coverage_arg;
2921 if (!parser_next(parser))
2922 goto error_in_coverage;
2923 if (parser->tok == ',') {
2924 if (!parser_next(parser))
2925 goto error_in_coverage;
2927 } while (parser->tok != ')');
2929 if (parser->tok != ')' || !parser_next(parser))
2930 goto error_in_coverage;
2932 /* without parameter [[coverage]] equals [[coverage(block)]] */
2933 flags |= AST_FLAG_BLOCK_COVERAGE;
2938 /* Skip tokens until we hit a ]] */
2939 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2940 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2941 if (!parser_next(parser)) {
2942 parseerror(parser, "error inside attribute");
2949 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2951 else if (!strcmp(parser_tokval(parser), "const"))
2953 else if (!strcmp(parser_tokval(parser), "var"))
2955 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2957 else if (!strcmp(parser_tokval(parser), "noref"))
2959 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2966 if (!parser_next(parser))
2976 *is_static = had_static;
2980 parseerror(parser, "parse error after variable qualifier");
2985 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2986 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2989 char *label = nullptr;
2991 /* skip the 'while' and get the body */
2992 if (!parser_next(parser)) {
2993 if (OPTS_FLAG(LOOP_LABELS))
2994 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2996 parseerror(parser, "expected 'switch' operand in parenthesis");
3000 if (parser->tok == ':') {
3001 if (!OPTS_FLAG(LOOP_LABELS))
3002 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3003 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3004 parseerror(parser, "expected loop label");
3007 label = util_strdup(parser_tokval(parser));
3008 if (!parser_next(parser)) {
3010 parseerror(parser, "expected 'switch' operand in parenthesis");
3015 if (parser->tok != '(') {
3016 parseerror(parser, "expected 'switch' operand in parenthesis");
3020 parser->breaks.push_back(label);
3022 rv = parse_switch_go(parser, block, out);
3025 if (parser->breaks.back() != label) {
3026 parseerror(parser, "internal error: label stack corrupted");
3032 parser->breaks.pop_back();
3037 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3039 ast_expression *operand;
3042 ast_switch *switchnode;
3043 ast_switch_case swcase;
3046 bool noref, is_static;
3047 uint32_t qflags = 0;
3049 lex_ctx_t ctx = parser_ctx(parser);
3051 (void)block; /* not touching */
3054 /* parse into the expression */
3055 if (!parser_next(parser)) {
3056 parseerror(parser, "expected switch operand");
3059 /* parse the operand */
3060 operand = parse_expression_leave(parser, false, false, false);
3064 switchnode = new ast_switch(ctx, operand);
3067 if (parser->tok != ')') {
3069 parseerror(parser, "expected closing paren after 'switch' operand");
3073 /* parse over the opening paren */
3074 if (!parser_next(parser) || parser->tok != '{') {
3076 parseerror(parser, "expected list of cases");
3080 if (!parser_next(parser)) {
3082 parseerror(parser, "expected 'case' or 'default'");
3086 /* new block; allow some variables to be declared here */
3087 parser_enterblock(parser);
3090 if (parser->tok == TOKEN_IDENT)
3091 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3092 if (typevar || parser->tok == TOKEN_TYPENAME) {
3093 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3099 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3101 if (cvq == CV_WRONG) {
3105 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3115 while (parser->tok != '}') {
3116 ast_block *caseblock;
3118 if (!strcmp(parser_tokval(parser), "case")) {
3119 if (!parser_next(parser)) {
3121 parseerror(parser, "expected expression for case");
3124 swcase.m_value = parse_expression_leave(parser, false, false, false);
3125 if (!swcase.m_value) {
3127 parseerror(parser, "expected expression for case");
3130 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3131 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3132 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3138 else if (!strcmp(parser_tokval(parser), "default")) {
3139 swcase.m_value = nullptr;
3140 if (!parser_next(parser)) {
3142 parseerror(parser, "expected colon");
3148 parseerror(parser, "expected 'case' or 'default'");
3152 /* Now the colon and body */
3153 if (parser->tok != ':') {
3154 if (swcase.m_value) ast_unref(swcase.m_value);
3156 parseerror(parser, "expected colon");
3160 if (!parser_next(parser)) {
3161 if (swcase.m_value) ast_unref(swcase.m_value);
3163 parseerror(parser, "expected statements or case");
3166 caseblock = new ast_block(parser_ctx(parser));
3168 if (swcase.m_value) ast_unref(swcase.m_value);
3172 swcase.m_code = caseblock;
3173 switchnode->m_cases.push_back(swcase);
3175 ast_expression *expr;
3176 if (parser->tok == '}')
3178 if (parser->tok == TOKEN_KEYWORD) {
3179 if (!strcmp(parser_tokval(parser), "case") ||
3180 !strcmp(parser_tokval(parser), "default"))
3185 if (!parse_statement(parser, caseblock, &expr, true)) {
3191 if (!caseblock->addExpr(expr)) {
3198 parser_leaveblock(parser);
3201 if (parser->tok != '}') {
3203 parseerror(parser, "expected closing paren of case list");
3206 if (!parser_next(parser)) {
3208 parseerror(parser, "parse error after switch");
3215 /* parse computed goto sides */
3216 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3217 ast_expression *on_true;
3218 ast_expression *on_false;
3219 ast_expression *cond;
3224 if (ast_istype(*side, ast_ternary)) {
3225 ast_ternary *tern = (ast_ternary*)*side;
3226 on_true = parse_goto_computed(parser, &tern->m_on_true);
3227 on_false = parse_goto_computed(parser, &tern->m_on_false);
3229 if (!on_true || !on_false) {
3230 parseerror(parser, "expected label or expression in ternary");
3231 if (on_true) ast_unref(on_true);
3232 if (on_false) ast_unref(on_false);
3236 cond = tern->m_cond;
3237 tern->m_cond = nullptr;
3240 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3241 } else if (ast_istype(*side, ast_label)) {
3242 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3243 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3250 static bool parse_goto(parser_t *parser, ast_expression **out)
3252 ast_goto *gt = nullptr;
3253 ast_expression *lbl;
3255 if (!parser_next(parser))
3258 if (parser->tok != TOKEN_IDENT) {
3259 ast_expression *expression;
3261 /* could be an expression i.e computed goto :-) */
3262 if (parser->tok != '(') {
3263 parseerror(parser, "expected label name after `goto`");
3267 /* failed to parse expression for goto */
3268 if (!(expression = parse_expression(parser, false, true)) ||
3269 !(*out = parse_goto_computed(parser, &expression))) {
3270 parseerror(parser, "invalid goto expression");
3272 ast_unref(expression);
3279 /* not computed goto */
3280 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3281 lbl = parser_find_label(parser, gt->m_name);
3283 if (!ast_istype(lbl, ast_label)) {
3284 parseerror(parser, "internal error: label is not an ast_label");
3288 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3291 parser->gotos.push_back(gt);
3293 if (!parser_next(parser) || parser->tok != ';') {
3294 parseerror(parser, "semicolon expected after goto label");
3297 if (!parser_next(parser)) {
3298 parseerror(parser, "parse error after goto");
3306 static bool parse_skipwhite(parser_t *parser)
3309 if (!parser_next(parser))
3311 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3312 return parser->tok < TOKEN_ERROR;
3315 static bool parse_eol(parser_t *parser)
3317 if (!parse_skipwhite(parser))
3319 return parser->tok == TOKEN_EOL;
3322 static bool parse_pragma_do(parser_t *parser)
3324 if (!parser_next(parser) ||
3325 parser->tok != TOKEN_IDENT ||
3326 strcmp(parser_tokval(parser), "pragma"))
3328 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3331 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3332 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3336 if (!strcmp(parser_tokval(parser), "noref")) {
3337 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3338 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3341 parser->noref = !!parser_token(parser)->constval.i;
3342 if (!parse_eol(parser)) {
3343 parseerror(parser, "parse error after `noref` pragma");
3349 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3352 while (!parse_eol(parser)) {
3353 parser_next(parser);
3362 static bool parse_pragma(parser_t *parser)
3365 parser->lex->flags.preprocessing = true;
3366 parser->lex->flags.mergelines = true;
3367 rv = parse_pragma_do(parser);
3368 if (parser->tok != TOKEN_EOL) {
3369 parseerror(parser, "junk after pragma");
3372 parser->lex->flags.preprocessing = false;
3373 parser->lex->flags.mergelines = false;
3374 if (!parser_next(parser)) {
3375 parseerror(parser, "parse error after pragma");
3381 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3383 bool noref, is_static;
3385 uint32_t qflags = 0;
3386 ast_value *typevar = nullptr;
3387 char *vstring = nullptr;
3391 if (parser->tok == TOKEN_IDENT)
3392 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3394 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3396 /* local variable */
3398 parseerror(parser, "cannot declare a variable from here");
3401 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3402 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3405 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3409 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3411 if (cvq == CV_WRONG)
3413 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3415 else if (parser->tok == TOKEN_KEYWORD)
3417 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3422 if (!parser_next(parser)) {
3423 parseerror(parser, "parse error after __builtin_debug_printtype");
3427 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3429 ast_type_to_string(tdef, ty, sizeof(ty));
3430 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3431 if (!parser_next(parser)) {
3432 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3438 if (!parse_statement(parser, block, out, allow_cases))
3441 con_out("__builtin_debug_printtype: got no output node\n");
3444 ast_type_to_string(*out, ty, sizeof(ty));
3445 con_out("__builtin_debug_printtype: `%s`\n", ty);
3450 else if (!strcmp(parser_tokval(parser), "return"))
3452 return parse_return(parser, block, out);
3454 else if (!strcmp(parser_tokval(parser), "if"))
3456 return parse_if(parser, block, out);
3458 else if (!strcmp(parser_tokval(parser), "while"))
3460 return parse_while(parser, block, out);
3462 else if (!strcmp(parser_tokval(parser), "do"))
3464 return parse_dowhile(parser, block, out);
3466 else if (!strcmp(parser_tokval(parser), "for"))
3468 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3469 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3472 return parse_for(parser, block, out);
3474 else if (!strcmp(parser_tokval(parser), "break"))
3476 return parse_break_continue(parser, block, out, false);
3478 else if (!strcmp(parser_tokval(parser), "continue"))
3480 return parse_break_continue(parser, block, out, true);
3482 else if (!strcmp(parser_tokval(parser), "switch"))
3484 return parse_switch(parser, block, out);
3486 else if (!strcmp(parser_tokval(parser), "case") ||
3487 !strcmp(parser_tokval(parser), "default"))
3490 parseerror(parser, "unexpected 'case' label");
3495 else if (!strcmp(parser_tokval(parser), "goto"))
3497 return parse_goto(parser, out);
3499 else if (!strcmp(parser_tokval(parser), "typedef"))
3501 if (!parser_next(parser)) {
3502 parseerror(parser, "expected type definition after 'typedef'");
3505 return parse_typedef(parser);
3507 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3510 else if (parser->tok == '{')
3513 inner = parse_block(parser);
3519 else if (parser->tok == ':')
3523 if (!parser_next(parser)) {
3524 parseerror(parser, "expected label name");
3527 if (parser->tok != TOKEN_IDENT) {
3528 parseerror(parser, "label must be an identifier");
3531 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3533 if (!label->m_undefined) {
3534 parseerror(parser, "label `%s` already defined", label->m_name);
3537 label->m_undefined = false;
3540 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3541 parser->labels.push_back(label);
3544 if (!parser_next(parser)) {
3545 parseerror(parser, "parse error after label");
3548 for (i = 0; i < parser->gotos.size(); ++i) {
3549 if (parser->gotos[i]->m_name == label->m_name) {
3550 parser->gotos[i]->setLabel(label);
3551 parser->gotos.erase(parser->gotos.begin() + i);
3557 else if (parser->tok == ';')
3559 if (!parser_next(parser)) {
3560 parseerror(parser, "parse error after empty statement");
3567 lex_ctx_t ctx = parser_ctx(parser);
3568 ast_expression *exp = parse_expression(parser, false, false);
3572 if (!exp->m_side_effects) {
3573 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3580 static bool parse_enum(parser_t *parser)
3583 bool reverse = false;
3585 ast_value **values = nullptr;
3586 ast_value *var = nullptr;
3589 ast_expression *old;
3591 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3592 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3596 /* enumeration attributes (can add more later) */
3597 if (parser->tok == ':') {
3598 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3599 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3604 if (!strcmp(parser_tokval(parser), "flag")) {
3608 else if (!strcmp(parser_tokval(parser), "reverse")) {
3612 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3616 if (!parser_next(parser) || parser->tok != '{') {
3617 parseerror(parser, "expected `{` after enum attribute ");
3623 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3624 if (parser->tok == '}') {
3625 /* allow an empty enum */
3628 parseerror(parser, "expected identifier or `}`");
3632 old = parser_find_field(parser, parser_tokval(parser));
3634 old = parser_find_global(parser, parser_tokval(parser));
3636 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3637 parser_tokval(parser), old->m_context.file, old->m_context.line);
3641 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3642 vec_push(values, var);
3643 var->m_cvq = CV_CONST;
3644 var->m_hasvalue = true;
3646 /* for flagged enumerations increment in POTs of TWO */
3647 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3648 parser_addglobal(parser, var->m_name, var);
3650 if (!parser_next(parser)) {
3651 parseerror(parser, "expected `=`, `}` or comma after identifier");
3655 if (parser->tok == ',')
3657 if (parser->tok == '}')
3659 if (parser->tok != '=') {
3660 parseerror(parser, "expected `=`, `}` or comma after identifier");
3664 if (!parser_next(parser)) {
3665 parseerror(parser, "expected expression after `=`");
3669 /* We got a value! */
3670 old = parse_expression_leave(parser, true, false, false);
3671 asvalue = (ast_value*)old;
3672 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3673 compile_error(var->m_context, "constant value or expression expected");
3676 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3678 if (parser->tok == '}')
3680 if (parser->tok != ',') {
3681 parseerror(parser, "expected `}` or comma after expression");
3686 /* patch them all (for reversed attribute) */
3689 for (i = 0; i < vec_size(values); i++)
3690 values[i]->m_constval.vfloat = vec_size(values) - i - 1;
3693 if (parser->tok != '}') {
3694 parseerror(parser, "internal error: breaking without `}`");
3698 if (!parser_next(parser) || parser->tok != ';') {
3699 parseerror(parser, "expected semicolon after enumeration");
3703 if (!parser_next(parser)) {
3704 parseerror(parser, "parse error after enumeration");
3716 static bool parse_block_into(parser_t *parser, ast_block *block)
3720 parser_enterblock(parser);
3722 if (!parser_next(parser)) { /* skip the '{' */
3723 parseerror(parser, "expected function body");
3727 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3729 ast_expression *expr = nullptr;
3730 if (parser->tok == '}')
3733 if (!parse_statement(parser, block, &expr, false)) {
3734 /* parseerror(parser, "parse error"); */
3740 if (!block->addExpr(expr)) {
3747 if (parser->tok != '}') {
3750 (void)parser_next(parser);
3754 if (!parser_leaveblock(parser))
3756 return retval && !!block;
3759 static ast_block* parse_block(parser_t *parser)
3762 block = new ast_block(parser_ctx(parser));
3765 if (!parse_block_into(parser, block)) {
3772 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3774 if (parser->tok == '{') {
3775 *out = parse_block(parser);
3778 return parse_statement(parser, nullptr, out, false);
3781 static bool create_vector_members(ast_value *var, ast_member **me)
3784 size_t len = var->m_name.length();
3786 for (i = 0; i < 3; ++i) {
3787 char *name = (char*)mem_a(len+3);
3788 memcpy(name, var->m_name.c_str(), len);
3790 name[len+1] = 'x'+i;
3792 me[i] = ast_member::make(var->m_context, var, i, name);
3801 do { delete me[--i]; } while(i);
3805 static bool parse_function_body(parser_t *parser, ast_value *var)
3807 ast_block *block = nullptr;
3811 ast_expression *framenum = nullptr;
3812 ast_expression *nextthink = nullptr;
3813 /* None of the following have to be deleted */
3814 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3815 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3816 bool has_frame_think;
3820 has_frame_think = false;
3821 old = parser->function;
3823 if (var->m_flags & AST_FLAG_ALIAS) {
3824 parseerror(parser, "function aliases cannot have bodies");
3828 if (parser->gotos.size() || parser->labels.size()) {
3829 parseerror(parser, "gotos/labels leaking");
3833 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3834 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3835 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3841 if (parser->tok == '[') {
3842 /* got a frame definition: [ framenum, nextthink ]
3843 * this translates to:
3844 * self.frame = framenum;
3845 * self.nextthink = time + 0.1;
3846 * self.think = nextthink;
3848 nextthink = nullptr;
3850 fld_think = parser_find_field(parser, "think");
3851 fld_nextthink = parser_find_field(parser, "nextthink");
3852 fld_frame = parser_find_field(parser, "frame");
3853 if (!fld_think || !fld_nextthink || !fld_frame) {
3854 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3855 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3858 gbl_time = parser_find_global(parser, "time");
3859 gbl_self = parser_find_global(parser, "self");
3860 if (!gbl_time || !gbl_self) {
3861 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3862 parseerror(parser, "please declare the following globals: `time`, `self`");
3866 if (!parser_next(parser))
3869 framenum = parse_expression_leave(parser, true, false, false);
3871 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3874 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3875 ast_unref(framenum);
3876 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3880 if (parser->tok != ',') {
3881 ast_unref(framenum);
3882 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3883 parseerror(parser, "Got a %i\n", parser->tok);
3887 if (!parser_next(parser)) {
3888 ast_unref(framenum);
3892 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3894 /* qc allows the use of not-yet-declared functions here
3895 * - this automatically creates a prototype */
3896 ast_value *thinkfunc;
3897 ast_expression *functype = fld_think->m_next;
3899 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3900 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3901 ast_unref(framenum);
3902 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3905 thinkfunc->adoptType(*functype);
3907 if (!parser_next(parser)) {
3908 ast_unref(framenum);
3913 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3915 nextthink = thinkfunc;
3918 nextthink = parse_expression_leave(parser, true, false, false);
3920 ast_unref(framenum);
3921 parseerror(parser, "expected a think-function in [frame,think] notation");
3926 if (!ast_istype(nextthink, ast_value)) {
3927 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3931 if (retval && parser->tok != ']') {
3932 parseerror(parser, "expected closing `]` for [frame,think] notation");
3936 if (retval && !parser_next(parser)) {
3940 if (retval && parser->tok != '{') {
3941 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3946 ast_unref(nextthink);
3947 ast_unref(framenum);
3951 has_frame_think = true;
3954 block = new ast_block(parser_ctx(parser));
3956 parseerror(parser, "failed to allocate block");
3957 if (has_frame_think) {
3958 ast_unref(nextthink);
3959 ast_unref(framenum);
3964 if (has_frame_think) {
3965 if (!OPTS_FLAG(EMULATE_STATE)) {
3966 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
3967 if (!block->addExpr(state_op)) {
3968 parseerror(parser, "failed to generate state op for [frame,think]");
3969 ast_unref(nextthink);
3970 ast_unref(framenum);
3975 /* emulate OP_STATE in code: */
3977 ast_expression *self_frame;
3978 ast_expression *self_nextthink;
3979 ast_expression *self_think;
3980 ast_expression *time_plus_1;
3981 ast_store *store_frame;
3982 ast_store *store_nextthink;
3983 ast_store *store_think;
3985 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3987 ctx = parser_ctx(parser);
3988 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
3989 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
3990 self_think = new ast_entfield(ctx, gbl_self, fld_think);
3992 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
3993 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
3995 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3996 if (self_frame) delete self_frame;
3997 if (self_nextthink) delete self_nextthink;
3998 if (self_think) delete self_think;
3999 if (time_plus_1) delete time_plus_1;
4005 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4006 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4007 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4013 if (!store_nextthink) {
4014 delete self_nextthink;
4022 if (store_frame) delete store_frame;
4023 if (store_nextthink) delete store_nextthink;
4024 if (store_think) delete store_think;
4027 if (!block->addExpr(store_frame) ||
4028 !block->addExpr(store_nextthink) ||
4029 !block->addExpr(store_think))
4036 parseerror(parser, "failed to generate code for [frame,think]");
4037 ast_unref(nextthink);
4038 ast_unref(framenum);
4045 if (var->m_hasvalue) {
4046 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4047 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4051 func = var->m_constval.vfunc;
4054 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4059 func = ast_function::make(var->m_context, var->m_name, var);
4062 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4066 parser->functions.push_back(func);
4069 parser_enterblock(parser);
4071 for (auto &it : var->m_type_params) {
4075 if (it->m_vtype != TYPE_VECTOR &&
4076 (it->m_vtype != TYPE_FIELD ||
4077 it->m_next->m_vtype != TYPE_VECTOR))
4082 if (!create_vector_members(it.get(), me)) {
4087 for (e = 0; e < 3; ++e) {
4088 parser_addlocal(parser, me[e]->m_name, me[e]);
4089 block->collect(me[e]);
4093 if (var->m_argcounter && !func->m_argc) {
4094 ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT);
4095 parser_addlocal(parser, argc->m_name, argc);
4096 func->m_argc.reset(argc);
4099 if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4101 ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY);
4102 varargs->m_flags |= AST_FLAG_IS_VARARG;
4103 varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR);
4104 varargs->m_count = 0;
4105 util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str());
4106 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4111 util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str());
4112 if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4117 func->m_varargs.reset(varargs);
4118 func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4121 parser->function = func;
4122 if (!parse_block_into(parser, block)) {
4127 func->m_blocks.emplace_back(block);
4129 parser->function = old;
4130 if (!parser_leaveblock(parser))
4132 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4133 parseerror(parser, "internal error: local scopes left");
4137 if (parser->tok == ';')
4138 return parser_next(parser);
4139 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4140 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4144 (void)!parser_leaveblock(parser);
4145 parser->functions.pop_back();
4147 var->m_constval.vfunc = nullptr;
4150 parser->function = old;
4154 static ast_expression *array_accessor_split(
4159 ast_expression *left,
4160 ast_expression *right
4166 lex_ctx_t ctx = array->m_context;
4168 if (!left || !right) {
4169 if (left) delete left;
4170 if (right) delete right;
4174 cmp = new ast_binary(ctx, INSTR_LT,
4176 parser->m_fold.constgen_float(middle, false));
4180 parseerror(parser, "internal error: failed to create comparison for array setter");
4184 ifthen = new ast_ifthen(ctx, cmp, left, right);
4186 delete cmp; /* will delete left and right */
4187 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4194 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4196 lex_ctx_t ctx = array->m_context;
4198 if (from+1 == afterend) {
4199 /* set this value */
4202 ast_array_index *subscript;
4204 int assignop = type_store_instr[value->m_vtype];
4206 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4207 assignop = INSTR_STORE_V;
4209 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4213 st = new ast_store(ctx, assignop, subscript, value);
4219 block = new ast_block(ctx);
4225 if (!block->addExpr(st)) {
4230 ret = new ast_return(ctx, nullptr);
4236 if (!block->addExpr(ret)) {
4243 ast_expression *left, *right;
4244 size_t diff = afterend - from;
4245 size_t middle = from + diff/2;
4246 left = array_setter_node(parser, array, index, value, from, middle);
4247 right = array_setter_node(parser, array, index, value, middle, afterend);
4248 return array_accessor_split(parser, array, index, middle, left, right);
4252 static ast_expression *array_field_setter_node(
4261 lex_ctx_t ctx = array->m_context;
4263 if (from+1 == afterend) {
4264 /* set this value */
4267 ast_entfield *entfield;
4268 ast_array_index *subscript;
4270 int assignop = type_storep_instr[value->m_vtype];
4272 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4273 assignop = INSTR_STOREP_V;
4275 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4279 subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript);
4280 subscript->m_vtype = TYPE_FIELD;
4282 entfield = new ast_entfield(ctx, entity, subscript, subscript);
4288 st = new ast_store(ctx, assignop, entfield, value);
4294 block = new ast_block(ctx);
4300 if (!block->addExpr(st)) {
4305 ret = new ast_return(ctx, nullptr);
4311 if (!block->addExpr(ret)) {
4318 ast_expression *left, *right;
4319 size_t diff = afterend - from;
4320 size_t middle = from + diff/2;
4321 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4322 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4323 return array_accessor_split(parser, array, index, middle, left, right);
4327 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4329 lex_ctx_t ctx = array->m_context;
4331 if (from+1 == afterend) {
4333 ast_array_index *subscript;
4335 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4339 ret = new ast_return(ctx, subscript);
4347 ast_expression *left, *right;
4348 size_t diff = afterend - from;
4349 size_t middle = from + diff/2;
4350 left = array_getter_node(parser, array, index, from, middle);
4351 right = array_getter_node(parser, array, index, middle, afterend);
4352 return array_accessor_split(parser, array, index, middle, left, right);
4356 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4358 ast_function *func = nullptr;
4359 ast_value *fval = nullptr;
4360 ast_block *body = nullptr;
4362 fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION);
4364 parseerror(parser, "failed to create accessor function value");
4367 fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4369 func = ast_function::make(array->m_context, funcname, fval);
4372 parseerror(parser, "failed to create accessor function node");
4376 body = new ast_block(array->m_context);
4378 parseerror(parser, "failed to create block for array accessor");
4384 func->m_blocks.emplace_back(body);
4387 parser->accessors.push_back(fval);
4392 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4394 ast_value *index = nullptr;
4395 ast_value *value = nullptr;
4399 if (!ast_istype(array->m_next, ast_value)) {
4400 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4404 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4406 func = fval->m_constval.vfunc;
4407 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4409 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4410 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4412 if (!index || !value) {
4413 parseerror(parser, "failed to create locals for array accessor");
4416 value->m_name = "value"; // not important
4417 fval->m_type_params.emplace_back(index);
4418 fval->m_type_params.emplace_back(value);
4420 array->m_setter = fval;
4423 if (index) delete index;
4424 if (value) delete value;
4430 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4432 ast_expression *root = nullptr;
4433 root = array_setter_node(parser, array,
4434 array->m_setter->m_type_params[0].get(),
4435 array->m_setter->m_type_params[1].get(),
4438 parseerror(parser, "failed to build accessor search tree");
4441 if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4448 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4450 if (!parser_create_array_setter_proto(parser, array, funcname))
4452 return parser_create_array_setter_impl(parser, array);
4455 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4457 ast_expression *root = nullptr;
4458 ast_value *entity = nullptr;
4459 ast_value *index = nullptr;
4460 ast_value *value = nullptr;
4464 if (!ast_istype(array->m_next, ast_value)) {
4465 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4469 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4471 func = fval->m_constval.vfunc;
4472 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4474 entity = new ast_value(array->m_context, "entity", TYPE_ENTITY);
4475 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4476 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4477 if (!entity || !index || !value) {
4478 parseerror(parser, "failed to create locals for array accessor");
4481 value->m_name = "value"; // not important
4482 fval->m_type_params.emplace_back(entity);
4483 fval->m_type_params.emplace_back(index);
4484 fval->m_type_params.emplace_back(value);
4486 root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4488 parseerror(parser, "failed to build accessor search tree");
4492 array->m_setter = fval;
4493 return func->m_blocks[0].get()->addExpr(root);
4495 if (entity) delete entity;
4496 if (index) delete index;
4497 if (value) delete value;
4498 if (root) delete root;
4504 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4506 ast_value *index = nullptr;
4510 /* NOTE: checking array->m_next rather than elemtype since
4511 * for fields elemtype is a temporary fieldtype.
4513 if (!ast_istype(array->m_next, ast_value)) {
4514 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4518 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4520 func = fval->m_constval.vfunc;
4521 fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype);
4523 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4526 parseerror(parser, "failed to create locals for array accessor");
4529 fval->m_type_params.emplace_back(index);
4531 array->m_getter = fval;
4534 if (index) delete index;
4540 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4542 ast_expression *root = nullptr;
4544 root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count);
4546 parseerror(parser, "failed to build accessor search tree");
4549 if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4556 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4558 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4560 return parser_create_array_getter_impl(parser, array);
4563 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4565 lex_ctx_t ctx = parser_ctx(parser);
4566 std::vector<std::unique_ptr<ast_value>> params;
4569 bool variadic = false;
4570 ast_value *varparam = nullptr;
4571 char *argcounter = nullptr;
4573 /* for the sake of less code we parse-in in this function */
4574 if (!parser_next(parser)) {
4576 parseerror(parser, "expected parameter list");
4580 /* parse variables until we hit a closing paren */
4581 while (parser->tok != ')') {
4582 bool is_varargs = false;
4585 /* there must be commas between them */
4586 if (parser->tok != ',') {
4587 parseerror(parser, "expected comma or end of parameter list");
4590 if (!parser_next(parser)) {
4591 parseerror(parser, "expected parameter");
4597 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4598 if (!param && !is_varargs)
4601 /* '...' indicates a varargs function */
4603 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4604 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4607 if (parser->tok == TOKEN_IDENT) {
4608 argcounter = util_strdup(parser_tokval(parser));
4609 if (!parser_next(parser) || parser->tok != ')') {
4610 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4615 params.emplace_back(param);
4616 if (param->m_vtype >= TYPE_VARIANT) {
4617 char tname[1024]; /* typename is reserved in C++ */
4618 ast_type_to_string(param, tname, sizeof(tname));
4619 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4622 /* type-restricted varargs */
4623 if (parser->tok == TOKEN_DOTS) {
4625 varparam = params.back().release();
4627 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4628 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4631 if (parser->tok == TOKEN_IDENT) {
4632 argcounter = util_strdup(parser_tokval(parser));
4633 param->m_name = argcounter;
4634 if (!parser_next(parser) || parser->tok != ')') {
4635 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4640 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4641 parseerror(parser, "parameter name omitted");
4647 if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4651 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4652 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4655 if (!parser_next(parser)) {
4656 parseerror(parser, "parse error after typename");
4660 /* now turn 'var' into a function type */
4661 fval = new ast_value(ctx, "<type()>", TYPE_FUNCTION);
4664 fval->m_flags |= AST_FLAG_VARIADIC;
4667 var->m_type_params = move(params);
4668 var->m_varparam = varparam;
4669 var->m_argcounter = argcounter;
4682 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4684 ast_expression *cexp;
4685 ast_value *cval, *tmp;
4688 ctx = parser_ctx(parser);
4690 if (!parser_next(parser)) {
4692 parseerror(parser, "expected array-size");
4696 if (parser->tok != ']') {
4697 cexp = parse_expression_leave(parser, true, false, false);
4699 if (!cexp || !ast_istype(cexp, ast_value)) {
4703 parseerror(parser, "expected array-size as constant positive integer");
4706 cval = (ast_value*)cexp;
4713 tmp = new ast_value(ctx, "<type[]>", TYPE_ARRAY);
4718 if (cval->m_vtype == TYPE_INTEGER)
4719 tmp->m_count = cval->m_constval.vint;
4720 else if (cval->m_vtype == TYPE_FLOAT)
4721 tmp->m_count = cval->m_constval.vfloat;
4725 parseerror(parser, "array-size must be a positive integer constant");
4732 var->m_flags |= AST_FLAG_ARRAY_INIT;
4735 if (parser->tok != ']') {
4737 parseerror(parser, "expected ']' after array-size");
4740 if (!parser_next(parser)) {
4742 parseerror(parser, "error after parsing array size");
4748 /* Parse a complete typename.
4749 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4750 * but when parsing variables separated by comma
4751 * 'storebase' should point to where the base-type should be kept.
4752 * The base type makes up every bit of type information which comes *before* the
4755 * NOTE: The value must either be named, have a nullptr name, or a name starting
4756 * with '<'. In the first case, this will be the actual variable or type
4757 * name, in the other cases it is assumed that the name will appear
4758 * later, and an error is generated otherwise.
4760 * The following will be parsed in its entirety:
4762 * The 'basetype' in this case is 'void()'
4763 * and if there's a comma after it, say:
4765 * then the type-information 'void()' can be stored in 'storebase'
4767 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4769 ast_value *var, *tmp;
4772 const char *name = nullptr;
4773 bool isfield = false;
4774 bool wasarray = false;
4775 size_t morefields = 0;
4777 bool vararg = (parser->tok == TOKEN_DOTS);
4779 ctx = parser_ctx(parser);
4781 /* types may start with a dot */
4782 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4784 if (parser->tok == TOKEN_DOTS)
4786 /* if we parsed a dot we need a typename now */
4787 if (!parser_next(parser)) {
4788 parseerror(parser, "expected typename for field definition");
4792 /* Further dots are handled seperately because they won't be part of the
4796 if (parser->tok == '.')
4798 else if (parser->tok == TOKEN_DOTS)
4803 if (!parser_next(parser)) {
4804 parseerror(parser, "expected typename for field definition");
4809 if (parser->tok == TOKEN_IDENT)
4810 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4811 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4812 if (vararg && is_vararg) {
4816 parseerror(parser, "expected typename");
4820 /* generate the basic type value */
4821 if (cached_typedef) {
4822 var = new ast_value(ast_copy_type, *cached_typedef);
4823 var->m_name = "<type(from_def)>";
4825 var = new ast_value(ctx, "<type>", parser_token(parser)->constval.t);
4827 for (; morefields; --morefields) {
4828 tmp = new ast_value(ctx, "<.type>", TYPE_FIELD);
4833 /* do not yet turn into a field - remember:
4834 * .void() foo; is a field too
4835 * .void()() foo; is a function
4839 if (!parser_next(parser)) {
4841 parseerror(parser, "parse error after typename");
4845 /* an opening paren now starts the parameter-list of a function
4846 * this is where original-QC has parameter lists.
4847 * We allow a single parameter list here.
4848 * Much like fteqcc we don't allow `float()() x`
4850 if (parser->tok == '(') {
4851 var = parse_parameter_list(parser, var);
4856 /* store the base if requested */
4858 *storebase = new ast_value(ast_copy_type, *var);
4860 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4861 tmp->m_next = *storebase;
4866 /* there may be a name now */
4867 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4868 if (!strcmp(parser_tokval(parser), "break"))
4869 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4870 else if (parser->tok == TOKEN_KEYWORD)
4873 name = util_strdup(parser_tokval(parser));
4876 if (!parser_next(parser)) {
4879 parseerror(parser, "error after variable or field declaration");
4885 /* now this may be an array */
4886 if (parser->tok == '[') {
4888 var = parse_arraysize(parser, var);
4890 if (name) mem_d(name);
4895 /* This is the point where we can turn it into a field */
4897 /* turn it into a field if desired */
4898 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4903 /* now there may be function parens again */
4904 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4905 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4906 if (parser->tok == '(' && wasarray)
4907 parseerror(parser, "arrays as part of a return type is not supported");
4908 while (parser->tok == '(') {
4909 var = parse_parameter_list(parser, var);
4911 if (name) mem_d(name);
4916 /* finally name it */
4919 // free the name, ast_value_set_name duplicates
4926 static bool parse_typedef(parser_t *parser)
4928 ast_value *typevar, *oldtype;
4929 ast_expression *old;
4931 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4936 // while parsing types, the ast_value's get named '<something>'
4937 if (!typevar->m_name.length() || typevar->m_name[0] == '<') {
4938 parseerror(parser, "missing name in typedef");
4943 if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4944 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4945 " -> `%s` has been declared here: %s:%i",
4946 typevar->m_name, old->m_context.file, old->m_context.line);
4951 if ( (oldtype = parser_find_typedef(parser, typevar->m_name, vec_last(parser->_blocktypedefs))) ) {
4952 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4953 typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
4958 vec_push(parser->_typedefs, typevar);
4959 util_htset(vec_last(parser->typedefs), typevar->m_name.c_str(), typevar);
4961 if (parser->tok != ';') {
4962 parseerror(parser, "expected semicolon after typedef");
4965 if (!parser_next(parser)) {
4966 parseerror(parser, "parse error after typedef");
4973 static const char *cvq_to_str(int cvq) {
4975 case CV_NONE: return "none";
4976 case CV_VAR: return "`var`";
4977 case CV_CONST: return "`const`";
4978 default: return "<INVALID>";
4982 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4985 if (proto->m_cvq != var->m_cvq) {
4986 if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
4987 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4988 parser->tok == '='))
4990 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4991 "`%s` declared with different qualifiers: %s\n"
4992 " -> previous declaration here: %s:%i uses %s",
4993 var->m_name, cvq_to_str(var->m_cvq),
4994 proto->m_context.file, proto->m_context.line,
4995 cvq_to_str(proto->m_cvq));
4998 av = (var ->m_flags & AST_FLAG_NORETURN);
4999 ao = (proto->m_flags & AST_FLAG_NORETURN);
5001 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5002 "`%s` declared with different attributes%s\n"
5003 " -> previous declaration here: %s:%i",
5004 var->m_name, (av ? ": noreturn" : ""),
5005 proto->m_context.file, proto->m_context.line,
5006 (ao ? ": noreturn" : ""));
5011 static bool create_array_accessors(parser_t *parser, ast_value *var)
5014 util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str());
5015 if (!parser_create_array_setter(parser, var, name))
5017 util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str());
5018 if (!parser_create_array_getter(parser, var, var->m_next, name))
5023 static bool parse_array(parser_t *parser, ast_value *array)
5026 if (array->m_initlist.size()) {
5027 parseerror(parser, "array already initialized elsewhere");
5030 if (!parser_next(parser)) {
5031 parseerror(parser, "parse error in array initializer");
5035 while (parser->tok != '}') {
5036 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5039 if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5041 parseerror(parser, "initializing element must be a compile time constant");
5044 array->m_initlist.push_back(v->m_constval);
5045 if (v->m_vtype == TYPE_STRING) {
5046 array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5050 if (parser->tok == '}')
5052 if (parser->tok != ',' || !parser_next(parser)) {
5053 parseerror(parser, "expected comma or '}' in element list");
5057 if (!parser_next(parser) || parser->tok != ';') {
5058 parseerror(parser, "expected semicolon after initializer, got %s");
5062 if (!parser_next(parser)) {
5063 parseerror(parser, "parse error after initializer");
5068 if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5069 if (array->m_count != (size_t)-1) {
5070 parseerror(parser, "array `%s' has already been initialized with %u elements",
5071 array->m_name, (unsigned)array->m_count);
5073 array->m_count = array->m_initlist.size();
5074 if (!create_array_accessors(parser, array))
5080 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)
5084 ast_expression *old;
5088 ast_value *basetype = nullptr;
5090 bool isparam = false;
5091 bool isvector = false;
5092 bool cleanvar = true;
5093 bool wasarray = false;
5095 ast_member *me[3] = { nullptr, nullptr, nullptr };
5096 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5098 if (!localblock && is_static)
5099 parseerror(parser, "`static` qualifier is not supported in global scope");
5101 /* get the first complete variable */
5102 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5109 /* while parsing types, the ast_value's get named '<something>' */
5110 if (!var->m_name.length() || var->m_name[0] == '<') {
5111 parseerror(parser, "declaration does not declare anything");
5121 /* Part 0: finish the type */
5122 if (parser->tok == '(') {
5123 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5124 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5125 var = parse_parameter_list(parser, var);
5131 /* we only allow 1-dimensional arrays */
5132 if (parser->tok == '[') {
5134 var = parse_arraysize(parser, var);
5140 if (parser->tok == '(' && wasarray) {
5141 parseerror(parser, "arrays as part of a return type is not supported");
5142 /* we'll still parse the type completely for now */
5144 /* for functions returning functions */
5145 while (parser->tok == '(') {
5146 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5147 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5148 var = parse_parameter_list(parser, var);
5155 var->m_cvq = qualifier;
5156 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5157 var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5158 var->m_flags |= qflags;
5161 * store the vstring back to var for alias and
5162 * deprecation messages.
5164 if (var->m_flags & AST_FLAG_DEPRECATED ||
5165 var->m_flags & AST_FLAG_ALIAS)
5166 var->m_desc = vstring;
5168 if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5169 parseerror(parser, "function aliases cannot be forward declared");
5176 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5177 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5178 * is then filled with the previous definition and the parameter-names replaced.
5180 if (var->m_name == "nil") {
5181 if (OPTS_FLAG(UNTYPED_NIL)) {
5182 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5183 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5185 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5188 /* Deal with end_sys_ vars */
5190 if (var->m_name == "end_sys_globals") {
5192 parser->crc_globals = parser->globals.size();
5195 else if (var->m_name == "end_sys_fields") {
5197 parser->crc_fields = parser->fields.size();
5200 if (was_end && var->m_vtype == TYPE_FIELD) {
5201 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5202 "global '%s' hint should not be a field",
5203 parser_tokval(parser)))
5210 if (!nofields && var->m_vtype == TYPE_FIELD)
5212 /* deal with field declarations */
5213 old = parser_find_field(parser, var->m_name);
5215 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5216 var->m_name, old->m_context.file, (int)old->m_context.line))
5225 parseerror(parser, "field `%s` already declared here: %s:%i",
5226 var->m_name, old->m_context.file, old->m_context.line);
5231 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5232 (old = parser_find_global(parser, var->m_name)))
5234 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5235 parseerror(parser, "field `%s` already declared here: %s:%i",
5236 var->m_name, old->m_context.file, old->m_context.line);
5243 /* deal with other globals */
5244 old = parser_find_global(parser, var->m_name);
5245 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5247 /* This is a function which had a prototype */
5248 if (!ast_istype(old, ast_value)) {
5249 parseerror(parser, "internal error: prototype is not an ast_value");
5253 proto = (ast_value*)old;
5254 proto->m_desc = var->m_desc;
5255 if (!proto->compareType(*var)) {
5256 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5258 proto->m_context.file, proto->m_context.line);
5262 /* we need the new parameter-names */
5263 for (i = 0; i < proto->m_type_params.size(); ++i)
5264 proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name;
5265 if (!parser_check_qualifiers(parser, var, proto)) {
5270 proto->m_flags |= var->m_flags;
5278 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5279 "global `%s` already declared here: %s:%i",
5280 var->m_name, old->m_context.file, old->m_context.line))
5285 if (old->m_flags & AST_FLAG_FINAL_DECL) {
5286 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5287 var->m_name, old->m_context.file, old->m_context.line);
5291 proto = (ast_value*)old;
5292 if (!ast_istype(old, ast_value)) {
5293 parseerror(parser, "internal error: not an ast_value");
5298 if (!parser_check_qualifiers(parser, var, proto)) {
5303 proto->m_flags |= var->m_flags;
5304 /* copy the context for finals,
5305 * so the error can show where it was actually made 'final'
5307 if (proto->m_flags & AST_FLAG_FINAL_DECL)
5308 old->m_context = var->m_context;
5312 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5313 (old = parser_find_field(parser, var->m_name)))
5315 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5316 parseerror(parser, "global `%s` already declared here: %s:%i",
5317 var->m_name, old->m_context.file, old->m_context.line);
5324 else /* it's not a global */
5326 old = parser_find_local(parser, var->m_name, vec_size(parser->variables)-1, &isparam);
5327 if (old && !isparam) {
5328 parseerror(parser, "local `%s` already declared here: %s:%i",
5329 var->m_name, old->m_context.file, (int)old->m_context.line);
5333 /* doing this here as the above is just for a single scope */
5334 old = parser_find_local(parser, var->m_name, 0, &isparam);
5335 if (old && isparam) {
5336 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5337 "local `%s` is shadowing a parameter", var->m_name))
5339 parseerror(parser, "local `%s` already declared here: %s:%i",
5340 var->m_name, old->m_context.file, (int)old->m_context.line);
5344 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5346 if (ast_istype(old, ast_value))
5347 var = proto = (ast_value*)old;
5356 /* in a noref section we simply bump the usecount */
5357 if (noref || parser->noref)
5361 * Create the global/local, and deal with vector types.
5364 if (var->m_vtype == TYPE_VECTOR)
5366 else if (var->m_vtype == TYPE_FIELD &&
5367 var->m_next->m_vtype == TYPE_VECTOR)
5371 if (!create_vector_members(var, me)) {
5378 /* deal with global variables, fields, functions */
5379 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5380 var->m_isfield = true;
5381 parser->fields.push_back(var);
5382 util_htset(parser->htfields, var->m_name.c_str(), var);
5384 for (i = 0; i < 3; ++i) {
5385 parser->fields.push_back(me[i]);
5386 util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]);
5391 if (!(var->m_flags & AST_FLAG_ALIAS)) {
5392 parser_addglobal(parser, var->m_name, var);
5394 for (i = 0; i < 3; ++i) {
5395 parser_addglobal(parser, me[i]->m_name.c_str(), me[i]);
5399 ast_expression *find = parser_find_global(parser, var->m_desc);
5402 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5406 if (!var->compareType(*find)) {
5410 ast_type_to_string(find, ty1, sizeof(ty1));
5411 ast_type_to_string(var, ty2, sizeof(ty2));
5413 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5414 ty1, ty2, var->m_name
5419 util_htset(parser->aliases, var->m_name.c_str(), find);
5421 /* generate aliases for vector components */
5425 util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str());
5426 util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str());
5427 util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str());
5429 util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0]));
5430 util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1]));
5431 util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2]));
5441 // a static adds itself to be generated like any other global
5442 // but is added to the local namespace instead
5443 std::string defname;
5447 defname = parser->function->m_name;
5448 defname.append(2, ':');
5450 // remember the length up to here
5451 prefix_len = defname.length();
5453 // Add it to the local scope
5454 util_htset(vec_last(parser->variables), var->m_name.c_str(), (void*)var);
5456 // now rename the global
5457 defname.append(var->m_name);
5458 // if a variable of that name already existed, add the
5460 // The counter is incremented either way.
5461 sn_size = parser->function->m_static_names.size();
5462 for (sn = 0; sn != sn_size; ++sn) {
5463 if (parser->function->m_static_names[sn] == var->m_name.c_str())
5466 if (sn != sn_size) {
5467 char *num = nullptr;
5468 int len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5469 defname.append(num, 0, len);
5473 parser->function->m_static_names.emplace_back(var->m_name);
5474 parser->function->m_static_count++;
5475 var->m_name = defname;
5477 // push it to the to-be-generated globals
5478 parser->globals.push_back(var);
5480 // same game for the vector members
5482 defname.erase(prefix_len);
5483 for (i = 0; i < 3; ++i) {
5484 util_htset(vec_last(parser->variables), me[i]->m_name.c_str(), (void*)(me[i]));
5485 me[i]->m_name = move(defname + me[i]->m_name);
5486 parser->globals.push_back(me[i]);
5490 localblock->m_locals.push_back(var);
5491 parser_addlocal(parser, var->m_name, var);
5493 for (i = 0; i < 3; ++i) {
5494 parser_addlocal(parser, me[i]->m_name, me[i]);
5495 localblock->collect(me[i]);
5501 memcpy(last_me, me, sizeof(me));
5502 me[0] = me[1] = me[2] = nullptr;
5507 if (var->m_vtype == TYPE_ARRAY) {
5508 if (var->m_count != (size_t)-1) {
5509 if (!create_array_accessors(parser, var))
5513 else if (!localblock && !nofields &&
5514 var->m_vtype == TYPE_FIELD &&
5515 var->m_next->m_vtype == TYPE_ARRAY)
5518 ast_expression *telem;
5520 ast_value *array = (ast_value*)var->m_next;
5522 if (!ast_istype(var->m_next, ast_value)) {
5523 parseerror(parser, "internal error: field element type must be an ast_value");
5527 util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str());
5528 if (!parser_create_array_field_setter(parser, array, name))
5531 telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next);
5532 tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD);
5533 tfield->m_next = telem;
5534 util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str());
5535 if (!parser_create_array_getter(parser, array, tfield, name)) {
5543 if (parser->tok == ';') {
5545 if (!parser_next(parser)) {
5546 parseerror(parser, "error after variable declaration");
5552 if (parser->tok == ',')
5556 if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5559 parseerror(parser, "missing comma or semicolon while parsing variables");
5563 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5564 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5565 "initializing expression turns variable `%s` into a constant in this standard",
5572 if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) {
5573 if (parser->tok != '=') {
5574 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5578 if (!parser_next(parser)) {
5579 parseerror(parser, "error parsing initializer");
5583 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5584 parseerror(parser, "expected '=' before function body in this standard");
5587 if (parser->tok == '#') {
5588 ast_function *func = nullptr;
5589 ast_value *number = nullptr;
5595 parseerror(parser, "cannot declare builtins within functions");
5598 if (var->m_vtype != TYPE_FUNCTION) {
5599 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5602 if (!parser_next(parser)) {
5603 parseerror(parser, "expected builtin number");
5607 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5608 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5610 parseerror(parser, "builtin number expected");
5613 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5616 parseerror(parser, "builtin number must be a compile time constant");
5619 if (number->m_vtype == TYPE_INTEGER)
5620 builtin_num = number->m_constval.vint;
5621 else if (number->m_vtype == TYPE_FLOAT)
5622 builtin_num = number->m_constval.vfloat;
5625 parseerror(parser, "builtin number must be an integer constant");
5630 fractional = modff(builtin_num, &integral);
5631 if (builtin_num < 0 || fractional != 0) {
5632 parseerror(parser, "builtin number must be an integer greater than zero");
5636 /* we only want the integral part anyways */
5637 builtin_num = integral;
5638 } else if (parser->tok == TOKEN_INTCONST) {
5639 builtin_num = parser_token(parser)->constval.i;
5641 parseerror(parser, "builtin number must be a compile time constant");
5645 if (var->m_hasvalue) {
5646 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5647 "builtin `%s` has already been defined\n"
5648 " -> previous declaration here: %s:%i",
5649 var->m_name, var->m_context.file, (int)var->m_context.line);
5653 func = ast_function::make(var->m_context, var->m_name, var);
5655 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5658 parser->functions.push_back(func);
5660 func->m_builtin = -builtin_num-1;
5663 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5664 ? (parser->tok != ',' && parser->tok != ';')
5665 : (!parser_next(parser)))
5667 parseerror(parser, "expected comma or semicolon");
5669 var->m_constval.vfunc = nullptr;
5673 else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5676 /* Note that fteqcc and most others don't even *have*
5677 * local arrays, so this is not a high priority.
5679 parseerror(parser, "TODO: initializers for local arrays");
5683 var->m_hasvalue = true;
5684 if (!parse_array(parser, var))
5687 else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5690 parseerror(parser, "cannot declare functions within functions");
5695 proto->m_context = parser_ctx(parser);
5697 if (!parse_function_body(parser, var))
5700 for (auto &it : parser->gotos)
5701 parseerror(parser, "undefined label: `%s`", it->m_name);
5702 parser->gotos.clear();
5703 parser->labels.clear();
5706 ast_expression *cexp;
5708 bool folded_const = false;
5710 cexp = parse_expression_leave(parser, true, false, false);
5713 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5715 /* deal with foldable constants: */
5717 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5719 /* remove it from the current locals */
5721 for (i = 0; i < 3; ++i) {
5722 vec_pop(parser->_locals);
5723 localblock->m_collect.pop_back();
5726 /* do sanity checking, this function really needs refactoring */
5727 if (vec_last(parser->_locals) != var)
5728 parseerror(parser, "internal error: unexpected change in local variable handling");
5730 vec_pop(parser->_locals);
5731 if (localblock->m_locals.back() != var)
5732 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5734 localblock->m_locals.pop_back();
5735 /* push it to the to-be-generated globals */
5736 parser->globals.push_back(var);
5738 for (i = 0; i < 3; ++i)
5739 parser->globals.push_back(last_me[i]);
5740 folded_const = true;
5743 if (folded_const || !localblock || is_static) {
5744 if (cval != parser->nil &&
5745 (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5748 parseerror(parser, "initializer is non constant");
5753 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5754 qualifier != CV_VAR)
5756 var->m_cvq = CV_CONST;
5758 if (cval == parser->nil)
5759 var->m_flags |= AST_FLAG_INITIALIZED;
5762 var->m_hasvalue = true;
5763 if (cval->m_vtype == TYPE_STRING)
5764 var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5765 else if (cval->m_vtype == TYPE_FIELD)
5766 var->m_constval.vfield = cval;
5768 memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5776 var->m_cvq = CV_NONE;
5777 sy.out.push_back(syexp(var->m_context, var));
5778 sy.out.push_back(syexp(cexp->m_context, cexp));
5779 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5780 if (!parser_sy_apply_operator(parser, &sy))
5783 if (sy.out.size() != 1 && sy.ops.size() != 0)
5784 parseerror(parser, "internal error: leaked operands");
5785 if (!localblock->addExpr(sy.out[0].out))
5790 /* a constant initialized to an inexact value should be marked inexact:
5791 * const float x = <inexact>; should propagate the inexact flag
5793 if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5794 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5795 var->m_inexact = cval->m_inexact;
5800 if (parser->tok == ',') {
5801 if (!parser_next(parser)) {
5802 parseerror(parser, "expected another variable");
5806 if (parser->tok != TOKEN_IDENT) {
5807 parseerror(parser, "expected another variable");
5810 var = new ast_value(ast_copy_type, *basetype);
5812 var->m_name = parser_tokval(parser);
5813 if (!parser_next(parser)) {
5814 parseerror(parser, "error parsing variable declaration");
5820 if (parser->tok != ';') {
5821 parseerror(parser, "missing semicolon after variables");
5825 if (!parser_next(parser)) {
5826 parseerror(parser, "parse error after variable declaration");
5834 if (cleanvar && var)
5841 if (cleanvar && var)
5849 static bool parser_global_statement(parser_t *parser)
5853 bool is_static = false;
5854 uint32_t qflags = 0;
5855 ast_value *istype = nullptr;
5856 char *vstring = nullptr;
5858 if (parser->tok == TOKEN_IDENT)
5859 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5861 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5863 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5865 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5867 if (cvq == CV_WRONG)
5869 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5871 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5873 return parse_enum(parser);
5875 else if (parser->tok == TOKEN_KEYWORD)
5877 if (!strcmp(parser_tokval(parser), "typedef")) {
5878 if (!parser_next(parser)) {
5879 parseerror(parser, "expected type definition after 'typedef'");
5882 return parse_typedef(parser);
5884 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5887 else if (parser->tok == '#')
5889 return parse_pragma(parser);
5891 else if (parser->tok == '$')
5893 if (!parser_next(parser)) {
5894 parseerror(parser, "parse error");
5900 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5906 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5908 return util_crc16(old, str, strlen(str));
5911 static void progdefs_crc_file(const char *str)
5913 /* write to progdefs.h here */
5917 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5919 old = progdefs_crc_sum(old, str);
5920 progdefs_crc_file(str);
5924 static void generate_checksum(parser_t *parser, ir_builder *ir)
5926 uint16_t crc = 0xFFFF;
5930 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5931 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5933 progdefs_crc_file("\tint\tpad;\n");
5934 progdefs_crc_file("\tint\tofs_return[3];\n");
5935 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5936 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5937 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5938 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5939 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5940 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5941 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5942 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5944 for (i = 0; i < parser->crc_globals; ++i) {
5945 if (!ast_istype(parser->globals[i], ast_value))
5947 value = (ast_value*)(parser->globals[i]);
5948 switch (value->m_vtype) {
5949 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5950 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5951 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5952 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5954 crc = progdefs_crc_both(crc, "\tint\t");
5957 crc = progdefs_crc_both(crc, value->m_name.c_str());
5958 crc = progdefs_crc_both(crc, ";\n");
5960 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5961 for (i = 0; i < parser->crc_fields; ++i) {
5962 if (!ast_istype(parser->fields[i], ast_value))
5964 value = (ast_value*)(parser->fields[i]);
5965 switch (value->m_next->m_vtype) {
5966 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5967 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5968 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5969 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5971 crc = progdefs_crc_both(crc, "\tint\t");
5974 crc = progdefs_crc_both(crc, value->m_name.c_str());
5975 crc = progdefs_crc_both(crc, ";\n");
5977 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5978 ir->m_code->crc = crc;
5981 parser_t *parser_create()
5984 lex_ctx_t empty_ctx;
5987 parser = (parser_t*)mem_a(sizeof(parser_t));
5991 memset(parser, 0, sizeof(*parser));
5994 new (parser) parser_t();
5996 for (i = 0; i < operator_count; ++i) {
5997 if (operators[i].id == opid1('=')) {
5998 parser->assign_op = operators+i;
6002 if (!parser->assign_op) {
6003 con_err("internal error: initializing parser: failed to find assign operator\n");
6008 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6009 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6010 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6011 vec_push(parser->_blocktypedefs, 0);
6013 parser->aliases = util_htnew(PARSER_HT_SIZE);
6015 empty_ctx.file = "<internal>";
6017 empty_ctx.column = 0;
6018 parser->nil = new ast_value(empty_ctx, "nil", TYPE_NIL);
6019 parser->nil->m_cvq = CV_CONST;
6020 if (OPTS_FLAG(UNTYPED_NIL))
6021 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6023 parser->max_param_count = 1;
6025 parser->const_vec[0] = new ast_value(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6026 parser->const_vec[1] = new ast_value(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6027 parser->const_vec[2] = new ast_value(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6029 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6030 parser->reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING);
6031 parser->reserved_version->m_cvq = CV_CONST;
6032 parser->reserved_version->m_hasvalue = true;
6033 parser->reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6034 parser->reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6036 parser->reserved_version = nullptr;
6039 parser->m_fold = fold(parser);
6040 parser->m_intrin = intrin(parser);
6044 static bool parser_compile(parser_t *parser)
6046 /* initial lexer/parser state */
6047 parser->lex->flags.noops = true;
6049 if (parser_next(parser))
6051 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6053 if (!parser_global_statement(parser)) {
6054 if (parser->tok == TOKEN_EOF)
6055 parseerror(parser, "unexpected end of file");
6056 else if (compile_errors)
6057 parseerror(parser, "there have been errors, bailing out");
6058 lex_close(parser->lex);
6059 parser->lex = nullptr;
6064 parseerror(parser, "parse error");
6065 lex_close(parser->lex);
6066 parser->lex = nullptr;
6070 lex_close(parser->lex);
6071 parser->lex = nullptr;
6073 return !compile_errors;
6076 bool parser_compile_file(parser_t *parser, const char *filename)
6078 parser->lex = lex_open(filename);
6080 con_err("failed to open file \"%s\"\n", filename);
6083 return parser_compile(parser);
6086 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6088 parser->lex = lex_open_string(str, len, name);
6090 con_err("failed to create lexer for string \"%s\"\n", name);
6093 return parser_compile(parser);
6096 static void parser_remove_ast(parser_t *parser)
6099 if (parser->ast_cleaned)
6101 parser->ast_cleaned = true;
6102 for (auto &it : parser->accessors) {
6103 delete it->m_constval.vfunc;
6104 it->m_constval.vfunc = nullptr;
6107 for (auto &it : parser->functions) delete it;
6108 for (auto &it : parser->globals) delete it;
6109 for (auto &it : parser->fields) delete it;
6111 for (i = 0; i < vec_size(parser->variables); ++i)
6112 util_htdel(parser->variables[i]);
6113 vec_free(parser->variables);
6114 vec_free(parser->_blocklocals);
6115 vec_free(parser->_locals);
6117 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6118 delete parser->_typedefs[i];
6119 vec_free(parser->_typedefs);
6120 for (i = 0; i < vec_size(parser->typedefs); ++i)
6121 util_htdel(parser->typedefs[i]);
6122 vec_free(parser->typedefs);
6123 vec_free(parser->_blocktypedefs);
6125 vec_free(parser->_block_ctx);
6129 delete parser->const_vec[0];
6130 delete parser->const_vec[1];
6131 delete parser->const_vec[2];
6133 if (parser->reserved_version)
6134 delete parser->reserved_version;
6136 util_htdel(parser->aliases);
6139 void parser_cleanup(parser_t *parser)
6141 parser_remove_ast(parser);
6142 parser->~parser_t();
6146 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6147 ast_expression *expr;
6151 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6155 for (auto &it : parser->functions) {
6156 if (it->m_name == "coverage") {
6162 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6163 con_out("coverage support requested but no coverage() builtin declared\n");
6170 cov = func->m_function_type;
6173 if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) {
6175 ast_type_to_string(expr, ty, sizeof(ty));
6176 con_out("invalid type for coverage(): %s\n", ty);
6181 ir->m_coverage_func = func->m_ir_func->m_value;
6185 bool parser_finish(parser_t *parser, const char *output)
6190 if (compile_errors) {
6191 con_out("*** there were compile errors\n");
6195 ir = new ir_builder("gmqcc_out");
6197 con_out("failed to allocate builder\n");
6201 for (auto &it : parser->fields) {
6203 if (!ast_istype(it, ast_value))
6205 ast_value *field = (ast_value*)it;
6206 hasvalue = field->m_hasvalue;
6207 field->m_hasvalue = false;
6208 if (!reinterpret_cast<ast_value*>(field)->generateGlobal(ir, true)) {
6209 con_out("failed to generate field %s\n", field->m_name.c_str());
6215 ast_expression *subtype;
6216 field->m_hasvalue = true;
6217 subtype = field->m_next;
6218 ifld = ir_builder_create_field(ir, field->m_name, subtype->m_vtype);
6219 if (subtype->m_vtype == TYPE_FIELD)
6220 ifld->m_fieldtype = subtype->m_next->m_vtype;
6221 else if (subtype->m_vtype == TYPE_FUNCTION)
6222 ifld->m_outtype = subtype->m_next->m_vtype;
6223 (void)!ir_value_set_field(field->m_ir_v, ifld);
6226 for (auto &it : parser->globals) {
6228 if (!ast_istype(it, ast_value))
6230 asvalue = (ast_value*)it;
6231 if (!asvalue->m_uses && !asvalue->m_hasvalue && asvalue->m_vtype != TYPE_FUNCTION) {
6232 retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE,
6233 "unused global: `%s`", asvalue->m_name);
6235 if (!asvalue->generateGlobal(ir, false)) {
6236 con_out("failed to generate global %s\n", asvalue->m_name.c_str());
6241 /* Build function vararg accessor ast tree now before generating
6242 * immediates, because the accessors may add new immediates
6244 for (auto &f : parser->functions) {
6246 if (parser->max_param_count > f->m_function_type->m_type_params.size()) {
6247 f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size();
6248 if (!parser_create_array_setter_impl(parser, f->m_varargs.get())) {
6249 con_out("failed to generate vararg setter for %s\n", f->m_name.c_str());
6253 if (!parser_create_array_getter_impl(parser, f->m_varargs.get())) {
6254 con_out("failed to generate vararg getter for %s\n", f->m_name.c_str());
6259 f->m_varargs = nullptr;
6263 /* Now we can generate immediates */
6264 if (!parser->m_fold.generate(ir))
6267 /* before generating any functions we need to set the coverage_func */
6268 if (!parser_set_coverage_func(parser, ir))
6270 for (auto &it : parser->globals) {
6271 if (!ast_istype(it, ast_value))
6273 ast_value *asvalue = (ast_value*)it;
6274 if (!(asvalue->m_flags & AST_FLAG_INITIALIZED))
6276 if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue)
6277 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT,
6278 "uninitialized constant: `%s`",
6280 else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue)
6281 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL,
6282 "uninitialized global: `%s`",
6285 if (!asvalue->generateAccessors(ir)) {
6290 for (auto &it : parser->fields) {
6291 ast_value *asvalue = (ast_value*)it->m_next;
6292 if (!ast_istype(asvalue, ast_value))
6294 if (asvalue->m_vtype != TYPE_ARRAY)
6296 if (!asvalue->generateAccessors(ir)) {
6301 if (parser->reserved_version &&
6302 !parser->reserved_version->generateGlobal(ir, false))
6304 con_out("failed to generate reserved::version");
6308 for (auto &f : parser->functions) {
6309 if (!f->generateFunction(ir)) {
6310 con_out("failed to generate function %s\n", f->m_name.c_str());
6316 generate_checksum(parser, ir);
6318 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6319 ir_builder_dump(ir, con_out);
6320 for (auto &it : parser->functions) {
6321 if (!ir_function_finalize(it->m_ir_func)) {
6322 con_out("failed to finalize function %s\n", it->m_name.c_str());
6327 parser_remove_ast(parser);
6329 if (compile_Werrors) {
6330 con_out("*** there were warnings treated as errors\n");
6331 compile_show_werrors();
6336 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6337 ir_builder_dump(ir, con_out);
6339 if (!ir_builder_generate(ir, output)) {
6340 con_out("*** failed to generate output file\n");