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 bool parse_block_into(parser_t *parser, ast_block *block);
22 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
23 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
24 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
25 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
26 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
27 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
28 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
30 static void parseerror_(parser_t *parser, const char *fmt, ...)
34 vcompile_error(parser->lex->tok.ctx, fmt, ap);
38 template<typename... Ts>
39 static inline void parseerror(parser_t *parser, const char *fmt, const Ts&... ts) {
40 return parseerror_(parser, fmt, formatNormalize(ts)...);
43 // returns true if it counts as an error
44 static bool GMQCC_WARN parsewarning_(parser_t *parser, int warntype, const char *fmt, ...)
49 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
54 template<typename... Ts>
55 static inline bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, const Ts&... ts) {
56 return parsewarning_(parser, warntype, fmt, formatNormalize(ts)...);
59 /**********************************************************************
63 static bool parser_next(parser_t *parser)
65 /* lex_do kills the previous token */
66 parser->tok = lex_do(parser->lex);
67 if (parser->tok == TOKEN_EOF)
69 if (parser->tok >= TOKEN_ERROR) {
70 parseerror(parser, "lex error");
76 #define parser_tokval(p) ((p)->lex->tok.value)
77 #define parser_token(p) (&((p)->lex->tok))
79 char *parser_strdup(const char *str)
82 /* actually dup empty strings */
83 char *out = (char*)mem_a(1);
87 return util_strdup(str);
90 static ast_expression* parser_find_field(parser_t *parser, const char *name) {
91 return (ast_expression*)util_htget(parser->htfields, name);
93 static ast_expression* parser_find_field(parser_t *parser, const std::string &name) {
94 return parser_find_field(parser, name.c_str());
97 static ast_expression* parser_find_label(parser_t *parser, const char *name)
99 for (auto &it : parser->labels)
100 if (it->m_name == name)
104 static inline ast_expression* parser_find_label(parser_t *parser, const std::string &name) {
105 return parser_find_label(parser, name.c_str());
108 ast_expression* parser_find_global(parser_t *parser, const char *name)
110 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
113 return (ast_expression*)util_htget(parser->htglobals, name);
116 ast_expression* parser_find_global(parser_t *parser, const std::string &name) {
117 return parser_find_global(parser, name.c_str());
120 static ast_expression* parser_find_param(parser_t *parser, const char *name)
123 if (!parser->function)
125 fun = parser->function->m_function_type;
126 for (auto &it : fun->m_type_params) {
127 if (it->m_name == name)
133 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
138 hash = util_hthash(parser->htglobals, name);
141 for (i = parser->variables.size(); i > upto;) {
143 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
147 return parser_find_param(parser, name);
150 static ast_expression* parser_find_local(parser_t *parser, const std::string &name, size_t upto, bool *isparam) {
151 return parser_find_local(parser, name.c_str(), upto, isparam);
154 static ast_expression* parser_find_var(parser_t *parser, const char *name)
158 v = parser_find_local(parser, name, PARSER_HT_LOCALS, &dummy);
159 if (!v) v = parser_find_global(parser, name);
163 static inline ast_expression* parser_find_var(parser_t *parser, const std::string &name) {
164 return parser_find_var(parser, name.c_str());
167 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
171 hash = util_hthash(parser->typedefs[0], name);
173 for (i = parser->typedefs.size(); i > upto;) {
175 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
181 static ast_value* parser_find_typedef(parser_t *parser, const std::string &name, size_t upto) {
182 return parser_find_typedef(parser, name.c_str(), upto);
186 size_t etype; /* 0 = expression, others are operators */
190 ast_block *block; /* for commas and function calls */
203 std::vector<sy_elem> out;
204 std::vector<sy_elem> ops;
205 std::vector<size_t> argc;
206 std::vector<unsigned int> paren;
209 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
220 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
231 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
233 e.etype = 1 + (op - operators);
242 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
253 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
254 * so we need to rotate it to become ent.(foo[n]).
256 static bool rotate_entfield_array_index_nodes(ast_expression **out)
258 ast_array_index *index, *oldindex;
259 ast_entfield *entfield;
263 ast_expression *entity;
265 lex_ctx_t ctx = (*out)->m_context;
267 if (!ast_istype(*out, ast_array_index))
269 index = (ast_array_index*)*out;
271 if (!ast_istype(index->m_array, ast_entfield))
273 entfield = (ast_entfield*)index->m_array;
275 if (!ast_istype(entfield->m_field, ast_value))
277 field = (ast_value*)entfield->m_field;
279 sub = index->m_index;
280 entity = entfield->m_entity;
284 index = ast_array_index::make(ctx, field, sub);
285 entfield = new ast_entfield(ctx, entity, index);
288 oldindex->m_array = nullptr;
289 oldindex->m_index = nullptr;
295 static int store_op_for(ast_expression* expr)
297 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) && expr->m_vtype == TYPE_FIELD && expr->m_next->m_vtype == TYPE_VECTOR) {
298 if (ast_istype(expr, ast_entfield)) {
299 return type_storep_instr[TYPE_VECTOR];
301 return type_store_instr[TYPE_VECTOR];
305 if (ast_istype(expr, ast_member) && ast_istype(((ast_member*)expr)->m_owner, ast_entfield)) {
306 return type_storep_instr[expr->m_vtype];
309 if (ast_istype(expr, ast_entfield)) {
310 return type_storep_instr[expr->m_vtype];
313 return type_store_instr[expr->m_vtype];
316 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
318 if (ast_istype(expr, ast_value)) {
319 ast_value *val = (ast_value*)expr;
320 if (val->m_cvq == CV_CONST) {
321 if (val->m_name[0] == '#') {
322 compile_error(ctx, "invalid assignment to a literal constant");
326 * To work around quakeworld we must elide the error and make it
329 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
330 compile_error(ctx, "assignment to constant `%s`", val->m_name);
332 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
339 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
343 ast_expression *out = nullptr;
344 ast_expression *exprs[3] = { 0, 0, 0 };
345 ast_block *blocks[3];
346 ast_binstore *asbinstore;
347 size_t i, assignop, addop, subop;
348 qcint_t generated_op = 0;
353 if (sy->ops.empty()) {
354 parseerror(parser, "internal error: missing operator");
358 if (sy->ops.back().isparen) {
359 parseerror(parser, "unmatched parenthesis");
363 op = &operators[sy->ops.back().etype - 1];
364 ctx = sy->ops.back().ctx;
366 if (sy->out.size() < op->operands) {
367 if (op->flags & OP_PREFIX)
368 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
369 else /* this should have errored previously already */
370 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
376 /* op(:?) has no input and no output */
380 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
381 for (i = 0; i < op->operands; ++i) {
382 exprs[i] = sy->out[sy->out.size()+i].out;
383 blocks[i] = sy->out[sy->out.size()+i].block;
385 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
386 !(i != 0 && op->id == opid2('?',':')) &&
387 !(i == 1 && op->id == opid1('.')))
389 if (ast_istype(exprs[i], ast_label))
390 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
392 compile_error(exprs[i]->m_context, "not an expression");
393 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
397 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
398 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
402 #define NotSameType(T) \
403 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
404 exprs[0]->m_vtype != T)
409 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
413 if (exprs[0]->m_vtype == TYPE_VECTOR &&
414 exprs[1]->m_vtype == TYPE_NOEXPR)
416 if (exprs[1] == parser->const_vec[0])
417 out = ast_member::make(ctx, exprs[0], 0, "");
418 else if (exprs[1] == parser->const_vec[1])
419 out = ast_member::make(ctx, exprs[0], 1, "");
420 else if (exprs[1] == parser->const_vec[2])
421 out = ast_member::make(ctx, exprs[0], 2, "");
423 compile_error(ctx, "access to invalid vector component");
427 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
428 if (exprs[1]->m_vtype != TYPE_FIELD) {
429 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
432 out = new ast_entfield(ctx, exprs[0], exprs[1]);
434 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
435 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
439 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
445 if (exprs[0]->m_vtype != TYPE_ARRAY &&
446 !(exprs[0]->m_vtype == TYPE_FIELD &&
447 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
449 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
450 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
453 if (exprs[1]->m_vtype != TYPE_FLOAT) {
454 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
455 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
458 out = ast_array_index::make(ctx, exprs[0], exprs[1]);
459 rotate_entfield_array_index_nodes(&out);
463 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
464 sy->out.push_back(syexp(ctx, exprs[0]));
465 sy->out.push_back(syexp(ctx, exprs[1]));
470 if (!blocks[0]->addExpr(exprs[1]))
473 blocks[0] = new ast_block(ctx);
474 if (!blocks[0]->addExpr(exprs[0]) ||
475 !blocks[0]->addExpr(exprs[1]))
480 blocks[0]->setType(*exprs[1]);
482 sy->out.push_back(syblock(ctx, blocks[0]));
489 if ((out = parser->m_fold.op(op, exprs)))
492 if (exprs[0]->m_vtype != TYPE_FLOAT &&
493 exprs[0]->m_vtype != TYPE_VECTOR) {
494 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
495 type_name[exprs[0]->m_vtype]);
498 if (exprs[0]->m_vtype == TYPE_FLOAT)
499 out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]);
501 out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]);
505 if (!(out = parser->m_fold.op(op, exprs))) {
506 switch (exprs[0]->m_vtype) {
508 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
511 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]);
514 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
515 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
517 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]);
519 /* we don't constant-fold NOT for these types */
521 out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]);
524 out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]);
527 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
528 type_name[exprs[0]->m_vtype]);
535 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
536 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
538 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
539 type_name[exprs[0]->m_vtype],
540 type_name[exprs[1]->m_vtype]);
543 if (!(out = parser->m_fold.op(op, exprs))) {
544 switch (exprs[0]->m_vtype) {
546 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
549 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
552 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
553 type_name[exprs[0]->m_vtype],
554 type_name[exprs[1]->m_vtype]);
560 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
561 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
563 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
564 type_name[exprs[1]->m_vtype],
565 type_name[exprs[0]->m_vtype]);
568 if (!(out = parser->m_fold.op(op, exprs))) {
569 switch (exprs[0]->m_vtype) {
571 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
574 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
577 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
578 type_name[exprs[1]->m_vtype],
579 type_name[exprs[0]->m_vtype]);
585 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
586 !(exprs[0]->m_vtype == TYPE_VECTOR &&
587 exprs[1]->m_vtype == TYPE_FLOAT) &&
588 !(exprs[1]->m_vtype == TYPE_VECTOR &&
589 exprs[0]->m_vtype == TYPE_FLOAT)
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]);
597 if (!(out = parser->m_fold.op(op, exprs))) {
598 switch (exprs[0]->m_vtype) {
600 if (exprs[1]->m_vtype == TYPE_VECTOR)
601 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
603 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
606 if (exprs[1]->m_vtype == TYPE_FLOAT)
607 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
609 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
612 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
613 type_name[exprs[1]->m_vtype],
614 type_name[exprs[0]->m_vtype]);
621 if (exprs[1]->m_vtype != TYPE_FLOAT) {
622 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
623 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
624 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
627 if (!(out = parser->m_fold.op(op, exprs))) {
628 if (exprs[0]->m_vtype == TYPE_FLOAT)
629 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
631 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
632 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
633 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
640 if (NotSameType(TYPE_FLOAT)) {
641 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
642 type_name[exprs[0]->m_vtype],
643 type_name[exprs[1]->m_vtype]);
645 } else if (!(out = parser->m_fold.op(op, exprs))) {
646 /* generate a call to __builtin_mod */
647 ast_expression *mod = parser->m_intrin.func("mod");
648 ast_call *call = nullptr;
649 if (!mod) return false; /* can return null for missing floor */
651 call = ast_call::make(parser_ctx(parser), mod);
652 call->m_params.push_back(exprs[0]);
653 call->m_params.push_back(exprs[1]);
660 compile_error(ctx, "%= is unimplemented");
666 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
667 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
668 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
670 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
671 type_name[exprs[0]->m_vtype],
672 type_name[exprs[1]->m_vtype]);
676 if (!(out = parser->m_fold.op(op, exprs))) {
678 * IF the first expression is float, the following will be too
679 * since scalar ^ vector is not allowed.
681 if (exprs[0]->m_vtype == TYPE_FLOAT) {
682 out = fold::binary(ctx,
683 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
687 * The first is a vector: vector is allowed to bitop with vector and
688 * with scalar, branch here for the second operand.
690 if (exprs[1]->m_vtype == TYPE_VECTOR) {
692 * Bitop all the values of the vector components against the
693 * vectors components in question.
695 out = fold::binary(ctx,
696 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
699 out = fold::binary(ctx,
700 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
709 if (NotSameType(TYPE_FLOAT)) {
710 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
711 type_name[exprs[0]->m_vtype],
712 type_name[exprs[1]->m_vtype]);
716 if (!(out = parser->m_fold.op(op, exprs))) {
717 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
718 ast_call *call = ast_call::make(parser_ctx(parser), shift);
719 call->m_params.push_back(exprs[0]);
720 call->m_params.push_back(exprs[1]);
725 case opid3('<','<','='):
726 case opid3('>','>','='):
727 if (NotSameType(TYPE_FLOAT)) {
728 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
729 type_name[exprs[0]->m_vtype],
730 type_name[exprs[1]->m_vtype]);
734 if(!(out = parser->m_fold.op(op, exprs))) {
735 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
736 ast_call *call = ast_call::make(parser_ctx(parser), shift);
737 call->m_params.push_back(exprs[0]);
738 call->m_params.push_back(exprs[1]);
750 generated_op += 1; /* INSTR_OR */
753 generated_op += INSTR_AND;
754 if (!(out = parser->m_fold.op(op, exprs))) {
755 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
756 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
757 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
758 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
761 for (i = 0; i < 2; ++i) {
762 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
763 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
765 out = ast_unary::make(ctx, INSTR_NOT_F, out);
767 exprs[i] = out; out = nullptr;
768 if (OPTS_FLAG(PERL_LOGIC)) {
769 /* here we want to keep the right expressions' type */
773 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
774 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
776 out = ast_unary::make(ctx, INSTR_NOT_F, out);
778 exprs[i] = out; out = nullptr;
779 if (OPTS_FLAG(PERL_LOGIC)) {
780 /* here we want to keep the right expressions' type */
785 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
790 if (sy->paren.back() != PAREN_TERNARY2) {
791 compile_error(ctx, "mismatched parenthesis/ternary");
794 sy->paren.pop_back();
795 if (!exprs[1]->compareType(*exprs[2])) {
796 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
797 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
798 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
801 if (!(out = parser->m_fold.op(op, exprs)))
802 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
805 case opid2('*', '*'):
806 if (NotSameType(TYPE_FLOAT)) {
807 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
808 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
809 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
814 if (!(out = parser->m_fold.op(op, exprs))) {
815 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
816 gencall->m_params.push_back(exprs[0]);
817 gencall->m_params.push_back(exprs[1]);
822 case opid2('>', '<'):
823 if (NotSameType(TYPE_VECTOR)) {
824 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
825 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
826 compile_error(ctx, "invalid types used in cross product: %s and %s",
831 if (!(out = parser->m_fold.op(op, exprs))) {
842 case opid3('<','=','>'): /* -1, 0, or 1 */
843 if (NotSameType(TYPE_FLOAT)) {
844 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
845 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
846 compile_error(ctx, "invalid types used in comparision: %s and %s",
852 if (!(out = parser->m_fold.op(op, exprs))) {
853 /* This whole block is NOT fold_binary safe */
854 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
856 eq->m_refs = AST_REF_NONE;
859 out = new ast_ternary(ctx,
860 new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
862 parser->m_fold.imm_float(2),
865 new ast_ternary(ctx, eq,
867 parser->m_fold.imm_float(0),
870 parser->m_fold.imm_float(1)
880 generated_op += 1; /* INSTR_GT */
883 generated_op += 1; /* INSTR_LT */
885 case opid2('>', '='):
886 generated_op += 1; /* INSTR_GE */
888 case opid2('<', '='):
889 generated_op += INSTR_LE;
890 if (NotSameType(TYPE_FLOAT)) {
891 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
892 type_name[exprs[0]->m_vtype],
893 type_name[exprs[1]->m_vtype]);
896 if (!(out = parser->m_fold.op(op, exprs)))
897 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
899 case opid2('!', '='):
900 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
901 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
902 type_name[exprs[0]->m_vtype],
903 type_name[exprs[1]->m_vtype]);
906 if (!(out = parser->m_fold.op(op, exprs)))
907 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
909 case opid2('=', '='):
910 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
911 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
912 type_name[exprs[0]->m_vtype],
913 type_name[exprs[1]->m_vtype]);
916 if (!(out = parser->m_fold.op(op, exprs)))
917 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
921 if (ast_istype(exprs[0], ast_entfield)) {
922 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
923 assignop = store_op_for(exprs[0]);
924 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
926 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
927 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
928 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
929 field->m_next->m_vtype == TYPE_FUNCTION &&
930 exprs[1]->m_vtype == TYPE_FUNCTION)
932 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
933 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
936 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
941 assignop = store_op_for(exprs[0]);
943 if (assignop == VINSTR_END) {
944 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
945 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
946 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
948 else if (!exprs[0]->compareType(*exprs[1]))
950 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
951 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
952 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
953 exprs[0]->m_vtype == TYPE_FUNCTION &&
954 exprs[1]->m_vtype == TYPE_FUNCTION)
956 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
957 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
960 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
963 (void)check_write_to(ctx, exprs[0]);
964 /* When we're a vector of part of an entity field we use STOREP */
965 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
966 assignop = INSTR_STOREP_F;
967 out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
969 case opid3('+','+','P'):
970 case opid3('-','-','P'):
972 if (exprs[0]->m_vtype != TYPE_FLOAT) {
973 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
974 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
977 if (op->id == opid3('+','+','P'))
981 (void)check_write_to(exprs[0]->m_context, exprs[0]);
982 if (ast_istype(exprs[0], ast_entfield)) {
983 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
985 parser->m_fold.imm_float(1));
987 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
989 parser->m_fold.imm_float(1));
992 case opid3('S','+','+'):
993 case opid3('S','-','-'):
995 if (exprs[0]->m_vtype != TYPE_FLOAT) {
996 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
997 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
1000 if (op->id == opid3('S','+','+')) {
1001 addop = INSTR_ADD_F;
1002 subop = INSTR_SUB_F;
1004 addop = INSTR_SUB_F;
1005 subop = INSTR_ADD_F;
1007 (void)check_write_to(exprs[0]->m_context, exprs[0]);
1008 if (ast_istype(exprs[0], ast_entfield)) {
1009 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1011 parser->m_fold.imm_float(1));
1013 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1015 parser->m_fold.imm_float(1));
1019 out = fold::binary(ctx, subop,
1021 parser->m_fold.imm_float(1));
1024 case opid2('+','='):
1025 case opid2('-','='):
1026 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1027 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1029 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1030 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1031 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1035 (void)check_write_to(ctx, exprs[0]);
1036 assignop = store_op_for(exprs[0]);
1037 switch (exprs[0]->m_vtype) {
1039 out = new ast_binstore(ctx, assignop,
1040 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1041 exprs[0], exprs[1]);
1044 out = new ast_binstore(ctx, assignop,
1045 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1046 exprs[0], exprs[1]);
1049 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1050 type_name[exprs[0]->m_vtype],
1051 type_name[exprs[1]->m_vtype]);
1055 case opid2('*','='):
1056 case opid2('/','='):
1057 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1058 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1059 exprs[0]->m_vtype == TYPE_VECTOR))
1061 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1062 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1063 compile_error(ctx, "invalid types used in expression: %s and %s",
1067 (void)check_write_to(ctx, exprs[0]);
1068 assignop = store_op_for(exprs[0]);
1069 switch (exprs[0]->m_vtype) {
1071 out = new ast_binstore(ctx, assignop,
1072 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1073 exprs[0], exprs[1]);
1076 if (op->id == opid2('*','=')) {
1077 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1078 exprs[0], exprs[1]);
1080 out = fold::binary(ctx, INSTR_DIV_F,
1081 parser->m_fold.imm_float(1),
1084 compile_error(ctx, "internal error: failed to generate division");
1087 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1092 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1093 type_name[exprs[0]->m_vtype],
1094 type_name[exprs[1]->m_vtype]);
1098 case opid2('&','='):
1099 case opid2('|','='):
1100 case opid2('^','='):
1101 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1102 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1103 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1104 compile_error(ctx, "invalid types used in expression: %s and %s",
1108 (void)check_write_to(ctx, exprs[0]);
1109 assignop = store_op_for(exprs[0]);
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 assignop = store_op_for(exprs[0]);
1132 if (exprs[0]->m_vtype == TYPE_FLOAT)
1133 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1135 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1138 (void)check_write_to(ctx, exprs[0]);
1139 if (exprs[0]->m_vtype == TYPE_FLOAT)
1140 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1142 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1143 asbinstore->m_keep_dest = true;
1147 case opid3('l', 'e', 'n'):
1148 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1149 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1150 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1153 /* strings must be const, arrays are statically sized */
1154 if (exprs[0]->m_vtype == TYPE_STRING &&
1155 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1157 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1160 out = parser->m_fold.op(op, exprs);
1163 case opid2('~', 'P'):
1164 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1165 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1166 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1169 if (!(out = parser->m_fold.op(op, exprs))) {
1170 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1171 out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1173 out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1180 compile_error(ctx, "failed to apply operator %s", op->op);
1184 sy->out.push_back(syexp(ctx, out));
1188 static bool parser_close_call(parser_t *parser, shunt *sy)
1190 if (!parser->function)
1192 parseerror(parser, "cannot call functions from global scope");
1196 /* was a function call */
1197 ast_expression *fun;
1198 ast_value *funval = nullptr;
1202 size_t paramcount, i;
1205 fid = sy->ops.back().off;
1208 /* out[fid] is the function
1209 * everything above is parameters...
1211 if (sy->argc.empty()) {
1212 parseerror(parser, "internal error: no argument counter available");
1216 paramcount = sy->argc.back();
1217 sy->argc.pop_back();
1219 if (sy->out.size() < fid) {
1220 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1228 * TODO handle this at the intrinsic level with an ast_intrinsic
1231 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1233 if (fid+2 != sy->out.size() || sy->out.back().block) {
1234 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1237 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1238 ast_unref(sy->out.back().out);
1239 sy->out[fid] = syexp(sy->out.back().out->m_context,
1240 parser->m_fold.constgen_string(ty, false));
1246 * Now we need to determine if the function that is being called is
1247 * an intrinsic so we can evaluate if the arguments to it are constant
1248 * and than fruitfully fold them.
1250 #define fold_can_1(X) \
1251 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1252 ((X))->m_vtype != TYPE_FUNCTION)
1254 if (fid + 1 < sy->out.size())
1257 for (i = 0; i < paramcount; ++i) {
1258 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1265 * All is well which ends well, if we make it into here we can ignore the
1266 * intrinsic call and just evaluate it i.e constant fold it.
1268 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1269 std::vector<ast_expression*> exprs;
1270 ast_expression *foldval = nullptr;
1272 exprs.reserve(paramcount);
1273 for (i = 0; i < paramcount; i++)
1274 exprs.push_back(sy->out[fid+1 + i].out);
1276 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs.data()))) {
1281 * Blub: what sorts of unreffing and resizing of
1282 * sy->out should I be doing here?
1284 sy->out[fid] = syexp(foldval->m_context, foldval);
1285 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1291 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1296 if (fid+1 + paramcount != sy->out.size()) {
1297 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1304 for (i = 0; i < paramcount; ++i)
1305 call->m_params.push_back(sy->out[fid+1 + i].out);
1306 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1307 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1308 if (parser->max_param_count < paramcount)
1309 parser->max_param_count = paramcount;
1311 if (ast_istype(fun, ast_value)) {
1312 funval = (ast_value*)fun;
1313 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1314 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1316 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1320 /* overwrite fid, the function, with a call */
1321 sy->out[fid] = syexp(call->m_context, call);
1323 if (fun->m_vtype != TYPE_FUNCTION) {
1324 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1329 parseerror(parser, "could not determine function return type");
1332 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1334 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1336 return !parsewarning(parser, WARN_DEPRECATED,
1337 "call to function (which is marked deprecated)\n",
1338 "-> it has been declared here: %s:%i",
1339 fun->m_context.file, fun->m_context.line);
1341 if (!fval->m_desc.length()) {
1342 return !parsewarning(parser, WARN_DEPRECATED,
1343 "call to `%s` (which is marked deprecated)\n"
1344 "-> `%s` declared here: %s:%i",
1345 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1347 return !parsewarning(parser, WARN_DEPRECATED,
1348 "call to `%s` (deprecated: %s)\n"
1349 "-> `%s` declared here: %s:%i",
1350 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1351 fun->m_context.line);
1354 if (fun->m_type_params.size() != paramcount &&
1355 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1356 fun->m_type_params.size() < paramcount))
1358 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1360 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1361 "too %s parameters for call to %s: expected %i, got %i\n"
1362 " -> `%s` has been declared here: %s:%i",
1363 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1364 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1366 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1367 "too %s parameters for function call: expected %i, got %i\n"
1368 " -> it has been declared here: %s:%i",
1369 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1370 fun->m_context.file, (int)fun->m_context.line);
1377 static bool parser_close_paren(parser_t *parser, shunt *sy)
1379 if (sy->ops.empty()) {
1380 parseerror(parser, "unmatched closing paren");
1384 while (sy->ops.size()) {
1385 if (sy->ops.back().isparen) {
1386 if (sy->paren.back() == PAREN_FUNC) {
1387 sy->paren.pop_back();
1388 if (!parser_close_call(parser, sy))
1392 if (sy->paren.back() == PAREN_EXPR) {
1393 sy->paren.pop_back();
1394 if (sy->out.empty()) {
1395 compile_error(sy->ops.back().ctx, "empty paren expression");
1402 if (sy->paren.back() == PAREN_INDEX) {
1403 sy->paren.pop_back();
1404 // pop off the parenthesis
1406 /* then apply the index operator */
1407 if (!parser_sy_apply_operator(parser, sy))
1411 if (sy->paren.back() == PAREN_TERNARY1) {
1412 sy->paren.back() = PAREN_TERNARY2;
1413 // pop off the parenthesis
1417 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1420 if (!parser_sy_apply_operator(parser, sy))
1426 static void parser_reclassify_token(parser_t *parser)
1429 if (parser->tok >= TOKEN_START)
1431 for (i = 0; i < operator_count; ++i) {
1432 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1433 parser->tok = TOKEN_OPERATOR;
1439 static ast_expression* parse_vararg_do(parser_t *parser)
1441 ast_expression *idx, *out;
1443 ast_value *funtype = parser->function->m_function_type;
1444 lex_ctx_t ctx = parser_ctx(parser);
1446 if (!parser->function->m_varargs) {
1447 parseerror(parser, "function has no variable argument list");
1451 if (!parser_next(parser) || parser->tok != '(') {
1452 parseerror(parser, "expected parameter index and type in parenthesis");
1455 if (!parser_next(parser)) {
1456 parseerror(parser, "error parsing parameter index");
1460 idx = parse_expression_leave(parser, true, false, false);
1464 if (parser->tok != ',') {
1465 if (parser->tok != ')') {
1467 parseerror(parser, "expected comma after parameter index");
1470 // vararg piping: ...(start)
1471 out = new ast_argpipe(ctx, idx);
1475 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1477 parseerror(parser, "expected typename for vararg");
1481 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1487 if (parser->tok != ')') {
1490 parseerror(parser, "expected closing paren");
1494 if (funtype->m_varparam &&
1495 !typevar->compareType(*funtype->m_varparam))
1499 ast_type_to_string(typevar, ty1, sizeof(ty1));
1500 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1501 compile_error(typevar->m_context,
1502 "function was declared to take varargs of type `%s`, requested type is: %s",
1506 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1507 out->adoptType(*typevar);
1512 static ast_expression* parse_vararg(parser_t *parser)
1514 bool old_noops = parser->lex->flags.noops;
1516 ast_expression *out;
1518 parser->lex->flags.noops = true;
1519 out = parse_vararg_do(parser);
1521 parser->lex->flags.noops = old_noops;
1525 /* not to be exposed */
1526 bool ftepp_predef_exists(const char *name);
1527 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1529 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1530 parser->tok == TOKEN_IDENT &&
1531 !strcmp(parser_tokval(parser), "_"))
1533 /* a translatable string */
1536 parser->lex->flags.noops = true;
1537 if (!parser_next(parser) || parser->tok != '(') {
1538 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1541 parser->lex->flags.noops = false;
1542 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1543 parseerror(parser, "expected a constant string in translatable-string extension");
1546 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1549 sy->out.push_back(syexp(parser_ctx(parser), val));
1551 if (!parser_next(parser) || parser->tok != ')') {
1552 parseerror(parser, "expected closing paren after translatable string");
1557 else if (parser->tok == TOKEN_DOTS)
1560 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1561 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1564 va = parse_vararg(parser);
1567 sy->out.push_back(syexp(parser_ctx(parser), va));
1570 else if (parser->tok == TOKEN_FLOATCONST) {
1571 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1574 sy->out.push_back(syexp(parser_ctx(parser), val));
1577 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1578 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1581 sy->out.push_back(syexp(parser_ctx(parser), val));
1584 else if (parser->tok == TOKEN_STRINGCONST) {
1585 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1588 sy->out.push_back(syexp(parser_ctx(parser), val));
1591 else if (parser->tok == TOKEN_VECTORCONST) {
1592 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1595 sy->out.push_back(syexp(parser_ctx(parser), val));
1598 else if (parser->tok == TOKEN_IDENT)
1600 const char *ctoken = parser_tokval(parser);
1601 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1602 ast_expression *var;
1603 /* a_vector.{x,y,z} */
1604 if (sy->ops.empty() ||
1605 !sy->ops.back().etype ||
1606 operators[sy->ops.back().etype-1].id != opid1('.'))
1608 /* When adding more intrinsics, fix the above condition */
1611 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1613 var = parser->const_vec[ctoken[0]-'x'];
1615 var = parser_find_var(parser, parser_tokval(parser));
1617 var = parser_find_field(parser, parser_tokval(parser));
1619 if (!var && with_labels) {
1620 var = parser_find_label(parser, parser_tokval(parser));
1622 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1624 parser->labels.push_back(lbl);
1627 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1628 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1631 * now we try for the real intrinsic hashtable. If the string
1632 * begins with __builtin, we simply skip past it, otherwise we
1633 * use the identifier as is.
1635 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1636 var = parser->m_intrin.func(parser_tokval(parser));
1640 * Try it again, intrin_func deals with the alias method as well
1641 * the first one masks for __builtin though, we emit warning here.
1644 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1645 (void)!compile_warning(
1648 "using implicitly defined builtin `__builtin_%s' for `%s'",
1649 parser_tokval(parser),
1650 parser_tokval(parser)
1658 * sometimes people use preprocessing predefs without enabling them
1659 * i've done this thousands of times already myself. Lets check for
1660 * it in the predef table. And diagnose it better :)
1662 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1663 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1667 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1673 // promote these to norefs
1674 if (ast_istype(var, ast_value))
1676 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1678 else if (ast_istype(var, ast_member))
1680 ast_member *mem = (ast_member *)var;
1681 if (ast_istype(mem->m_owner, ast_value))
1682 ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1685 sy->out.push_back(syexp(parser_ctx(parser), var));
1688 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1692 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1694 ast_expression *expr = nullptr;
1696 bool wantop = false;
1697 /* only warn once about an assignment in a truth value because the current code
1698 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1700 bool warn_parenthesis = true;
1702 /* count the parens because an if starts with one, so the
1703 * end of a condition is an unmatched closing paren
1707 memset(&sy, 0, sizeof(sy));
1709 parser->lex->flags.noops = false;
1711 parser_reclassify_token(parser);
1715 if (parser->tok == TOKEN_TYPENAME) {
1716 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1720 if (parser->tok == TOKEN_OPERATOR)
1722 /* classify the operator */
1723 const oper_info *op;
1724 const oper_info *olast = nullptr;
1726 for (o = 0; o < operator_count; ++o) {
1727 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1728 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1729 !strcmp(parser_tokval(parser), operators[o].op))
1734 if (o == operator_count) {
1735 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1738 /* found an operator */
1741 /* when declaring variables, a comma starts a new variable */
1742 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1743 /* fixup the token */
1748 /* a colon without a pervious question mark cannot be a ternary */
1749 if (!ternaries && op->id == opid2(':','?')) {
1754 if (op->id == opid1(',')) {
1755 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1756 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1760 if (sy.ops.size() && !sy.ops.back().isparen)
1761 olast = &operators[sy.ops.back().etype-1];
1763 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1764 while (olast && op->prec < olast->prec)
1766 if (!parser_sy_apply_operator(parser, &sy))
1768 if (sy.ops.size() && !sy.ops.back().isparen)
1769 olast = &operators[sy.ops.back().etype-1];
1774 #define IsAssignOp(x) (\
1775 (x) == opid1('=') || \
1776 (x) == opid2('+','=') || \
1777 (x) == opid2('-','=') || \
1778 (x) == opid2('*','=') || \
1779 (x) == opid2('/','=') || \
1780 (x) == opid2('%','=') || \
1781 (x) == opid2('&','=') || \
1782 (x) == opid2('|','=') || \
1783 (x) == opid3('&','~','=') \
1785 if (warn_parenthesis) {
1786 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1787 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1788 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1791 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1792 warn_parenthesis = false;
1795 if (olast && olast->id != op->id) {
1796 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1797 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1799 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1800 warn_parenthesis = false;
1802 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1803 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1805 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1806 warn_parenthesis = false;
1812 (op->prec < olast->prec) ||
1813 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1815 if (!parser_sy_apply_operator(parser, &sy))
1817 if (sy.ops.size() && !sy.ops.back().isparen)
1818 olast = &operators[sy.ops.back().etype-1];
1823 if (op->id == opid1('(')) {
1825 size_t sycount = sy.out.size();
1826 /* we expected an operator, this is the function-call operator */
1827 sy.paren.push_back(PAREN_FUNC);
1828 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1829 sy.argc.push_back(0);
1831 sy.paren.push_back(PAREN_EXPR);
1832 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1835 } else if (op->id == opid1('[')) {
1837 parseerror(parser, "unexpected array subscript");
1840 sy.paren.push_back(PAREN_INDEX);
1841 /* push both the operator and the paren, this makes life easier */
1842 sy.ops.push_back(syop(parser_ctx(parser), op));
1843 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1845 } else if (op->id == opid2('?',':')) {
1846 sy.ops.push_back(syop(parser_ctx(parser), op));
1847 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1850 sy.paren.push_back(PAREN_TERNARY1);
1851 } else if (op->id == opid2(':','?')) {
1852 if (sy.paren.empty()) {
1853 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1856 if (sy.paren.back() != PAREN_TERNARY1) {
1857 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1860 if (!parser_close_paren(parser, &sy))
1862 sy.ops.push_back(syop(parser_ctx(parser), op));
1866 sy.ops.push_back(syop(parser_ctx(parser), op));
1867 wantop = !!(op->flags & OP_SUFFIX);
1870 else if (parser->tok == ')') {
1871 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1872 if (!parser_sy_apply_operator(parser, &sy))
1875 if (sy.paren.empty())
1878 if (sy.paren.back() == PAREN_TERNARY1) {
1879 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1882 if (!parser_close_paren(parser, &sy))
1885 /* must be a function call without parameters */
1886 if (sy.paren.back() != PAREN_FUNC) {
1887 parseerror(parser, "closing paren in invalid position");
1890 if (!parser_close_paren(parser, &sy))
1895 else if (parser->tok == '(') {
1896 parseerror(parser, "internal error: '(' should be classified as operator");
1899 else if (parser->tok == '[') {
1900 parseerror(parser, "internal error: '[' should be classified as operator");
1903 else if (parser->tok == ']') {
1904 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1905 if (!parser_sy_apply_operator(parser, &sy))
1908 if (sy.paren.empty())
1910 if (sy.paren.back() != PAREN_INDEX) {
1911 parseerror(parser, "mismatched parentheses, unexpected ']'");
1914 if (!parser_close_paren(parser, &sy))
1919 if (!parse_sya_operand(parser, &sy, with_labels))
1924 /* in this case we might want to allow constant string concatenation */
1925 bool concatenated = false;
1926 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1927 ast_expression *lexpr = sy.out.back().out;
1928 if (ast_istype(lexpr, ast_value)) {
1929 ast_value *last = (ast_value*)lexpr;
1930 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1931 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1933 char *newstr = nullptr;
1934 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1935 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1937 concatenated = true;
1941 if (!concatenated) {
1942 parseerror(parser, "expected operator or end of statement");
1947 if (!parser_next(parser)) {
1950 if (parser->tok == ';' ||
1951 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1952 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1958 while (sy.ops.size()) {
1959 if (!parser_sy_apply_operator(parser, &sy))
1963 parser->lex->flags.noops = true;
1964 if (sy.out.size() != 1) {
1965 parseerror(parser, "expression expected");
1968 expr = sy.out[0].out;
1969 if (sy.paren.size()) {
1970 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1976 parser->lex->flags.noops = true;
1977 for (auto &it : sy.out)
1978 if (it.out) ast_unref(it.out);
1982 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1984 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1987 if (parser->tok != ';') {
1988 parseerror(parser, "semicolon expected after expression");
1992 if (!parser_next(parser)) {
1999 static void parser_enterblock(parser_t *parser)
2001 parser->variables.push_back(util_htnew(PARSER_HT_SIZE));
2002 parser->_blocklocals.push_back(parser->_locals.size());
2003 parser->typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
2004 parser->_blocktypedefs.push_back(parser->_typedefs.size());
2005 parser->_block_ctx.push_back(parser_ctx(parser));
2008 static bool parser_leaveblock(parser_t *parser)
2011 size_t locals, typedefs;
2013 if (parser->variables.size() <= PARSER_HT_LOCALS) {
2014 parseerror(parser, "internal error: parser_leaveblock with no block");
2018 util_htdel(parser->variables.back());
2020 parser->variables.pop_back();
2021 if (!parser->_blocklocals.size()) {
2022 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2026 locals = parser->_blocklocals.back();
2027 parser->_blocklocals.pop_back();
2028 parser->_locals.resize(locals);
2030 typedefs = parser->_blocktypedefs.back();
2031 parser->_typedefs.resize(typedefs);
2032 util_htdel(parser->typedefs.back());
2033 parser->typedefs.pop_back();
2035 parser->_block_ctx.pop_back();
2040 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2042 parser->_locals.push_back(e);
2043 util_htset(parser->variables.back(), name, (void*)e);
2045 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2046 return parser_addlocal(parser, name.c_str(), e);
2049 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2051 parser->globals.push_back(e);
2052 util_htset(parser->htglobals, name, e);
2054 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2055 return parser_addglobal(parser, name.c_str(), e);
2058 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2062 ast_expression *prev;
2064 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2066 ast_type_to_string(cond, ty, sizeof(ty));
2067 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2070 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2073 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2076 parseerror(parser, "internal error: failed to process condition");
2081 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2083 /* vector types need to be cast to true booleans */
2084 ast_binary *bin = (ast_binary*)cond;
2085 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2087 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2089 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2092 parseerror(parser, "internal error: failed to process condition");
2099 unary = (ast_unary*)cond;
2100 /* ast_istype dereferences cond, should test here for safety */
2101 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2103 cond = unary->m_operand;
2104 unary->m_operand = nullptr;
2107 unary = (ast_unary*)cond;
2111 parseerror(parser, "internal error: failed to process condition");
2113 if (ifnot) *_ifnot = !*_ifnot;
2117 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2120 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2123 lex_ctx_t ctx = parser_ctx(parser);
2125 (void)block; /* not touching */
2127 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2128 if (!parser_next(parser)) {
2129 parseerror(parser, "expected condition or 'not'");
2132 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2134 if (!parser_next(parser)) {
2135 parseerror(parser, "expected condition in parenthesis");
2139 if (parser->tok != '(') {
2140 parseerror(parser, "expected 'if' condition in parenthesis");
2143 /* parse into the expression */
2144 if (!parser_next(parser)) {
2145 parseerror(parser, "expected 'if' condition after opening paren");
2148 /* parse the condition */
2149 cond = parse_expression_leave(parser, false, true, false);
2153 if (parser->tok != ')') {
2154 parseerror(parser, "expected closing paren after 'if' condition");
2158 /* parse into the 'then' branch */
2159 if (!parser_next(parser)) {
2160 parseerror(parser, "expected statement for on-true branch of 'if'");
2164 if (!parse_statement_or_block(parser, &ontrue)) {
2169 ontrue = new ast_block(parser_ctx(parser));
2170 /* check for an else */
2171 if (!strcmp(parser_tokval(parser), "else")) {
2172 /* parse into the 'else' branch */
2173 if (!parser_next(parser)) {
2174 parseerror(parser, "expected on-false branch after 'else'");
2179 if (!parse_statement_or_block(parser, &onfalse)) {
2186 cond = process_condition(parser, cond, &ifnot);
2188 if (ontrue) delete ontrue;
2189 if (onfalse) delete onfalse;
2194 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2196 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2201 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2202 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2205 char *label = nullptr;
2207 /* skip the 'while' and get the body */
2208 if (!parser_next(parser)) {
2209 if (OPTS_FLAG(LOOP_LABELS))
2210 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2212 parseerror(parser, "expected 'while' condition in parenthesis");
2216 if (parser->tok == ':') {
2217 if (!OPTS_FLAG(LOOP_LABELS))
2218 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2219 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2220 parseerror(parser, "expected loop label");
2223 label = util_strdup(parser_tokval(parser));
2224 if (!parser_next(parser)) {
2226 parseerror(parser, "expected 'while' condition in parenthesis");
2231 if (parser->tok != '(') {
2232 parseerror(parser, "expected 'while' condition in parenthesis");
2236 parser->breaks.push_back(label);
2237 parser->continues.push_back(label);
2239 rv = parse_while_go(parser, block, out);
2242 if (parser->breaks.back() != label || parser->continues.back() != label) {
2243 parseerror(parser, "internal error: label stack corrupted");
2249 parser->breaks.pop_back();
2250 parser->continues.pop_back();
2255 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2258 ast_expression *cond, *ontrue;
2262 lex_ctx_t ctx = parser_ctx(parser);
2264 (void)block; /* not touching */
2266 /* parse into the expression */
2267 if (!parser_next(parser)) {
2268 parseerror(parser, "expected 'while' condition after opening paren");
2271 /* parse the condition */
2272 cond = parse_expression_leave(parser, false, true, false);
2276 if (parser->tok != ')') {
2277 parseerror(parser, "expected closing paren after 'while' condition");
2281 /* parse into the 'then' branch */
2282 if (!parser_next(parser)) {
2283 parseerror(parser, "expected while-loop body");
2287 if (!parse_statement_or_block(parser, &ontrue)) {
2292 cond = process_condition(parser, cond, &ifnot);
2297 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2302 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2303 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2306 char *label = nullptr;
2308 /* skip the 'do' and get the body */
2309 if (!parser_next(parser)) {
2310 if (OPTS_FLAG(LOOP_LABELS))
2311 parseerror(parser, "expected loop label or body");
2313 parseerror(parser, "expected loop body");
2317 if (parser->tok == ':') {
2318 if (!OPTS_FLAG(LOOP_LABELS))
2319 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2320 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2321 parseerror(parser, "expected loop label");
2324 label = util_strdup(parser_tokval(parser));
2325 if (!parser_next(parser)) {
2327 parseerror(parser, "expected loop body");
2332 parser->breaks.push_back(label);
2333 parser->continues.push_back(label);
2335 rv = parse_dowhile_go(parser, block, out);
2338 if (parser->breaks.back() != label || parser->continues.back() != label) {
2339 parseerror(parser, "internal error: label stack corrupted");
2345 parser->breaks.pop_back();
2346 parser->continues.pop_back();
2351 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2354 ast_expression *cond, *ontrue;
2358 lex_ctx_t ctx = parser_ctx(parser);
2360 (void)block; /* not touching */
2362 if (!parse_statement_or_block(parser, &ontrue))
2365 /* expect the "while" */
2366 if (parser->tok != TOKEN_KEYWORD ||
2367 strcmp(parser_tokval(parser), "while"))
2369 parseerror(parser, "expected 'while' and condition");
2374 /* skip the 'while' and check for opening paren */
2375 if (!parser_next(parser) || parser->tok != '(') {
2376 parseerror(parser, "expected 'while' condition in parenthesis");
2380 /* parse into the expression */
2381 if (!parser_next(parser)) {
2382 parseerror(parser, "expected 'while' condition after opening paren");
2386 /* parse the condition */
2387 cond = parse_expression_leave(parser, false, true, false);
2391 if (parser->tok != ')') {
2392 parseerror(parser, "expected closing paren after 'while' condition");
2398 if (!parser_next(parser) || parser->tok != ';') {
2399 parseerror(parser, "expected semicolon after condition");
2405 if (!parser_next(parser)) {
2406 parseerror(parser, "parse error");
2412 cond = process_condition(parser, cond, &ifnot);
2417 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2422 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2423 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2426 char *label = nullptr;
2428 /* skip the 'for' and check for opening paren */
2429 if (!parser_next(parser)) {
2430 if (OPTS_FLAG(LOOP_LABELS))
2431 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2433 parseerror(parser, "expected 'for' expressions in parenthesis");
2437 if (parser->tok == ':') {
2438 if (!OPTS_FLAG(LOOP_LABELS))
2439 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2440 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2441 parseerror(parser, "expected loop label");
2444 label = util_strdup(parser_tokval(parser));
2445 if (!parser_next(parser)) {
2447 parseerror(parser, "expected 'for' expressions in parenthesis");
2452 if (parser->tok != '(') {
2453 parseerror(parser, "expected 'for' expressions in parenthesis");
2457 parser->breaks.push_back(label);
2458 parser->continues.push_back(label);
2460 rv = parse_for_go(parser, block, out);
2463 if (parser->breaks.back() != label || parser->continues.back() != label) {
2464 parseerror(parser, "internal error: label stack corrupted");
2470 parser->breaks.pop_back();
2471 parser->continues.pop_back();
2475 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2478 ast_expression *initexpr, *cond, *increment, *ontrue;
2483 lex_ctx_t ctx = parser_ctx(parser);
2485 parser_enterblock(parser);
2489 increment = nullptr;
2492 /* parse into the expression */
2493 if (!parser_next(parser)) {
2494 parseerror(parser, "expected 'for' initializer after opening paren");
2499 if (parser->tok == TOKEN_IDENT)
2500 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2502 if (typevar || parser->tok == TOKEN_TYPENAME) {
2503 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2506 else if (parser->tok != ';')
2508 initexpr = parse_expression_leave(parser, false, false, false);
2511 /* move on to condition */
2512 if (parser->tok != ';') {
2513 parseerror(parser, "expected semicolon after for-loop initializer");
2516 if (!parser_next(parser)) {
2517 parseerror(parser, "expected for-loop condition");
2520 } else if (!parser_next(parser)) {
2521 parseerror(parser, "expected for-loop condition");
2525 /* parse the condition */
2526 if (parser->tok != ';') {
2527 cond = parse_expression_leave(parser, false, true, false);
2531 /* move on to incrementor */
2532 if (parser->tok != ';') {
2533 parseerror(parser, "expected semicolon after for-loop initializer");
2536 if (!parser_next(parser)) {
2537 parseerror(parser, "expected for-loop condition");
2541 /* parse the incrementor */
2542 if (parser->tok != ')') {
2543 lex_ctx_t condctx = parser_ctx(parser);
2544 increment = parse_expression_leave(parser, false, false, false);
2547 if (!increment->m_side_effects) {
2548 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2554 if (parser->tok != ')') {
2555 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2558 /* parse into the 'then' branch */
2559 if (!parser_next(parser)) {
2560 parseerror(parser, "expected for-loop body");
2563 if (!parse_statement_or_block(parser, &ontrue))
2567 cond = process_condition(parser, cond, &ifnot);
2571 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2574 if (!parser_leaveblock(parser)) {
2580 if (initexpr) ast_unref(initexpr);
2581 if (cond) ast_unref(cond);
2582 if (increment) ast_unref(increment);
2583 (void)!parser_leaveblock(parser);
2587 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2589 ast_expression *exp = nullptr;
2590 ast_expression *var = nullptr;
2591 ast_return *ret = nullptr;
2592 ast_value *retval = parser->function->m_return_value;
2593 ast_value *expected = parser->function->m_function_type;
2595 lex_ctx_t ctx = parser_ctx(parser);
2597 (void)block; /* not touching */
2599 if (!parser_next(parser)) {
2600 parseerror(parser, "expected return expression");
2604 /* return assignments */
2605 if (parser->tok == '=') {
2606 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2607 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2611 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2613 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2614 parseerror(parser, "invalid return type: `%s'", ty1);
2618 if (!parser_next(parser)) {
2619 parseerror(parser, "expected return assignment expression");
2623 if (!(exp = parse_expression_leave(parser, false, false, false)))
2626 /* prepare the return value */
2628 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2629 retval->adoptType(*expected->m_next);
2630 parser->function->m_return_value = retval;
2631 parser->function->m_return_value->m_flags |= AST_FLAG_NOREF;
2634 if (!exp->compareType(*retval)) {
2635 char ty1[1024], ty2[1024];
2636 ast_type_to_string(exp, ty1, sizeof(ty1));
2637 ast_type_to_string(retval, ty2, sizeof(ty2));
2638 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2641 /* store to 'return' local variable */
2642 var = new ast_store(
2644 type_store_instr[expected->m_next->m_vtype],
2652 if (parser->tok != ';')
2653 parseerror(parser, "missing semicolon after return assignment");
2654 else if (!parser_next(parser))
2655 parseerror(parser, "parse error after return assignment");
2661 if (parser->tok != ';') {
2662 exp = parse_expression(parser, false, false);
2666 if (exp->m_vtype != TYPE_NIL &&
2667 exp->m_vtype != (expected)->m_next->m_vtype)
2669 parseerror(parser, "return with invalid expression");
2672 ret = new ast_return(ctx, exp);
2678 if (!parser_next(parser))
2679 parseerror(parser, "parse error");
2681 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2683 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2685 ret = new ast_return(ctx, retval);
2691 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2694 unsigned int levels = 0;
2695 lex_ctx_t ctx = parser_ctx(parser);
2696 auto &loops = (is_continue ? parser->continues : parser->breaks);
2698 (void)block; /* not touching */
2699 if (!parser_next(parser)) {
2700 parseerror(parser, "expected semicolon or loop label");
2704 if (loops.empty()) {
2706 parseerror(parser, "`continue` can only be used inside loops");
2708 parseerror(parser, "`break` can only be used inside loops or switches");
2711 if (parser->tok == TOKEN_IDENT) {
2712 if (!OPTS_FLAG(LOOP_LABELS))
2713 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2716 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2719 parseerror(parser, "no such loop to %s: `%s`",
2720 (is_continue ? "continue" : "break out of"),
2721 parser_tokval(parser));
2726 if (!parser_next(parser)) {
2727 parseerror(parser, "expected semicolon");
2732 if (parser->tok != ';') {
2733 parseerror(parser, "expected semicolon");
2737 if (!parser_next(parser))
2738 parseerror(parser, "parse error");
2740 *out = new ast_breakcont(ctx, is_continue, levels);
2744 /* returns true when it was a variable qualifier, false otherwise!
2745 * on error, cvq is set to CV_WRONG
2747 struct attribute_t {
2752 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2754 bool had_const = false;
2755 bool had_var = false;
2756 bool had_noref = false;
2757 bool had_attrib = false;
2758 bool had_static = false;
2761 static attribute_t attributes[] = {
2762 { "noreturn", AST_FLAG_NORETURN },
2763 { "inline", AST_FLAG_INLINE },
2764 { "eraseable", AST_FLAG_ERASEABLE },
2765 { "noerase", AST_FLAG_NOERASE },
2766 { "accumulate", AST_FLAG_ACCUMULATE },
2767 { "last", AST_FLAG_FINAL_DECL }
2774 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2776 /* parse an attribute */
2777 if (!parser_next(parser)) {
2778 parseerror(parser, "expected attribute after `[[`");
2783 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2784 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2785 flags |= attributes[i].flag;
2786 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2787 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2788 attributes[i].name);
2796 if (i != GMQCC_ARRAY_COUNT(attributes))
2799 if (!strcmp(parser_tokval(parser), "noref")) {
2801 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2802 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2807 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2808 flags |= AST_FLAG_ALIAS;
2811 if (!parser_next(parser)) {
2812 parseerror(parser, "parse error in attribute");
2816 if (parser->tok == '(') {
2817 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2818 parseerror(parser, "`alias` attribute missing parameter");
2822 *message = util_strdup(parser_tokval(parser));
2824 if (!parser_next(parser)) {
2825 parseerror(parser, "parse error in attribute");
2829 if (parser->tok != ')') {
2830 parseerror(parser, "`alias` attribute expected `)` after parameter");
2834 if (!parser_next(parser)) {
2835 parseerror(parser, "parse error in attribute");
2840 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2841 parseerror(parser, "`alias` attribute expected `]]`");
2845 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2846 flags |= AST_FLAG_DEPRECATED;
2849 if (!parser_next(parser)) {
2850 parseerror(parser, "parse error in attribute");
2854 if (parser->tok == '(') {
2855 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2856 parseerror(parser, "`deprecated` attribute missing parameter");
2860 *message = util_strdup(parser_tokval(parser));
2862 if (!parser_next(parser)) {
2863 parseerror(parser, "parse error in attribute");
2867 if(parser->tok != ')') {
2868 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2872 if (!parser_next(parser)) {
2873 parseerror(parser, "parse error in attribute");
2878 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2879 parseerror(parser, "`deprecated` attribute expected `]]`");
2882 if (*message) mem_d(*message);
2888 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2889 flags |= AST_FLAG_COVERAGE;
2890 if (!parser_next(parser)) {
2892 parseerror(parser, "parse error in coverage attribute");
2896 if (parser->tok == '(') {
2897 if (!parser_next(parser)) {
2899 parseerror(parser, "invalid parameter for coverage() attribute\n"
2900 "valid are: block");
2904 if (parser->tok != ')') {
2906 if (parser->tok != TOKEN_IDENT)
2907 goto bad_coverage_arg;
2908 if (!strcmp(parser_tokval(parser), "block"))
2909 flags |= AST_FLAG_BLOCK_COVERAGE;
2910 else if (!strcmp(parser_tokval(parser), "none"))
2911 flags &= ~(AST_FLAG_COVERAGE_MASK);
2913 goto bad_coverage_arg;
2914 if (!parser_next(parser))
2915 goto error_in_coverage;
2916 if (parser->tok == ',') {
2917 if (!parser_next(parser))
2918 goto error_in_coverage;
2920 } while (parser->tok != ')');
2922 if (parser->tok != ')' || !parser_next(parser))
2923 goto error_in_coverage;
2925 /* without parameter [[coverage]] equals [[coverage(block)]] */
2926 flags |= AST_FLAG_BLOCK_COVERAGE;
2931 /* Skip tokens until we hit a ]] */
2932 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2933 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2934 if (!parser_next(parser)) {
2935 parseerror(parser, "error inside attribute");
2942 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2944 else if (!strcmp(parser_tokval(parser), "const"))
2946 else if (!strcmp(parser_tokval(parser), "var"))
2948 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2950 else if (!strcmp(parser_tokval(parser), "noref"))
2952 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2959 if (!parser_next(parser))
2969 *is_static = had_static;
2973 parseerror(parser, "parse error after variable qualifier");
2978 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2979 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2982 char *label = nullptr;
2984 /* skip the 'while' and get the body */
2985 if (!parser_next(parser)) {
2986 if (OPTS_FLAG(LOOP_LABELS))
2987 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2989 parseerror(parser, "expected 'switch' operand in parenthesis");
2993 if (parser->tok == ':') {
2994 if (!OPTS_FLAG(LOOP_LABELS))
2995 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2996 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2997 parseerror(parser, "expected loop label");
3000 label = util_strdup(parser_tokval(parser));
3001 if (!parser_next(parser)) {
3003 parseerror(parser, "expected 'switch' operand in parenthesis");
3008 if (parser->tok != '(') {
3009 parseerror(parser, "expected 'switch' operand in parenthesis");
3013 parser->breaks.push_back(label);
3015 rv = parse_switch_go(parser, block, out);
3018 if (parser->breaks.back() != label) {
3019 parseerror(parser, "internal error: label stack corrupted");
3025 parser->breaks.pop_back();
3030 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3032 ast_expression *operand;
3035 ast_switch *switchnode;
3036 ast_switch_case swcase;
3039 bool noref, is_static;
3040 uint32_t qflags = 0;
3042 lex_ctx_t ctx = parser_ctx(parser);
3044 (void)block; /* not touching */
3047 /* parse into the expression */
3048 if (!parser_next(parser)) {
3049 parseerror(parser, "expected switch operand");
3052 /* parse the operand */
3053 operand = parse_expression_leave(parser, false, false, false);
3057 switchnode = new ast_switch(ctx, operand);
3060 if (parser->tok != ')') {
3062 parseerror(parser, "expected closing paren after 'switch' operand");
3066 /* parse over the opening paren */
3067 if (!parser_next(parser) || parser->tok != '{') {
3069 parseerror(parser, "expected list of cases");
3073 if (!parser_next(parser)) {
3075 parseerror(parser, "expected 'case' or 'default'");
3079 /* new block; allow some variables to be declared here */
3080 parser_enterblock(parser);
3083 if (parser->tok == TOKEN_IDENT)
3084 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3085 if (typevar || parser->tok == TOKEN_TYPENAME) {
3086 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3092 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3094 if (cvq == CV_WRONG) {
3098 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3108 while (parser->tok != '}') {
3109 ast_block *caseblock;
3111 if (!strcmp(parser_tokval(parser), "case")) {
3112 if (!parser_next(parser)) {
3114 parseerror(parser, "expected expression for case");
3117 swcase.m_value = parse_expression_leave(parser, false, false, false);
3119 if (!operand->compareType(*swcase.m_value)) {
3123 ast_type_to_string(swcase.m_value, ty1, sizeof ty1);
3124 ast_type_to_string(operand, ty2, sizeof ty2);
3126 auto fnLiteral = [](ast_expression *expression) -> char* {
3127 if (!ast_istype(expression, ast_value))
3129 ast_value *value = (ast_value *)expression;
3130 if (!value->m_hasvalue)
3132 char *string = nullptr;
3133 basic_value_t *constval = &value->m_constval;
3134 switch (value->m_vtype)
3137 util_asprintf(&string, "%.2f", constval->vfloat);
3140 util_asprintf(&string, "'%.2f %.2f %.2f'",
3146 util_asprintf(&string, "\"%s\"", constval->vstring);
3154 char *literal = fnLiteral(swcase.m_value);
3156 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case `%s` expected `%s`", ty1, literal, ty2);
3158 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case expected `%s`", ty1, ty2);
3164 if (!swcase.m_value) {
3166 parseerror(parser, "expected expression for case");
3169 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3170 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3172 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3178 else if (!strcmp(parser_tokval(parser), "default")) {
3179 swcase.m_value = nullptr;
3180 if (!parser_next(parser)) {
3182 parseerror(parser, "expected colon");
3188 parseerror(parser, "expected 'case' or 'default'");
3192 /* Now the colon and body */
3193 if (parser->tok != ':') {
3194 if (swcase.m_value) ast_unref(swcase.m_value);
3196 parseerror(parser, "expected colon");
3200 if (!parser_next(parser)) {
3201 if (swcase.m_value) ast_unref(swcase.m_value);
3203 parseerror(parser, "expected statements or case");
3206 caseblock = new ast_block(parser_ctx(parser));
3208 if (swcase.m_value) ast_unref(swcase.m_value);
3212 swcase.m_code = caseblock;
3213 switchnode->m_cases.push_back(swcase);
3215 ast_expression *expr;
3216 if (parser->tok == '}')
3218 if (parser->tok == TOKEN_KEYWORD) {
3219 if (!strcmp(parser_tokval(parser), "case") ||
3220 !strcmp(parser_tokval(parser), "default"))
3225 if (!parse_statement(parser, caseblock, &expr, true)) {
3231 if (!caseblock->addExpr(expr)) {
3238 parser_leaveblock(parser);
3241 if (parser->tok != '}') {
3243 parseerror(parser, "expected closing paren of case list");
3246 if (!parser_next(parser)) {
3248 parseerror(parser, "parse error after switch");
3255 /* parse computed goto sides */
3256 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3257 ast_expression *on_true;
3258 ast_expression *on_false;
3259 ast_expression *cond;
3264 if (ast_istype(*side, ast_ternary)) {
3265 ast_ternary *tern = (ast_ternary*)*side;
3266 on_true = parse_goto_computed(parser, &tern->m_on_true);
3267 on_false = parse_goto_computed(parser, &tern->m_on_false);
3269 if (!on_true || !on_false) {
3270 parseerror(parser, "expected label or expression in ternary");
3271 if (on_true) ast_unref(on_true);
3272 if (on_false) ast_unref(on_false);
3276 cond = tern->m_cond;
3277 tern->m_cond = nullptr;
3280 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3281 } else if (ast_istype(*side, ast_label)) {
3282 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3283 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3290 static bool parse_goto(parser_t *parser, ast_expression **out)
3292 ast_goto *gt = nullptr;
3293 ast_expression *lbl;
3295 if (!parser_next(parser))
3298 if (parser->tok != TOKEN_IDENT) {
3299 ast_expression *expression;
3301 /* could be an expression i.e computed goto :-) */
3302 if (parser->tok != '(') {
3303 parseerror(parser, "expected label name after `goto`");
3307 /* failed to parse expression for goto */
3308 if (!(expression = parse_expression(parser, false, true)) ||
3309 !(*out = parse_goto_computed(parser, &expression))) {
3310 parseerror(parser, "invalid goto expression");
3312 ast_unref(expression);
3319 /* not computed goto */
3320 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3321 lbl = parser_find_label(parser, gt->m_name);
3323 if (!ast_istype(lbl, ast_label)) {
3324 parseerror(parser, "internal error: label is not an ast_label");
3328 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3331 parser->gotos.push_back(gt);
3333 if (!parser_next(parser) || parser->tok != ';') {
3334 parseerror(parser, "semicolon expected after goto label");
3337 if (!parser_next(parser)) {
3338 parseerror(parser, "parse error after goto");
3346 static bool parse_skipwhite(parser_t *parser)
3349 if (!parser_next(parser))
3351 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3352 return parser->tok < TOKEN_ERROR;
3355 static bool parse_eol(parser_t *parser)
3357 if (!parse_skipwhite(parser))
3359 return parser->tok == TOKEN_EOL;
3362 static bool parse_pragma_do(parser_t *parser)
3364 if (!parser_next(parser) ||
3365 parser->tok != TOKEN_IDENT ||
3366 strcmp(parser_tokval(parser), "pragma"))
3368 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3371 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3372 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3376 if (!strcmp(parser_tokval(parser), "noref")) {
3377 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3378 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3381 parser->noref = !!parser_token(parser)->constval.i;
3382 if (!parse_eol(parser)) {
3383 parseerror(parser, "parse error after `noref` pragma");
3389 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3392 while (!parse_eol(parser)) {
3393 parser_next(parser);
3402 static bool parse_pragma(parser_t *parser)
3405 parser->lex->flags.preprocessing = true;
3406 parser->lex->flags.mergelines = true;
3407 rv = parse_pragma_do(parser);
3408 if (parser->tok != TOKEN_EOL) {
3409 parseerror(parser, "junk after pragma");
3412 parser->lex->flags.preprocessing = false;
3413 parser->lex->flags.mergelines = false;
3414 if (!parser_next(parser)) {
3415 parseerror(parser, "parse error after pragma");
3421 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3423 bool noref, is_static;
3425 uint32_t qflags = 0;
3426 ast_value *typevar = nullptr;
3427 char *vstring = nullptr;
3431 if (parser->tok == TOKEN_IDENT)
3432 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3434 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3436 /* local variable */
3438 parseerror(parser, "cannot declare a variable from here");
3441 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3442 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3445 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3449 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3451 if (cvq == CV_WRONG)
3453 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3455 else if (parser->tok == TOKEN_KEYWORD)
3457 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3462 if (!parser_next(parser)) {
3463 parseerror(parser, "parse error after __builtin_debug_printtype");
3467 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3469 ast_type_to_string(tdef, ty, sizeof(ty));
3470 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3471 if (!parser_next(parser)) {
3472 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3478 if (!parse_statement(parser, block, out, allow_cases))
3481 con_out("__builtin_debug_printtype: got no output node\n");
3484 ast_type_to_string(*out, ty, sizeof(ty));
3485 con_out("__builtin_debug_printtype: `%s`\n", ty);
3490 else if (!strcmp(parser_tokval(parser), "return"))
3492 return parse_return(parser, block, out);
3494 else if (!strcmp(parser_tokval(parser), "if"))
3496 return parse_if(parser, block, out);
3498 else if (!strcmp(parser_tokval(parser), "while"))
3500 return parse_while(parser, block, out);
3502 else if (!strcmp(parser_tokval(parser), "do"))
3504 return parse_dowhile(parser, block, out);
3506 else if (!strcmp(parser_tokval(parser), "for"))
3508 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3509 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3512 return parse_for(parser, block, out);
3514 else if (!strcmp(parser_tokval(parser), "break"))
3516 return parse_break_continue(parser, block, out, false);
3518 else if (!strcmp(parser_tokval(parser), "continue"))
3520 return parse_break_continue(parser, block, out, true);
3522 else if (!strcmp(parser_tokval(parser), "switch"))
3524 return parse_switch(parser, block, out);
3526 else if (!strcmp(parser_tokval(parser), "case") ||
3527 !strcmp(parser_tokval(parser), "default"))
3530 parseerror(parser, "unexpected 'case' label");
3535 else if (!strcmp(parser_tokval(parser), "goto"))
3537 return parse_goto(parser, out);
3539 else if (!strcmp(parser_tokval(parser), "typedef"))
3541 if (!parser_next(parser)) {
3542 parseerror(parser, "expected type definition after 'typedef'");
3545 return parse_typedef(parser);
3547 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3550 else if (parser->tok == '{')
3552 return parse_statement_or_block(parser, out);
3554 else if (parser->tok == ':')
3558 if (!parser_next(parser)) {
3559 parseerror(parser, "expected label name");
3562 if (parser->tok != TOKEN_IDENT) {
3563 parseerror(parser, "label must be an identifier");
3566 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3568 if (!label->m_undefined) {
3569 parseerror(parser, "label `%s` already defined", label->m_name);
3572 label->m_undefined = false;
3575 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3576 parser->labels.push_back(label);
3579 if (!parser_next(parser)) {
3580 parseerror(parser, "parse error after label");
3583 for (i = 0; i < parser->gotos.size(); ++i) {
3584 if (parser->gotos[i]->m_name == label->m_name) {
3585 parser->gotos[i]->setLabel(label);
3586 parser->gotos.erase(parser->gotos.begin() + i);
3592 else if (parser->tok == ';')
3594 if (!parser_next(parser)) {
3595 parseerror(parser, "parse error after empty statement");
3602 lex_ctx_t ctx = parser_ctx(parser);
3603 ast_expression *exp = parse_expression(parser, false, false);
3607 if (!exp->m_side_effects) {
3608 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3615 static bool parse_enum(parser_t *parser)
3618 bool reverse = false;
3620 ast_value *var = nullptr;
3622 std::vector<ast_value*> values;
3624 ast_expression *old;
3626 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3627 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3631 /* enumeration attributes (can add more later) */
3632 if (parser->tok == ':') {
3633 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3634 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3639 if (!strcmp(parser_tokval(parser), "flag")) {
3643 else if (!strcmp(parser_tokval(parser), "reverse")) {
3647 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3651 if (!parser_next(parser) || parser->tok != '{') {
3652 parseerror(parser, "expected `{` after enum attribute ");
3658 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3659 if (parser->tok == '}') {
3660 /* allow an empty enum */
3663 parseerror(parser, "expected identifier or `}`");
3667 old = parser_find_field(parser, parser_tokval(parser));
3669 old = parser_find_global(parser, parser_tokval(parser));
3671 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3672 parser_tokval(parser), old->m_context.file, old->m_context.line);
3676 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3677 values.push_back(var);
3678 var->m_cvq = CV_CONST;
3679 var->m_hasvalue = true;
3681 /* for flagged enumerations increment in POTs of TWO */
3682 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3683 parser_addglobal(parser, var->m_name, var);
3685 if (!parser_next(parser)) {
3686 parseerror(parser, "expected `=`, `}` or comma after identifier");
3690 if (parser->tok == ',')
3692 if (parser->tok == '}')
3694 if (parser->tok != '=') {
3695 parseerror(parser, "expected `=`, `}` or comma after identifier");
3699 if (!parser_next(parser)) {
3700 parseerror(parser, "expected expression after `=`");
3704 /* We got a value! */
3705 old = parse_expression_leave(parser, true, false, false);
3706 asvalue = (ast_value*)old;
3707 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3708 compile_error(var->m_context, "constant value or expression expected");
3711 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3713 if (parser->tok == '}')
3715 if (parser->tok != ',') {
3716 parseerror(parser, "expected `}` or comma after expression");
3721 /* patch them all (for reversed attribute) */
3724 for (i = 0; i < values.size(); i++)
3725 values[i]->m_constval.vfloat = values.size() - i - 1;
3728 if (parser->tok != '}') {
3729 parseerror(parser, "internal error: breaking without `}`");
3733 if (!parser_next(parser) || parser->tok != ';') {
3734 parseerror(parser, "expected semicolon after enumeration");
3738 if (!parser_next(parser)) {
3739 parseerror(parser, "parse error after enumeration");
3746 static bool parse_block_into(parser_t *parser, ast_block *block)
3750 parser_enterblock(parser);
3752 if (!parser_next(parser)) { /* skip the '{' */
3753 parseerror(parser, "expected function body");
3757 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3759 ast_expression *expr = nullptr;
3760 if (parser->tok == '}')
3763 if (!parse_statement(parser, block, &expr, false)) {
3764 /* parseerror(parser, "parse error"); */
3770 if (!block->addExpr(expr)) {
3777 if (parser->tok != '}') {
3780 (void)parser_next(parser);
3784 if (!parser_leaveblock(parser))
3786 return retval && !!block;
3789 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3792 std::unique_ptr<ast_block> block(new ast_block(parser_ctx(parser)));
3793 if (parser->tok == '{') {
3794 if (!parse_block_into(parser, block.get())) {
3798 parser_enterblock(parser);
3800 ast_expression* expression = nullptr;
3801 if (!parse_statement(parser, block.get(), &expression, false)) {
3805 if (expression && !block->addExpr(expression)) {
3809 if (!parser_leaveblock(parser)) {
3815 *out = block.release();
3822 static bool create_vector_members(ast_value *var, ast_member **me)
3825 size_t len = var->m_name.length();
3827 for (i = 0; i < 3; ++i) {
3828 char *name = (char*)mem_a(len+3);
3829 memcpy(name, var->m_name.c_str(), len);
3831 name[len+1] = 'x'+i;
3833 me[i] = ast_member::make(var->m_context, var, i, name);
3842 do { delete me[--i]; } while(i);
3846 static bool parse_function_body(parser_t *parser, ast_value *var)
3848 ast_block *block = nullptr;
3852 ast_expression *framenum = nullptr;
3853 ast_expression *nextthink = nullptr;
3854 /* None of the following have to be deleted */
3855 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3856 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3857 bool has_frame_think;
3861 has_frame_think = false;
3862 old = parser->function;
3864 if (var->m_flags & AST_FLAG_ALIAS) {
3865 parseerror(parser, "function aliases cannot have bodies");
3869 if (parser->gotos.size() || parser->labels.size()) {
3870 parseerror(parser, "gotos/labels leaking");
3874 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3875 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3876 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3882 if (parser->tok == '[') {
3883 /* got a frame definition: [ framenum, nextthink ]
3884 * this translates to:
3885 * self.frame = framenum;
3886 * self.nextthink = time + 0.1;
3887 * self.think = nextthink;
3889 nextthink = nullptr;
3891 fld_think = parser_find_field(parser, "think");
3892 fld_nextthink = parser_find_field(parser, "nextthink");
3893 fld_frame = parser_find_field(parser, "frame");
3894 if (!fld_think || !fld_nextthink || !fld_frame) {
3895 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3896 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3899 gbl_time = parser_find_global(parser, "time");
3900 gbl_self = parser_find_global(parser, "self");
3901 if (!gbl_time || !gbl_self) {
3902 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3903 parseerror(parser, "please declare the following globals: `time`, `self`");
3907 if (!parser_next(parser))
3910 framenum = parse_expression_leave(parser, true, false, false);
3912 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3915 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3916 ast_unref(framenum);
3917 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3921 if (parser->tok != ',') {
3922 ast_unref(framenum);
3923 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3924 parseerror(parser, "Got a %i\n", parser->tok);
3928 if (!parser_next(parser)) {
3929 ast_unref(framenum);
3933 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3935 /* qc allows the use of not-yet-declared functions here
3936 * - this automatically creates a prototype */
3937 ast_value *thinkfunc;
3938 ast_expression *functype = fld_think->m_next;
3940 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3941 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3942 ast_unref(framenum);
3943 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3946 thinkfunc->adoptType(*functype);
3948 if (!parser_next(parser)) {
3949 ast_unref(framenum);
3954 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3956 nextthink = thinkfunc;
3959 nextthink = parse_expression_leave(parser, true, false, false);
3961 ast_unref(framenum);
3962 parseerror(parser, "expected a think-function in [frame,think] notation");
3967 if (!ast_istype(nextthink, ast_value)) {
3968 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3972 if (retval && parser->tok != ']') {
3973 parseerror(parser, "expected closing `]` for [frame,think] notation");
3977 if (retval && !parser_next(parser)) {
3981 if (retval && parser->tok != '{') {
3982 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3987 ast_unref(nextthink);
3988 ast_unref(framenum);
3992 has_frame_think = true;
3995 block = new ast_block(parser_ctx(parser));
3997 parseerror(parser, "failed to allocate block");
3998 if (has_frame_think) {
3999 ast_unref(nextthink);
4000 ast_unref(framenum);
4005 if (has_frame_think) {
4006 if (!OPTS_FLAG(EMULATE_STATE)) {
4007 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
4008 if (!block->addExpr(state_op)) {
4009 parseerror(parser, "failed to generate state op for [frame,think]");
4010 ast_unref(nextthink);
4011 ast_unref(framenum);
4016 /* emulate OP_STATE in code: */
4018 ast_expression *self_frame;
4019 ast_expression *self_nextthink;
4020 ast_expression *self_think;
4021 ast_expression *time_plus_1;
4022 ast_store *store_frame;
4023 ast_store *store_nextthink;
4024 ast_store *store_think;
4026 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4028 ctx = parser_ctx(parser);
4029 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
4030 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4031 self_think = new ast_entfield(ctx, gbl_self, fld_think);
4033 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
4034 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4036 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4037 if (self_frame) delete self_frame;
4038 if (self_nextthink) delete self_nextthink;
4039 if (self_think) delete self_think;
4040 if (time_plus_1) delete time_plus_1;
4046 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4047 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4048 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4054 if (!store_nextthink) {
4055 delete self_nextthink;
4063 if (store_frame) delete store_frame;
4064 if (store_nextthink) delete store_nextthink;
4065 if (store_think) delete store_think;
4068 if (!block->addExpr(store_frame) ||
4069 !block->addExpr(store_nextthink) ||
4070 !block->addExpr(store_think))
4077 parseerror(parser, "failed to generate code for [frame,think]");
4078 ast_unref(nextthink);
4079 ast_unref(framenum);
4086 if (var->m_hasvalue) {
4087 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4088 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4092 func = var->m_constval.vfunc;
4095 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4100 func = ast_function::make(var->m_context, var->m_name, var);
4103 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4107 parser->functions.push_back(func);
4110 parser_enterblock(parser);
4112 for (auto &it : var->m_type_params) {
4116 if (it->m_vtype != TYPE_VECTOR &&
4117 (it->m_vtype != TYPE_FIELD ||
4118 it->m_next->m_vtype != TYPE_VECTOR))
4123 if (!create_vector_members(it.get(), me)) {
4128 for (e = 0; e < 3; ++e) {
4129 parser_addlocal(parser, me[e]->m_name, me[e]);
4130 block->collect(me[e]);
4134 if (var->m_argcounter && !func->m_argc) {
4135 ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT);
4136 parser_addlocal(parser, argc->m_name, argc);
4137 func->m_argc.reset(argc);
4140 if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4142 ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY);
4143 varargs->m_flags |= AST_FLAG_IS_VARARG;
4144 varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR);
4145 varargs->m_count = 0;
4146 util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str());
4147 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4152 util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str());
4153 if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4158 func->m_varargs.reset(varargs);
4159 func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4162 parser->function = func;
4163 if (!parse_block_into(parser, block)) {
4168 func->m_blocks.emplace_back(block);
4170 parser->function = old;
4171 if (!parser_leaveblock(parser))
4173 if (parser->variables.size() != PARSER_HT_LOCALS) {
4174 parseerror(parser, "internal error: local scopes left");
4178 if (parser->tok == ';')
4179 return parser_next(parser);
4180 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4181 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4185 (void)!parser_leaveblock(parser);
4189 // Remove |func| from |parser->functions|. It may not actually be at the
4190 // back of the vector for accumulated functions.
4191 for (auto it = parser->functions.begin(); it != parser->functions.end(); it++) {
4193 parser->functions.erase(it, it + 1);
4198 var->m_constval.vfunc = nullptr;
4201 parser->function = old;
4205 static ast_expression *array_accessor_split(
4210 ast_expression *left,
4211 ast_expression *right
4217 lex_ctx_t ctx = array->m_context;
4219 if (!left || !right) {
4220 if (left) delete left;
4221 if (right) delete right;
4225 cmp = new ast_binary(ctx, INSTR_LT,
4227 parser->m_fold.constgen_float(middle, false));
4231 parseerror(parser, "internal error: failed to create comparison for array setter");
4235 ifthen = new ast_ifthen(ctx, cmp, left, right);
4237 delete cmp; /* will delete left and right */
4238 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4245 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4247 lex_ctx_t ctx = array->m_context;
4249 if (from+1 == afterend) {
4250 /* set this value */
4253 ast_array_index *subscript;
4255 int assignop = type_store_instr[value->m_vtype];
4257 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4258 assignop = INSTR_STORE_V;
4260 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4264 st = new ast_store(ctx, assignop, subscript, value);
4270 block = new ast_block(ctx);
4276 if (!block->addExpr(st)) {
4281 ret = new ast_return(ctx, nullptr);
4287 if (!block->addExpr(ret)) {
4294 ast_expression *left, *right;
4295 size_t diff = afterend - from;
4296 size_t middle = from + diff/2;
4297 left = array_setter_node(parser, array, index, value, from, middle);
4298 right = array_setter_node(parser, array, index, value, middle, afterend);
4299 return array_accessor_split(parser, array, index, middle, left, right);
4303 static ast_expression *array_field_setter_node(
4312 lex_ctx_t ctx = array->m_context;
4314 if (from+1 == afterend) {
4315 /* set this value */
4318 ast_entfield *entfield;
4319 ast_array_index *subscript;
4321 int assignop = type_storep_instr[value->m_vtype];
4323 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4324 assignop = INSTR_STOREP_V;
4326 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4330 subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript);
4331 subscript->m_vtype = TYPE_FIELD;
4333 entfield = new ast_entfield(ctx, entity, subscript, subscript);
4339 st = new ast_store(ctx, assignop, entfield, value);
4345 block = new ast_block(ctx);
4351 if (!block->addExpr(st)) {
4356 ret = new ast_return(ctx, nullptr);
4362 if (!block->addExpr(ret)) {
4369 ast_expression *left, *right;
4370 size_t diff = afterend - from;
4371 size_t middle = from + diff/2;
4372 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4373 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4374 return array_accessor_split(parser, array, index, middle, left, right);
4378 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4380 lex_ctx_t ctx = array->m_context;
4382 if (from+1 == afterend) {
4384 ast_array_index *subscript;
4386 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4390 ret = new ast_return(ctx, subscript);
4398 ast_expression *left, *right;
4399 size_t diff = afterend - from;
4400 size_t middle = from + diff/2;
4401 left = array_getter_node(parser, array, index, from, middle);
4402 right = array_getter_node(parser, array, index, middle, afterend);
4403 return array_accessor_split(parser, array, index, middle, left, right);
4407 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4409 ast_function *func = nullptr;
4410 ast_value *fval = nullptr;
4411 ast_block *body = nullptr;
4413 fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION);
4415 parseerror(parser, "failed to create accessor function value");
4418 fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4420 func = ast_function::make(array->m_context, funcname, fval);
4423 parseerror(parser, "failed to create accessor function node");
4427 body = new ast_block(array->m_context);
4429 parseerror(parser, "failed to create block for array accessor");
4435 func->m_blocks.emplace_back(body);
4438 parser->accessors.push_back(fval);
4443 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4445 ast_value *index = nullptr;
4446 ast_value *value = nullptr;
4450 if (!ast_istype(array->m_next, ast_value)) {
4451 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4455 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4457 func = fval->m_constval.vfunc;
4458 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4460 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4461 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4463 if (!index || !value) {
4464 parseerror(parser, "failed to create locals for array accessor");
4467 value->m_name = "value"; // not important
4468 fval->m_type_params.emplace_back(index);
4469 fval->m_type_params.emplace_back(value);
4471 array->m_setter = fval;
4474 if (index) delete index;
4475 if (value) delete value;
4481 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4483 ast_expression *root = nullptr;
4484 root = array_setter_node(parser, array,
4485 array->m_setter->m_type_params[0].get(),
4486 array->m_setter->m_type_params[1].get(),
4489 parseerror(parser, "failed to build accessor search tree");
4492 if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4499 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4501 if (!parser_create_array_setter_proto(parser, array, funcname))
4503 return parser_create_array_setter_impl(parser, array);
4506 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4508 ast_expression *root = nullptr;
4509 ast_value *entity = nullptr;
4510 ast_value *index = nullptr;
4511 ast_value *value = nullptr;
4515 if (!ast_istype(array->m_next, ast_value)) {
4516 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4520 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4522 func = fval->m_constval.vfunc;
4523 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4525 entity = new ast_value(array->m_context, "entity", TYPE_ENTITY);
4526 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4527 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4528 if (!entity || !index || !value) {
4529 parseerror(parser, "failed to create locals for array accessor");
4532 value->m_name = "value"; // not important
4533 fval->m_type_params.emplace_back(entity);
4534 fval->m_type_params.emplace_back(index);
4535 fval->m_type_params.emplace_back(value);
4537 root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4539 parseerror(parser, "failed to build accessor search tree");
4543 array->m_setter = fval;
4544 return func->m_blocks[0].get()->addExpr(root);
4546 if (entity) delete entity;
4547 if (index) delete index;
4548 if (value) delete value;
4549 if (root) delete root;
4555 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4557 ast_value *index = nullptr;
4561 /* NOTE: checking array->m_next rather than elemtype since
4562 * for fields elemtype is a temporary fieldtype.
4564 if (!ast_istype(array->m_next, ast_value)) {
4565 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4569 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4571 func = fval->m_constval.vfunc;
4572 fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype);
4574 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4577 parseerror(parser, "failed to create locals for array accessor");
4580 fval->m_type_params.emplace_back(index);
4582 array->m_getter = fval;
4585 if (index) delete index;
4591 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4593 ast_expression *root = nullptr;
4595 root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count);
4597 parseerror(parser, "failed to build accessor search tree");
4600 if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4607 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4609 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4611 return parser_create_array_getter_impl(parser, array);
4614 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4616 lex_ctx_t ctx = parser_ctx(parser);
4617 std::vector<std::unique_ptr<ast_value>> params;
4620 bool variadic = false;
4621 ast_value *varparam = nullptr;
4622 char *argcounter = nullptr;
4624 /* for the sake of less code we parse-in in this function */
4625 if (!parser_next(parser)) {
4627 parseerror(parser, "expected parameter list");
4631 /* parse variables until we hit a closing paren */
4632 while (parser->tok != ')') {
4633 bool is_varargs = false;
4636 /* there must be commas between them */
4637 if (parser->tok != ',') {
4638 parseerror(parser, "expected comma or end of parameter list");
4641 if (!parser_next(parser)) {
4642 parseerror(parser, "expected parameter");
4648 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4649 if (!param && !is_varargs)
4652 /* '...' indicates a varargs function */
4654 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4655 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4658 if (parser->tok == TOKEN_IDENT) {
4659 argcounter = util_strdup(parser_tokval(parser));
4660 if (!parser_next(parser) || parser->tok != ')') {
4661 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4666 params.emplace_back(param);
4667 if (param->m_vtype >= TYPE_VARIANT) {
4668 char tname[1024]; /* typename is reserved in C++ */
4669 ast_type_to_string(param, tname, sizeof(tname));
4670 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4673 /* type-restricted varargs */
4674 if (parser->tok == TOKEN_DOTS) {
4676 varparam = params.back().release();
4678 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4679 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4682 if (parser->tok == TOKEN_IDENT) {
4683 argcounter = util_strdup(parser_tokval(parser));
4684 param->m_name = argcounter;
4685 if (!parser_next(parser) || parser->tok != ')') {
4686 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4691 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4692 parseerror(parser, "parameter name omitted");
4698 if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4702 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4703 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4706 if (!parser_next(parser)) {
4707 parseerror(parser, "parse error after typename");
4711 /* now turn 'var' into a function type */
4712 fval = new ast_value(ctx, "<type()>", TYPE_FUNCTION);
4715 fval->m_flags |= AST_FLAG_VARIADIC;
4718 var->m_type_params = move(params);
4719 var->m_varparam = varparam;
4720 var->m_argcounter = argcounter;
4733 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4735 ast_expression *cexp;
4736 ast_value *cval, *tmp;
4739 ctx = parser_ctx(parser);
4741 if (!parser_next(parser)) {
4743 parseerror(parser, "expected array-size");
4747 if (parser->tok != ']') {
4748 cexp = parse_expression_leave(parser, true, false, false);
4750 if (!cexp || !ast_istype(cexp, ast_value)) {
4754 parseerror(parser, "expected array-size as constant positive integer");
4757 cval = (ast_value*)cexp;
4764 tmp = new ast_value(ctx, "<type[]>", TYPE_ARRAY);
4769 if (cval->m_vtype == TYPE_INTEGER)
4770 tmp->m_count = cval->m_constval.vint;
4771 else if (cval->m_vtype == TYPE_FLOAT)
4772 tmp->m_count = cval->m_constval.vfloat;
4776 parseerror(parser, "array-size must be a positive integer constant");
4783 var->m_flags |= AST_FLAG_ARRAY_INIT;
4786 if (parser->tok != ']') {
4788 parseerror(parser, "expected ']' after array-size");
4791 if (!parser_next(parser)) {
4793 parseerror(parser, "error after parsing array size");
4799 /* Parse a complete typename.
4800 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4801 * but when parsing variables separated by comma
4802 * 'storebase' should point to where the base-type should be kept.
4803 * The base type makes up every bit of type information which comes *before* the
4806 * NOTE: The value must either be named, have a nullptr name, or a name starting
4807 * with '<'. In the first case, this will be the actual variable or type
4808 * name, in the other cases it is assumed that the name will appear
4809 * later, and an error is generated otherwise.
4811 * The following will be parsed in its entirety:
4813 * The 'basetype' in this case is 'void()'
4814 * and if there's a comma after it, say:
4816 * then the type-information 'void()' can be stored in 'storebase'
4818 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4820 ast_value *var, *tmp;
4823 const char *name = nullptr;
4824 bool isfield = false;
4825 bool wasarray = false;
4826 size_t morefields = 0;
4828 bool vararg = (parser->tok == TOKEN_DOTS);
4830 ctx = parser_ctx(parser);
4832 /* types may start with a dot */
4833 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4835 if (parser->tok == TOKEN_DOTS)
4837 /* if we parsed a dot we need a typename now */
4838 if (!parser_next(parser)) {
4839 parseerror(parser, "expected typename for field definition");
4843 /* Further dots are handled seperately because they won't be part of the
4847 if (parser->tok == '.')
4849 else if (parser->tok == TOKEN_DOTS)
4854 if (!parser_next(parser)) {
4855 parseerror(parser, "expected typename for field definition");
4860 if (parser->tok == TOKEN_IDENT)
4861 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4862 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4863 if (vararg && is_vararg) {
4867 parseerror(parser, "expected typename");
4871 /* generate the basic type value */
4872 if (cached_typedef) {
4873 var = new ast_value(ast_copy_type, *cached_typedef);
4874 var->m_name = "<type(from_def)>";
4876 var = new ast_value(ctx, "<type>", parser_token(parser)->constval.t);
4878 for (; morefields; --morefields) {
4879 tmp = new ast_value(ctx, "<.type>", TYPE_FIELD);
4884 /* do not yet turn into a field - remember:
4885 * .void() foo; is a field too
4886 * .void()() foo; is a function
4890 if (!parser_next(parser)) {
4892 parseerror(parser, "parse error after typename");
4896 /* an opening paren now starts the parameter-list of a function
4897 * this is where original-QC has parameter lists.
4898 * We allow a single parameter list here.
4899 * Much like fteqcc we don't allow `float()() x`
4901 if (parser->tok == '(') {
4902 var = parse_parameter_list(parser, var);
4907 /* store the base if requested */
4909 *storebase = new ast_value(ast_copy_type, *var);
4911 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4912 tmp->m_next = *storebase;
4917 /* there may be a name now */
4918 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4919 if (!strcmp(parser_tokval(parser), "break"))
4920 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4921 else if (parser->tok == TOKEN_KEYWORD)
4924 name = util_strdup(parser_tokval(parser));
4927 if (!parser_next(parser)) {
4930 parseerror(parser, "error after variable or field declaration");
4936 /* now this may be an array */
4937 if (parser->tok == '[') {
4939 var = parse_arraysize(parser, var);
4941 if (name) mem_d(name);
4946 /* This is the point where we can turn it into a field */
4948 /* turn it into a field if desired */
4949 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4954 /* now there may be function parens again */
4955 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4956 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4957 if (parser->tok == '(' && wasarray)
4958 parseerror(parser, "arrays as part of a return type is not supported");
4959 while (parser->tok == '(') {
4960 var = parse_parameter_list(parser, var);
4962 if (name) mem_d(name);
4967 /* finally name it */
4970 // free the name, ast_value_set_name duplicates
4977 static bool parse_typedef(parser_t *parser)
4979 ast_value *typevar, *oldtype;
4980 ast_expression *old;
4982 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4987 // while parsing types, the ast_value's get named '<something>'
4988 if (!typevar->m_name.length() || typevar->m_name[0] == '<') {
4989 parseerror(parser, "missing name in typedef");
4994 if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4995 parseerror(parser, "cannot define a type with the same name as a variable:\n"
4996 " -> `%s` has been declared here: %s:%i",
4997 typevar->m_name, old->m_context.file, old->m_context.line);
5002 if ( (oldtype = parser_find_typedef(parser, typevar->m_name, parser->_blocktypedefs.back())) ) {
5003 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5004 typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
5009 parser->_typedefs.emplace_back(typevar);
5010 util_htset(parser->typedefs.back(), typevar->m_name.c_str(), typevar);
5012 if (parser->tok != ';') {
5013 parseerror(parser, "expected semicolon after typedef");
5016 if (!parser_next(parser)) {
5017 parseerror(parser, "parse error after typedef");
5024 static const char *cvq_to_str(int cvq) {
5026 case CV_NONE: return "none";
5027 case CV_VAR: return "`var`";
5028 case CV_CONST: return "`const`";
5029 default: return "<INVALID>";
5033 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5036 if (proto->m_cvq != var->m_cvq) {
5037 if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
5038 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5039 parser->tok == '='))
5041 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5042 "`%s` declared with different qualifiers: %s\n"
5043 " -> previous declaration here: %s:%i uses %s",
5044 var->m_name, cvq_to_str(var->m_cvq),
5045 proto->m_context.file, proto->m_context.line,
5046 cvq_to_str(proto->m_cvq));
5049 av = (var ->m_flags & AST_FLAG_NORETURN);
5050 ao = (proto->m_flags & AST_FLAG_NORETURN);
5052 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5053 "`%s` declared with different attributes%s\n"
5054 " -> previous declaration here: %s:%i",
5055 var->m_name, (av ? ": noreturn" : ""),
5056 proto->m_context.file, proto->m_context.line,
5057 (ao ? ": noreturn" : ""));
5062 static bool create_array_accessors(parser_t *parser, ast_value *var)
5065 util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str());
5066 if (!parser_create_array_setter(parser, var, name))
5068 util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str());
5069 if (!parser_create_array_getter(parser, var, var->m_next, name))
5074 static bool parse_array(parser_t *parser, ast_value *array)
5077 if (array->m_initlist.size()) {
5078 parseerror(parser, "array already initialized elsewhere");
5081 if (!parser_next(parser)) {
5082 parseerror(parser, "parse error in array initializer");
5086 while (parser->tok != '}') {
5087 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5090 if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5092 parseerror(parser, "initializing element must be a compile time constant");
5095 array->m_initlist.push_back(v->m_constval);
5096 if (v->m_vtype == TYPE_STRING) {
5097 array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5101 if (parser->tok == '}')
5103 if (parser->tok != ',' || !parser_next(parser)) {
5104 parseerror(parser, "expected comma or '}' in element list");
5108 if (!parser_next(parser) || parser->tok != ';') {
5109 parseerror(parser, "expected semicolon after initializer, got %s");
5113 if (!parser_next(parser)) {
5114 parseerror(parser, "parse error after initializer");
5119 if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5120 if (array->m_count != (size_t)-1) {
5121 parseerror(parser, "array `%s' has already been initialized with %u elements",
5122 array->m_name, (unsigned)array->m_count);
5124 array->m_count = array->m_initlist.size();
5125 if (!create_array_accessors(parser, array))
5131 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)
5135 ast_expression *old;
5139 ast_value *basetype = nullptr;
5141 bool isparam = false;
5142 bool isvector = false;
5143 bool cleanvar = true;
5144 bool wasarray = false;
5146 ast_member *me[3] = { nullptr, nullptr, nullptr };
5147 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5149 if (!localblock && is_static)
5150 parseerror(parser, "`static` qualifier is not supported in global scope");
5152 /* get the first complete variable */
5153 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5160 /* while parsing types, the ast_value's get named '<something>' */
5161 if (!var->m_name.length() || var->m_name[0] == '<') {
5162 parseerror(parser, "declaration does not declare anything");
5172 /* Part 0: finish the type */
5173 if (parser->tok == '(') {
5174 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5175 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5176 var = parse_parameter_list(parser, var);
5182 /* we only allow 1-dimensional arrays */
5183 if (var->m_vtype != TYPE_FUNCTION && parser->tok == '[') {
5185 var = parse_arraysize(parser, var);
5191 if (parser->tok == '(' && wasarray) {
5192 parseerror(parser, "arrays as part of a return type is not supported");
5193 /* we'll still parse the type completely for now */
5195 /* for functions returning functions */
5196 while (parser->tok == '(') {
5197 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5198 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5199 var = parse_parameter_list(parser, var);
5206 var->m_cvq = qualifier;
5207 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5208 var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5209 var->m_flags |= qflags;
5212 * store the vstring back to var for alias and
5213 * deprecation messages.
5215 if (var->m_flags & AST_FLAG_DEPRECATED || var->m_flags & AST_FLAG_ALIAS)
5216 var->m_desc = vstring;
5218 if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5219 parseerror(parser, "function aliases cannot be forward declared");
5226 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5227 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5228 * is then filled with the previous definition and the parameter-names replaced.
5230 if (var->m_name == "nil") {
5231 if (OPTS_FLAG(UNTYPED_NIL)) {
5232 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5233 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5235 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5238 /* Deal with end_sys_ vars */
5240 if (var->m_name == "end_sys_globals") {
5241 var->m_flags |= AST_FLAG_NOREF;
5242 parser->crc_globals = parser->globals.size();
5245 else if (var->m_name == "end_sys_fields") {
5246 var->m_flags |= AST_FLAG_NOREF;
5247 parser->crc_fields = parser->fields.size();
5250 if (was_end && var->m_vtype == TYPE_FIELD) {
5251 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5252 "global '%s' hint should not be a field",
5253 parser_tokval(parser)))
5260 if (!nofields && var->m_vtype == TYPE_FIELD)
5262 /* deal with field declarations */
5263 old = parser_find_field(parser, var->m_name);
5265 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5266 var->m_name, old->m_context.file, (int)old->m_context.line))
5275 parseerror(parser, "field `%s` already declared here: %s:%i",
5276 var->m_name, old->m_context.file, old->m_context.line);
5281 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5282 (old = parser_find_global(parser, var->m_name)))
5284 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5285 parseerror(parser, "field `%s` already declared here: %s:%i",
5286 var->m_name, old->m_context.file, old->m_context.line);
5293 /* deal with other globals */
5294 old = parser_find_global(parser, var->m_name);
5295 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5297 /* This is a function which had a prototype */
5298 if (!ast_istype(old, ast_value)) {
5299 parseerror(parser, "internal error: prototype is not an ast_value");
5303 proto = (ast_value*)old;
5304 proto->m_desc = var->m_desc;
5305 if (!proto->compareType(*var)) {
5306 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5308 proto->m_context.file, proto->m_context.line);
5312 /* we need the new parameter-names */
5313 for (i = 0; i < proto->m_type_params.size(); ++i)
5314 proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name;
5315 if (!parser_check_qualifiers(parser, var, proto)) {
5320 proto->m_flags |= var->m_flags;
5328 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5329 "global `%s` already declared here: %s:%i",
5330 var->m_name, old->m_context.file, old->m_context.line))
5335 if (old->m_flags & AST_FLAG_FINAL_DECL) {
5336 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5337 var->m_name, old->m_context.file, old->m_context.line);
5341 proto = (ast_value*)old;
5342 if (!ast_istype(old, ast_value)) {
5343 parseerror(parser, "internal error: not an ast_value");
5348 if (!parser_check_qualifiers(parser, var, proto)) {
5353 proto->m_flags |= var->m_flags;
5354 /* copy the context for finals,
5355 * so the error can show where it was actually made 'final'
5357 if (proto->m_flags & AST_FLAG_FINAL_DECL)
5358 old->m_context = var->m_context;
5362 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5363 (old = parser_find_field(parser, var->m_name)))
5365 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5366 parseerror(parser, "global `%s` already declared here: %s:%i",
5367 var->m_name, old->m_context.file, old->m_context.line);
5374 else /* it's not a global */
5376 old = parser_find_local(parser, var->m_name, parser->variables.size()-1, &isparam);
5377 if (old && !isparam) {
5378 parseerror(parser, "local `%s` already declared here: %s:%i",
5379 var->m_name, old->m_context.file, (int)old->m_context.line);
5383 /* doing this here as the above is just for a single scope */
5384 old = parser_find_local(parser, var->m_name, 0, &isparam);
5385 if (old && isparam) {
5386 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5387 "local `%s` is shadowing a parameter", var->m_name))
5389 parseerror(parser, "local `%s` already declared here: %s:%i",
5390 var->m_name, old->m_context.file, (int)old->m_context.line);
5394 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5396 if (ast_istype(old, ast_value))
5397 var = proto = (ast_value*)old;
5406 if (noref || parser->noref)
5407 var->m_flags |= AST_FLAG_NOREF;
5410 * Create the global/local, and deal with vector types.
5413 if (var->m_vtype == TYPE_VECTOR)
5415 else if (var->m_vtype == TYPE_FIELD &&
5416 var->m_next->m_vtype == TYPE_VECTOR)
5420 if (!create_vector_members(var, me)) {
5427 /* deal with global variables, fields, functions */
5428 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5429 var->m_isfield = true;
5430 parser->fields.push_back(var);
5431 util_htset(parser->htfields, var->m_name.c_str(), var);
5433 for (i = 0; i < 3; ++i) {
5434 parser->fields.push_back(me[i]);
5435 util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]);
5440 if (!(var->m_flags & AST_FLAG_ALIAS)) {
5441 parser_addglobal(parser, var->m_name, var);
5443 for (i = 0; i < 3; ++i) {
5444 parser_addglobal(parser, me[i]->m_name.c_str(), me[i]);
5448 ast_expression *find = parser_find_global(parser, var->m_desc);
5451 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5455 if (!var->compareType(*find)) {
5459 ast_type_to_string(find, ty1, sizeof(ty1));
5460 ast_type_to_string(var, ty2, sizeof(ty2));
5462 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5463 ty1, ty2, var->m_name
5468 util_htset(parser->aliases, var->m_name.c_str(), find);
5470 /* generate aliases for vector components */
5474 util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str());
5475 util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str());
5476 util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str());
5478 util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0]));
5479 util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1]));
5480 util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2]));
5490 // a static adds itself to be generated like any other global
5491 // but is added to the local namespace instead
5492 std::string defname;
5496 defname = parser->function->m_name;
5497 defname.append(2, ':');
5499 // remember the length up to here
5500 prefix_len = defname.length();
5502 // Add it to the local scope
5503 util_htset(parser->variables.back(), var->m_name.c_str(), (void*)var);
5505 // now rename the global
5506 defname.append(var->m_name);
5507 // if a variable of that name already existed, add the
5509 // The counter is incremented either way.
5510 sn_size = parser->function->m_static_names.size();
5511 for (sn = 0; sn != sn_size; ++sn) {
5512 if (parser->function->m_static_names[sn] == var->m_name.c_str())
5515 if (sn != sn_size) {
5516 char *num = nullptr;
5517 int len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5518 defname.append(num, 0, len);
5522 parser->function->m_static_names.emplace_back(var->m_name);
5523 parser->function->m_static_count++;
5524 var->m_name = defname;
5526 // push it to the to-be-generated globals
5527 parser->globals.push_back(var);
5529 // same game for the vector members
5531 defname.erase(prefix_len);
5532 for (i = 0; i < 3; ++i) {
5533 util_htset(parser->variables.back(), me[i]->m_name.c_str(), (void*)(me[i]));
5534 me[i]->m_name = defname + me[i]->m_name;
5535 parser->globals.push_back(me[i]);
5539 localblock->m_locals.push_back(var);
5540 parser_addlocal(parser, var->m_name, var);
5542 for (i = 0; i < 3; ++i) {
5543 parser_addlocal(parser, me[i]->m_name, me[i]);
5544 localblock->collect(me[i]);
5550 memcpy(last_me, me, sizeof(me));
5551 me[0] = me[1] = me[2] = nullptr;
5556 if (var->m_vtype == TYPE_ARRAY) {
5557 if (var->m_count != (size_t)-1) {
5558 if (!create_array_accessors(parser, var))
5562 else if (!localblock && !nofields &&
5563 var->m_vtype == TYPE_FIELD &&
5564 var->m_next->m_vtype == TYPE_ARRAY)
5567 ast_expression *telem;
5569 ast_value *array = (ast_value*)var->m_next;
5571 if (!ast_istype(var->m_next, ast_value)) {
5572 parseerror(parser, "internal error: field element type must be an ast_value");
5576 util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str());
5577 if (!parser_create_array_field_setter(parser, array, name))
5580 telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next);
5581 tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD);
5582 tfield->m_next = telem;
5583 util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str());
5584 if (!parser_create_array_getter(parser, array, tfield, name)) {
5592 if (parser->tok == ';') {
5594 if (!parser_next(parser)) {
5595 parseerror(parser, "error after variable declaration");
5601 if (parser->tok == ',')
5605 if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5608 parseerror(parser, "missing comma or semicolon while parsing variables");
5612 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5613 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5614 "initializing expression turns variable `%s` into a constant in this standard",
5621 if (var->m_vtype != TYPE_FUNCTION || (parser->tok != '{' && parser->tok != '[')) {
5622 if (parser->tok != '=') {
5623 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5627 if (!parser_next(parser)) {
5628 parseerror(parser, "error parsing initializer");
5632 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5633 parseerror(parser, "expected '=' before function body in this standard");
5636 if (parser->tok == '#') {
5637 ast_function *func = nullptr;
5638 ast_value *number = nullptr;
5644 parseerror(parser, "cannot declare builtins within functions");
5647 if (var->m_vtype != TYPE_FUNCTION) {
5648 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5651 if (!parser_next(parser)) {
5652 parseerror(parser, "expected builtin number");
5656 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5657 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5659 parseerror(parser, "builtin number expected");
5662 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5665 parseerror(parser, "builtin number must be a compile time constant");
5668 if (number->m_vtype == TYPE_INTEGER)
5669 builtin_num = number->m_constval.vint;
5670 else if (number->m_vtype == TYPE_FLOAT)
5671 builtin_num = number->m_constval.vfloat;
5674 parseerror(parser, "builtin number must be an integer constant");
5679 fractional = modff(builtin_num, &integral);
5680 if (builtin_num < 0 || fractional != 0) {
5681 parseerror(parser, "builtin number must be an integer greater than zero");
5685 /* we only want the integral part anyways */
5686 builtin_num = integral;
5687 } else if (parser->tok == TOKEN_INTCONST) {
5688 builtin_num = parser_token(parser)->constval.i;
5690 parseerror(parser, "builtin number must be a compile time constant");
5694 if (var->m_hasvalue) {
5695 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5696 "builtin `%s` has already been defined\n"
5697 " -> previous declaration here: %s:%i",
5698 var->m_name, var->m_context.file, (int)var->m_context.line);
5702 func = ast_function::make(var->m_context, var->m_name, var);
5704 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5707 parser->functions.push_back(func);
5709 func->m_builtin = -builtin_num-1;
5712 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5713 ? (parser->tok != ',' && parser->tok != ';')
5714 : (!parser_next(parser)))
5716 parseerror(parser, "expected comma or semicolon");
5718 var->m_constval.vfunc = nullptr;
5722 else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5725 /* Note that fteqcc and most others don't even *have*
5726 * local arrays, so this is not a high priority.
5728 parseerror(parser, "TODO: initializers for local arrays");
5732 var->m_hasvalue = true;
5733 if (!parse_array(parser, var))
5736 else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5739 parseerror(parser, "cannot declare functions within functions");
5744 proto->m_context = parser_ctx(parser);
5746 if (!parse_function_body(parser, var))
5749 for (auto &it : parser->gotos)
5750 parseerror(parser, "undefined label: `%s`", it->m_name);
5751 parser->gotos.clear();
5752 parser->labels.clear();
5755 ast_expression *cexp;
5757 bool folded_const = false;
5759 cexp = parse_expression_leave(parser, true, false, false);
5762 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5764 /* deal with foldable constants: */
5766 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5768 /* remove it from the current locals */
5770 for (i = 0; i < 3; ++i) {
5771 parser->_locals.pop_back();
5772 localblock->m_collect.pop_back();
5775 /* do sanity checking, this function really needs refactoring */
5776 if (parser->_locals.back() != var)
5777 parseerror(parser, "internal error: unexpected change in local variable handling");
5779 parser->_locals.pop_back();
5780 if (localblock->m_locals.back() != var)
5781 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5783 localblock->m_locals.pop_back();
5784 /* push it to the to-be-generated globals */
5785 parser->globals.push_back(var);
5787 for (i = 0; i < 3; ++i)
5788 parser->globals.push_back(last_me[i]);
5789 folded_const = true;
5792 if (folded_const || !localblock || is_static) {
5793 if (cval != parser->nil &&
5794 (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5797 parseerror(parser, "initializer is non constant");
5802 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5803 qualifier != CV_VAR)
5805 var->m_cvq = CV_CONST;
5807 if (cval == parser->nil)
5809 var->m_flags |= AST_FLAG_INITIALIZED;
5810 var->m_flags |= AST_FLAG_NOREF;
5814 var->m_hasvalue = true;
5815 if (cval->m_vtype == TYPE_STRING)
5816 var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5817 else if (cval->m_vtype == TYPE_FIELD)
5818 var->m_constval.vfield = cval;
5820 memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5828 var->m_cvq = CV_NONE;
5829 sy.out.push_back(syexp(var->m_context, var));
5830 sy.out.push_back(syexp(cexp->m_context, cexp));
5831 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5832 if (!parser_sy_apply_operator(parser, &sy))
5835 if (sy.out.size() != 1 && sy.ops.size() != 0)
5836 parseerror(parser, "internal error: leaked operands");
5837 if (!localblock->addExpr(sy.out[0].out))
5842 /* a constant initialized to an inexact value should be marked inexact:
5843 * const float x = <inexact>; should propagate the inexact flag
5845 if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5846 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5847 var->m_inexact = cval->m_inexact;
5852 if (parser->tok == ',') {
5853 if (!parser_next(parser)) {
5854 parseerror(parser, "expected another variable");
5858 if (parser->tok != TOKEN_IDENT) {
5859 parseerror(parser, "expected another variable");
5862 var = new ast_value(ast_copy_type, *basetype);
5864 var->m_name = parser_tokval(parser);
5865 if (!parser_next(parser)) {
5866 parseerror(parser, "error parsing variable declaration");
5872 if (parser->tok != ';') {
5873 parseerror(parser, "missing semicolon after variables");
5877 if (!parser_next(parser)) {
5878 parseerror(parser, "parse error after variable declaration");
5886 if (cleanvar && var)
5893 if (cleanvar && var)
5901 static bool parser_global_statement(parser_t *parser)
5905 bool is_static = false;
5906 uint32_t qflags = 0;
5907 ast_value *istype = nullptr;
5908 char *vstring = nullptr;
5910 if (parser->tok == TOKEN_IDENT)
5911 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5913 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5915 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5917 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5919 if (cvq == CV_WRONG)
5921 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5923 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5925 return parse_enum(parser);
5927 else if (parser->tok == TOKEN_KEYWORD)
5929 if (!strcmp(parser_tokval(parser), "typedef")) {
5930 if (!parser_next(parser)) {
5931 parseerror(parser, "expected type definition after 'typedef'");
5934 return parse_typedef(parser);
5936 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5939 else if (parser->tok == '#')
5941 return parse_pragma(parser);
5943 else if (parser->tok == '$')
5945 if (!parser_next(parser)) {
5946 parseerror(parser, "parse error");
5952 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5958 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5960 return util_crc16(old, str, strlen(str));
5963 static void progdefs_crc_file(const char *str)
5965 /* write to progdefs.h here */
5969 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5971 old = progdefs_crc_sum(old, str);
5972 progdefs_crc_file(str);
5976 static void generate_checksum(parser_t *parser, ir_builder *ir)
5978 uint16_t crc = 0xFFFF;
5982 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5983 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5985 progdefs_crc_file("\tint\tpad;\n");
5986 progdefs_crc_file("\tint\tofs_return[3];\n");
5987 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5988 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5989 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5990 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5991 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5992 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5993 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5994 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5996 for (i = 0; i < parser->crc_globals; ++i) {
5997 if (!ast_istype(parser->globals[i], ast_value))
5999 value = (ast_value*)(parser->globals[i]);
6000 switch (value->m_vtype) {
6001 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6002 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6003 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6004 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6006 crc = progdefs_crc_both(crc, "\tint\t");
6009 crc = progdefs_crc_both(crc, value->m_name.c_str());
6010 crc = progdefs_crc_both(crc, ";\n");
6012 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6013 for (i = 0; i < parser->crc_fields; ++i) {
6014 if (!ast_istype(parser->fields[i], ast_value))
6016 value = (ast_value*)(parser->fields[i]);
6017 switch (value->m_next->m_vtype) {
6018 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6019 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6020 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6021 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6023 crc = progdefs_crc_both(crc, "\tint\t");
6026 crc = progdefs_crc_both(crc, value->m_name.c_str());
6027 crc = progdefs_crc_both(crc, ";\n");
6029 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6030 ir->m_code->crc = crc;
6033 parser_t::parser_t()
6036 , ast_cleaned(false)
6041 , aliases(util_htnew(PARSER_HT_SIZE))
6042 , htfields(util_htnew(PARSER_HT_SIZE))
6043 , htglobals(util_htnew(PARSER_HT_SIZE))
6044 , assign_op(nullptr)
6046 , max_param_count(1)
6047 // finish initializing the rest of the parser before initializing
6048 // m_fold and m_intrin with the parser passed along
6052 variables.push_back(htfields);
6053 variables.push_back(htglobals);
6054 typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
6055 _blocktypedefs.push_back(0);
6057 lex_ctx_t empty_ctx;
6058 empty_ctx.file = "<internal>";
6060 empty_ctx.column = 0;
6061 nil = new ast_value(empty_ctx, "nil", TYPE_NIL);
6062 nil->m_cvq = CV_CONST;
6063 if (OPTS_FLAG(UNTYPED_NIL))
6064 util_htset(htglobals, "nil", (void*)nil);
6066 const_vec[0] = new ast_value(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6067 const_vec[1] = new ast_value(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6068 const_vec[2] = new ast_value(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6070 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6071 reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING);
6072 reserved_version->m_cvq = CV_CONST;
6073 reserved_version->m_hasvalue = true;
6074 reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6075 reserved_version->m_flags |= AST_FLAG_NOREF;
6076 reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6078 reserved_version = nullptr;
6081 m_fold = fold(this);
6082 m_intrin = intrin(this);
6085 parser_t::~parser_t()
6090 parser_t *parser_create()
6095 parser = new parser_t;
6099 for (i = 0; i < operator_count; ++i) {
6100 if (operators[i].id == opid1('=')) {
6101 parser->assign_op = operators+i;
6105 if (!parser->assign_op) {
6106 con_err("internal error: initializing parser: failed to find assign operator\n");
6114 static bool parser_compile(parser_t *parser)
6116 /* initial lexer/parser state */
6117 parser->lex->flags.noops = true;
6119 if (parser_next(parser))
6121 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6123 if (!parser_global_statement(parser)) {
6124 if (parser->tok == TOKEN_EOF)
6125 parseerror(parser, "unexpected end of file");
6126 else if (compile_errors)
6127 parseerror(parser, "there have been errors, bailing out");
6128 lex_close(parser->lex);
6129 parser->lex = nullptr;
6134 parseerror(parser, "parse error");
6135 lex_close(parser->lex);
6136 parser->lex = nullptr;
6140 lex_close(parser->lex);
6141 parser->lex = nullptr;
6143 return !compile_errors;
6146 bool parser_compile_file(parser_t *parser, const char *filename)
6148 parser->lex = lex_open(filename);
6150 con_err("failed to open file \"%s\"\n", filename);
6153 return parser_compile(parser);
6156 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6158 parser->lex = lex_open_string(str, len, name);
6160 con_err("failed to create lexer for string \"%s\"\n", name);
6163 return parser_compile(parser);
6166 void parser_t::remove_ast()
6171 for (auto &it : accessors) {
6172 delete it->m_constval.vfunc;
6173 it->m_constval.vfunc = nullptr;
6176 for (auto &it : functions) delete it;
6177 for (auto &it : globals) delete it;
6178 for (auto &it : fields) delete it;
6180 for (auto &it : variables) util_htdel(it);
6182 _blocklocals.clear();
6186 for (auto &it : typedefs) util_htdel(it);
6188 _blocktypedefs.clear();
6194 delete const_vec[0];
6195 delete const_vec[1];
6196 delete const_vec[2];
6198 if (reserved_version)
6199 delete reserved_version;
6201 util_htdel(aliases);
6204 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6205 ast_expression *expr;
6209 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6213 for (auto &it : parser->functions) {
6214 if (it->m_name == "coverage") {
6220 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6221 con_out("coverage support requested but no coverage() builtin declared\n");
6228 cov = func->m_function_type;
6231 if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) {
6233 ast_type_to_string(expr, ty, sizeof(ty));
6234 con_out("invalid type for coverage(): %s\n", ty);
6239 ir->m_coverage_func = func->m_ir_func->m_value;
6243 bool parser_finish(parser_t *parser, const char *output)
6248 if (compile_errors) {
6249 con_out("*** there were compile errors\n");
6253 ir = new ir_builder("gmqcc_out");
6255 con_out("failed to allocate builder\n");
6259 for (auto &it : parser->fields) {
6261 if (!ast_istype(it, ast_value))
6263 ast_value *field = (ast_value*)it;
6264 hasvalue = field->m_hasvalue;
6265 field->m_hasvalue = false;
6266 if (!reinterpret_cast<ast_value*>(field)->generateGlobal(ir, true)) {
6267 con_out("failed to generate field %s\n", field->m_name.c_str());
6273 ast_expression *subtype;
6274 field->m_hasvalue = true;
6275 subtype = field->m_next;
6276 ifld = ir->createField(field->m_name, subtype->m_vtype);
6277 if (subtype->m_vtype == TYPE_FIELD)
6278 ifld->m_fieldtype = subtype->m_next->m_vtype;
6279 else if (subtype->m_vtype == TYPE_FUNCTION)
6280 ifld->m_outtype = subtype->m_next->m_vtype;
6281 (void)!field->m_ir_v->setField(ifld);
6284 for (auto &it : parser->globals) {
6286 if (!ast_istype(it, ast_value))
6288 asvalue = (ast_value*)it;
6289 if (!(asvalue->m_flags & AST_FLAG_NOREF) && asvalue->m_cvq != CV_CONST && asvalue->m_vtype != TYPE_FUNCTION) {
6290 retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE,
6291 "unused global: `%s`", asvalue->m_name);
6293 if (!asvalue->generateGlobal(ir, false)) {
6294 con_out("failed to generate global %s\n", asvalue->m_name.c_str());
6299 /* Build function vararg accessor ast tree now before generating
6300 * immediates, because the accessors may add new immediates
6302 for (auto &f : parser->functions) {
6304 if (parser->max_param_count > f->m_function_type->m_type_params.size()) {
6305 f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size();
6306 if (!parser_create_array_setter_impl(parser, f->m_varargs.get())) {
6307 con_out("failed to generate vararg setter for %s\n", f->m_name.c_str());
6311 if (!parser_create_array_getter_impl(parser, f->m_varargs.get())) {
6312 con_out("failed to generate vararg getter for %s\n", f->m_name.c_str());
6317 f->m_varargs = nullptr;
6321 /* Now we can generate immediates */
6322 if (!parser->m_fold.generate(ir))
6325 /* before generating any functions we need to set the coverage_func */
6326 if (!parser_set_coverage_func(parser, ir))
6328 for (auto &it : parser->globals) {
6329 if (!ast_istype(it, ast_value))
6331 ast_value *asvalue = (ast_value*)it;
6332 if (!(asvalue->m_flags & AST_FLAG_INITIALIZED))
6334 if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue)
6335 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT,
6336 "uninitialized constant: `%s`",
6338 else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue)
6339 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL,
6340 "uninitialized global: `%s`",
6343 if (!asvalue->generateAccessors(ir)) {
6348 for (auto &it : parser->fields) {
6349 ast_value *asvalue = (ast_value*)it->m_next;
6350 if (!ast_istype(asvalue, ast_value))
6352 if (asvalue->m_vtype != TYPE_ARRAY)
6354 if (!asvalue->generateAccessors(ir)) {
6359 if (parser->reserved_version &&
6360 !parser->reserved_version->generateGlobal(ir, false))
6362 con_out("failed to generate reserved::version");
6366 for (auto &f : parser->functions) {
6367 if (!f->generateFunction(ir)) {
6368 con_out("failed to generate function %s\n", f->m_name.c_str());
6374 generate_checksum(parser, ir);
6376 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6378 for (auto &it : parser->functions) {
6379 if (!ir_function_finalize(it->m_ir_func)) {
6380 con_out("failed to finalize function %s\n", it->m_name.c_str());
6385 parser->remove_ast();
6387 auto fnCheckWErrors = [&retval]() {
6388 if (compile_Werrors) {
6389 con_out("*** there were warnings treated as errors\n");
6390 compile_show_werrors();
6398 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6401 if (!ir->generate(output)) {
6402 con_out("*** failed to generate output file\n");
6407 // ir->generate can generate compiler warnings