9 #define PARSER_HT_LOCALS 2
10 #define PARSER_HT_SIZE 512
11 #define TYPEDEF_HT_SIZE 512
13 static void parser_enterblock(parser_t *parser);
14 static bool parser_leaveblock(parser_t *parser);
15 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
16 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e);
17 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
18 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e);
19 static bool parse_typedef(parser_t *parser);
20 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
21 static ast_block* parse_block(parser_t *parser);
22 static bool parse_block_into(parser_t *parser, ast_block *block);
23 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
24 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
25 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
26 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
27 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
28 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
29 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
31 static void parseerror_(parser_t *parser, const char *fmt, ...)
35 vcompile_error(parser->lex->tok.ctx, fmt, ap);
39 template<typename... Ts>
40 static inline void parseerror(parser_t *parser, const char *fmt, const Ts&... ts) {
41 return parseerror_(parser, fmt, formatNormalize(ts)...);
44 // returns true if it counts as an error
45 static bool GMQCC_WARN parsewarning_(parser_t *parser, int warntype, const char *fmt, ...)
50 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
55 template<typename... Ts>
56 static inline bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, const Ts&... ts) {
57 return parsewarning_(parser, warntype, fmt, formatNormalize(ts)...);
60 /**********************************************************************
64 static bool parser_next(parser_t *parser)
66 /* lex_do kills the previous token */
67 parser->tok = lex_do(parser->lex);
68 if (parser->tok == TOKEN_EOF)
70 if (parser->tok >= TOKEN_ERROR) {
71 parseerror(parser, "lex error");
77 #define parser_tokval(p) ((p)->lex->tok.value)
78 #define parser_token(p) (&((p)->lex->tok))
80 char *parser_strdup(const char *str)
83 /* actually dup empty strings */
84 char *out = (char*)mem_a(1);
88 return util_strdup(str);
91 static ast_expression* parser_find_field(parser_t *parser, const char *name) {
92 return (ast_expression*)util_htget(parser->htfields, name);
94 static ast_expression* parser_find_field(parser_t *parser, const std::string &name) {
95 return parser_find_field(parser, name.c_str());
98 static ast_expression* parser_find_label(parser_t *parser, const char *name)
100 for (auto &it : parser->labels)
101 if (it->m_name == name)
105 static inline ast_expression* parser_find_label(parser_t *parser, const std::string &name) {
106 return parser_find_label(parser, name.c_str());
109 ast_expression* parser_find_global(parser_t *parser, const char *name)
111 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
114 return (ast_expression*)util_htget(parser->htglobals, name);
117 ast_expression* parser_find_global(parser_t *parser, const std::string &name) {
118 return parser_find_global(parser, name.c_str());
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->m_function_type;
127 for (auto &it : fun->m_type_params) {
128 if (it->m_name == name)
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = parser->variables.size(); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_local(parser_t *parser, const std::string &name, size_t upto, bool *isparam) {
152 return parser_find_local(parser, name.c_str(), upto, isparam);
155 static ast_expression* parser_find_var(parser_t *parser, const char *name)
159 v = parser_find_local(parser, name, PARSER_HT_LOCALS, &dummy);
160 if (!v) v = parser_find_global(parser, name);
164 static inline ast_expression* parser_find_var(parser_t *parser, const std::string &name) {
165 return parser_find_var(parser, name.c_str());
168 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
172 hash = util_hthash(parser->typedefs[0], name);
174 for (i = parser->typedefs.size(); i > upto;) {
176 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
182 static ast_value* parser_find_typedef(parser_t *parser, const std::string &name, size_t upto) {
183 return parser_find_typedef(parser, name.c_str(), upto);
187 size_t etype; /* 0 = expression, others are operators */
191 ast_block *block; /* for commas and function calls */
204 std::vector<sy_elem> out;
205 std::vector<sy_elem> ops;
206 std::vector<size_t> argc;
207 std::vector<unsigned int> paren;
210 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
221 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
232 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
234 e.etype = 1 + (op - operators);
243 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
254 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
255 * so we need to rotate it to become ent.(foo[n]).
257 static bool rotate_entfield_array_index_nodes(ast_expression **out)
259 ast_array_index *index, *oldindex;
260 ast_entfield *entfield;
264 ast_expression *entity;
266 lex_ctx_t ctx = (*out)->m_context;
268 if (!ast_istype(*out, ast_array_index))
270 index = (ast_array_index*)*out;
272 if (!ast_istype(index->m_array, ast_entfield))
274 entfield = (ast_entfield*)index->m_array;
276 if (!ast_istype(entfield->m_field, ast_value))
278 field = (ast_value*)entfield->m_field;
280 sub = index->m_index;
281 entity = entfield->m_entity;
285 index = ast_array_index::make(ctx, field, sub);
286 entfield = new ast_entfield(ctx, entity, index);
289 oldindex->m_array = nullptr;
290 oldindex->m_index = nullptr;
296 static int store_op_for(ast_expression* expr)
298 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) && expr->m_vtype == TYPE_FIELD && expr->m_next->m_vtype == TYPE_VECTOR) {
299 if (ast_istype(expr, ast_entfield)) {
300 return type_storep_instr[TYPE_VECTOR];
302 return type_store_instr[TYPE_VECTOR];
306 if (ast_istype(expr, ast_member) && ast_istype(((ast_member*)expr)->m_owner, ast_entfield)) {
307 return type_storep_instr[expr->m_vtype];
310 if (ast_istype(expr, ast_entfield)) {
311 return type_storep_instr[expr->m_vtype];
314 return type_store_instr[expr->m_vtype];
317 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
319 if (ast_istype(expr, ast_value)) {
320 ast_value *val = (ast_value*)expr;
321 if (val->m_cvq == CV_CONST) {
322 if (val->m_name[0] == '#') {
323 compile_error(ctx, "invalid assignment to a literal constant");
327 * To work around quakeworld we must elide the error and make it
330 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
331 compile_error(ctx, "assignment to constant `%s`", val->m_name);
333 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
340 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
344 ast_expression *out = nullptr;
345 ast_expression *exprs[3] = { 0, 0, 0 };
346 ast_block *blocks[3];
347 ast_binstore *asbinstore;
348 size_t i, assignop, addop, subop;
349 qcint_t generated_op = 0;
354 if (sy->ops.empty()) {
355 parseerror(parser, "internal error: missing operator");
359 if (sy->ops.back().isparen) {
360 parseerror(parser, "unmatched parenthesis");
364 op = &operators[sy->ops.back().etype - 1];
365 ctx = sy->ops.back().ctx;
367 if (sy->out.size() < op->operands) {
368 if (op->flags & OP_PREFIX)
369 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
370 else /* this should have errored previously already */
371 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
377 /* op(:?) has no input and no output */
381 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
382 for (i = 0; i < op->operands; ++i) {
383 exprs[i] = sy->out[sy->out.size()+i].out;
384 blocks[i] = sy->out[sy->out.size()+i].block;
386 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
387 !(i != 0 && op->id == opid2('?',':')) &&
388 !(i == 1 && op->id == opid1('.')))
390 if (ast_istype(exprs[i], ast_label))
391 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
393 compile_error(exprs[i]->m_context, "not an expression");
394 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
398 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
399 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
403 #define NotSameType(T) \
404 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
405 exprs[0]->m_vtype != T)
410 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
414 if (exprs[0]->m_vtype == TYPE_VECTOR &&
415 exprs[1]->m_vtype == TYPE_NOEXPR)
417 if (exprs[1] == parser->const_vec[0])
418 out = ast_member::make(ctx, exprs[0], 0, "");
419 else if (exprs[1] == parser->const_vec[1])
420 out = ast_member::make(ctx, exprs[0], 1, "");
421 else if (exprs[1] == parser->const_vec[2])
422 out = ast_member::make(ctx, exprs[0], 2, "");
424 compile_error(ctx, "access to invalid vector component");
428 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
429 if (exprs[1]->m_vtype != TYPE_FIELD) {
430 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
433 out = new ast_entfield(ctx, exprs[0], exprs[1]);
435 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
436 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
440 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
446 if (exprs[0]->m_vtype != TYPE_ARRAY &&
447 !(exprs[0]->m_vtype == TYPE_FIELD &&
448 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
450 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
451 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
454 if (exprs[1]->m_vtype != TYPE_FLOAT) {
455 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
456 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
459 out = ast_array_index::make(ctx, exprs[0], exprs[1]);
460 rotate_entfield_array_index_nodes(&out);
464 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
465 sy->out.push_back(syexp(ctx, exprs[0]));
466 sy->out.push_back(syexp(ctx, exprs[1]));
471 if (!blocks[0]->addExpr(exprs[1]))
474 blocks[0] = new ast_block(ctx);
475 if (!blocks[0]->addExpr(exprs[0]) ||
476 !blocks[0]->addExpr(exprs[1]))
481 blocks[0]->setType(*exprs[1]);
483 sy->out.push_back(syblock(ctx, blocks[0]));
490 if ((out = parser->m_fold.op(op, exprs)))
493 if (exprs[0]->m_vtype != TYPE_FLOAT &&
494 exprs[0]->m_vtype != TYPE_VECTOR) {
495 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
496 type_name[exprs[0]->m_vtype]);
499 if (exprs[0]->m_vtype == TYPE_FLOAT)
500 out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]);
502 out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]);
506 if (!(out = parser->m_fold.op(op, exprs))) {
507 switch (exprs[0]->m_vtype) {
509 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
512 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]);
515 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
516 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
518 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]);
520 /* we don't constant-fold NOT for these types */
522 out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]);
525 out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]);
528 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
529 type_name[exprs[0]->m_vtype]);
536 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
537 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
539 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
540 type_name[exprs[0]->m_vtype],
541 type_name[exprs[1]->m_vtype]);
544 if (!(out = parser->m_fold.op(op, exprs))) {
545 switch (exprs[0]->m_vtype) {
547 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
550 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
553 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
554 type_name[exprs[0]->m_vtype],
555 type_name[exprs[1]->m_vtype]);
561 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
562 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
564 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
565 type_name[exprs[1]->m_vtype],
566 type_name[exprs[0]->m_vtype]);
569 if (!(out = parser->m_fold.op(op, exprs))) {
570 switch (exprs[0]->m_vtype) {
572 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
575 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
578 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
579 type_name[exprs[1]->m_vtype],
580 type_name[exprs[0]->m_vtype]);
586 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
587 !(exprs[0]->m_vtype == TYPE_VECTOR &&
588 exprs[1]->m_vtype == TYPE_FLOAT) &&
589 !(exprs[1]->m_vtype == TYPE_VECTOR &&
590 exprs[0]->m_vtype == TYPE_FLOAT)
593 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
594 type_name[exprs[1]->m_vtype],
595 type_name[exprs[0]->m_vtype]);
598 if (!(out = parser->m_fold.op(op, exprs))) {
599 switch (exprs[0]->m_vtype) {
601 if (exprs[1]->m_vtype == TYPE_VECTOR)
602 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
604 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
607 if (exprs[1]->m_vtype == TYPE_FLOAT)
608 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
610 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
613 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
614 type_name[exprs[1]->m_vtype],
615 type_name[exprs[0]->m_vtype]);
622 if (exprs[1]->m_vtype != TYPE_FLOAT) {
623 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
624 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
625 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
628 if (!(out = parser->m_fold.op(op, exprs))) {
629 if (exprs[0]->m_vtype == TYPE_FLOAT)
630 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
632 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
633 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
634 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
641 if (NotSameType(TYPE_FLOAT)) {
642 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
643 type_name[exprs[0]->m_vtype],
644 type_name[exprs[1]->m_vtype]);
646 } else if (!(out = parser->m_fold.op(op, exprs))) {
647 /* generate a call to __builtin_mod */
648 ast_expression *mod = parser->m_intrin.func("mod");
649 ast_call *call = nullptr;
650 if (!mod) return false; /* can return null for missing floor */
652 call = ast_call::make(parser_ctx(parser), mod);
653 call->m_params.push_back(exprs[0]);
654 call->m_params.push_back(exprs[1]);
661 compile_error(ctx, "%= is unimplemented");
667 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
668 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
669 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
671 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
672 type_name[exprs[0]->m_vtype],
673 type_name[exprs[1]->m_vtype]);
677 if (!(out = parser->m_fold.op(op, exprs))) {
679 * IF the first expression is float, the following will be too
680 * since scalar ^ vector is not allowed.
682 if (exprs[0]->m_vtype == TYPE_FLOAT) {
683 out = fold::binary(ctx,
684 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
688 * The first is a vector: vector is allowed to bitop with vector and
689 * with scalar, branch here for the second operand.
691 if (exprs[1]->m_vtype == TYPE_VECTOR) {
693 * Bitop all the values of the vector components against the
694 * vectors components in question.
696 out = fold::binary(ctx,
697 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
700 out = fold::binary(ctx,
701 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
710 if (NotSameType(TYPE_FLOAT)) {
711 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
712 type_name[exprs[0]->m_vtype],
713 type_name[exprs[1]->m_vtype]);
717 if (!(out = parser->m_fold.op(op, exprs))) {
718 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
719 ast_call *call = ast_call::make(parser_ctx(parser), shift);
720 call->m_params.push_back(exprs[0]);
721 call->m_params.push_back(exprs[1]);
726 case opid3('<','<','='):
727 case opid3('>','>','='):
728 if (NotSameType(TYPE_FLOAT)) {
729 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
730 type_name[exprs[0]->m_vtype],
731 type_name[exprs[1]->m_vtype]);
735 if(!(out = parser->m_fold.op(op, exprs))) {
736 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
737 ast_call *call = ast_call::make(parser_ctx(parser), shift);
738 call->m_params.push_back(exprs[0]);
739 call->m_params.push_back(exprs[1]);
751 generated_op += 1; /* INSTR_OR */
754 generated_op += INSTR_AND;
755 if (!(out = parser->m_fold.op(op, exprs))) {
756 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
757 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
758 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
759 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
762 for (i = 0; i < 2; ++i) {
763 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
764 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
766 out = ast_unary::make(ctx, INSTR_NOT_F, out);
768 exprs[i] = out; out = nullptr;
769 if (OPTS_FLAG(PERL_LOGIC)) {
770 /* here we want to keep the right expressions' type */
774 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
775 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
777 out = ast_unary::make(ctx, INSTR_NOT_F, out);
779 exprs[i] = out; out = nullptr;
780 if (OPTS_FLAG(PERL_LOGIC)) {
781 /* here we want to keep the right expressions' type */
786 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
791 if (sy->paren.back() != PAREN_TERNARY2) {
792 compile_error(ctx, "mismatched parenthesis/ternary");
795 sy->paren.pop_back();
796 if (!exprs[1]->compareType(*exprs[2])) {
797 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
798 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
799 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
802 if (!(out = parser->m_fold.op(op, exprs)))
803 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
806 case opid2('*', '*'):
807 if (NotSameType(TYPE_FLOAT)) {
808 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
809 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
810 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
815 if (!(out = parser->m_fold.op(op, exprs))) {
816 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
817 gencall->m_params.push_back(exprs[0]);
818 gencall->m_params.push_back(exprs[1]);
823 case opid2('>', '<'):
824 if (NotSameType(TYPE_VECTOR)) {
825 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
826 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
827 compile_error(ctx, "invalid types used in cross product: %s and %s",
832 if (!(out = parser->m_fold.op(op, exprs))) {
843 case opid3('<','=','>'): /* -1, 0, or 1 */
844 if (NotSameType(TYPE_FLOAT)) {
845 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
846 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
847 compile_error(ctx, "invalid types used in comparision: %s and %s",
853 if (!(out = parser->m_fold.op(op, exprs))) {
854 /* This whole block is NOT fold_binary safe */
855 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
857 eq->m_refs = AST_REF_NONE;
860 out = new ast_ternary(ctx,
861 new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
863 parser->m_fold.imm_float(2),
866 new ast_ternary(ctx, eq,
868 parser->m_fold.imm_float(0),
871 parser->m_fold.imm_float(1)
881 generated_op += 1; /* INSTR_GT */
884 generated_op += 1; /* INSTR_LT */
886 case opid2('>', '='):
887 generated_op += 1; /* INSTR_GE */
889 case opid2('<', '='):
890 generated_op += INSTR_LE;
891 if (NotSameType(TYPE_FLOAT)) {
892 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
893 type_name[exprs[0]->m_vtype],
894 type_name[exprs[1]->m_vtype]);
897 if (!(out = parser->m_fold.op(op, exprs)))
898 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
900 case opid2('!', '='):
901 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
902 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
903 type_name[exprs[0]->m_vtype],
904 type_name[exprs[1]->m_vtype]);
907 if (!(out = parser->m_fold.op(op, exprs)))
908 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
910 case opid2('=', '='):
911 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
912 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
913 type_name[exprs[0]->m_vtype],
914 type_name[exprs[1]->m_vtype]);
917 if (!(out = parser->m_fold.op(op, exprs)))
918 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
922 if (ast_istype(exprs[0], ast_entfield)) {
923 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
924 assignop = store_op_for(exprs[0]);
925 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
927 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
928 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
929 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
930 field->m_next->m_vtype == TYPE_FUNCTION &&
931 exprs[1]->m_vtype == TYPE_FUNCTION)
933 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
934 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
937 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
942 assignop = store_op_for(exprs[0]);
944 if (assignop == VINSTR_END) {
945 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
946 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
947 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
949 else if (!exprs[0]->compareType(*exprs[1]))
951 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
952 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
953 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
954 exprs[0]->m_vtype == TYPE_FUNCTION &&
955 exprs[1]->m_vtype == TYPE_FUNCTION)
957 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
958 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
961 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
964 (void)check_write_to(ctx, exprs[0]);
965 /* When we're a vector of part of an entity field we use STOREP */
966 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
967 assignop = INSTR_STOREP_F;
968 out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
970 case opid3('+','+','P'):
971 case opid3('-','-','P'):
973 if (exprs[0]->m_vtype != TYPE_FLOAT) {
974 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
975 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
978 if (op->id == opid3('+','+','P'))
982 (void)check_write_to(exprs[0]->m_context, exprs[0]);
983 if (ast_istype(exprs[0], ast_entfield)) {
984 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
986 parser->m_fold.imm_float(1));
988 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
990 parser->m_fold.imm_float(1));
993 case opid3('S','+','+'):
994 case opid3('S','-','-'):
996 if (exprs[0]->m_vtype != TYPE_FLOAT) {
997 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
998 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
1001 if (op->id == opid3('S','+','+')) {
1002 addop = INSTR_ADD_F;
1003 subop = INSTR_SUB_F;
1005 addop = INSTR_SUB_F;
1006 subop = INSTR_ADD_F;
1008 (void)check_write_to(exprs[0]->m_context, exprs[0]);
1009 if (ast_istype(exprs[0], ast_entfield)) {
1010 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1012 parser->m_fold.imm_float(1));
1014 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1016 parser->m_fold.imm_float(1));
1020 out = fold::binary(ctx, subop,
1022 parser->m_fold.imm_float(1));
1025 case opid2('+','='):
1026 case opid2('-','='):
1027 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1028 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1030 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1031 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1032 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1036 (void)check_write_to(ctx, exprs[0]);
1037 assignop = store_op_for(exprs[0]);
1038 switch (exprs[0]->m_vtype) {
1040 out = new ast_binstore(ctx, assignop,
1041 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1042 exprs[0], exprs[1]);
1045 out = new ast_binstore(ctx, assignop,
1046 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1047 exprs[0], exprs[1]);
1050 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1051 type_name[exprs[0]->m_vtype],
1052 type_name[exprs[1]->m_vtype]);
1056 case opid2('*','='):
1057 case opid2('/','='):
1058 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1059 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1060 exprs[0]->m_vtype == TYPE_VECTOR))
1062 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1063 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1064 compile_error(ctx, "invalid types used in expression: %s and %s",
1068 (void)check_write_to(ctx, exprs[0]);
1069 assignop = store_op_for(exprs[0]);
1070 switch (exprs[0]->m_vtype) {
1072 out = new ast_binstore(ctx, assignop,
1073 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1074 exprs[0], exprs[1]);
1077 if (op->id == opid2('*','=')) {
1078 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1079 exprs[0], exprs[1]);
1081 out = fold::binary(ctx, INSTR_DIV_F,
1082 parser->m_fold.imm_float(1),
1085 compile_error(ctx, "internal error: failed to generate division");
1088 out = new ast_binstore(ctx, assignop, INSTR_MUL_VF,
1093 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1094 type_name[exprs[0]->m_vtype],
1095 type_name[exprs[1]->m_vtype]);
1099 case opid2('&','='):
1100 case opid2('|','='):
1101 case opid2('^','='):
1102 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1103 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1104 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1105 compile_error(ctx, "invalid types used in expression: %s and %s",
1109 (void)check_write_to(ctx, exprs[0]);
1110 assignop = store_op_for(exprs[0]);
1111 if (exprs[0]->m_vtype == TYPE_FLOAT)
1112 out = new ast_binstore(ctx, assignop,
1113 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1114 exprs[0], exprs[1]);
1116 out = new ast_binstore(ctx, assignop,
1117 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1118 exprs[0], exprs[1]);
1120 case opid3('&','~','='):
1121 /* This is like: a &= ~(b);
1122 * But QC has no bitwise-not, so we implement it as
1125 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1126 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1127 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1128 compile_error(ctx, "invalid types used in expression: %s and %s",
1132 assignop = store_op_for(exprs[0]);
1133 if (exprs[0]->m_vtype == TYPE_FLOAT)
1134 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1136 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1139 (void)check_write_to(ctx, exprs[0]);
1140 if (exprs[0]->m_vtype == TYPE_FLOAT)
1141 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1143 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1144 asbinstore->m_keep_dest = true;
1148 case opid3('l', 'e', 'n'):
1149 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1150 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1151 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1154 /* strings must be const, arrays are statically sized */
1155 if (exprs[0]->m_vtype == TYPE_STRING &&
1156 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1158 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1161 out = parser->m_fold.op(op, exprs);
1164 case opid2('~', 'P'):
1165 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1166 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1167 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1170 if (!(out = parser->m_fold.op(op, exprs))) {
1171 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1172 out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1174 out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1181 compile_error(ctx, "failed to apply operator %s", op->op);
1185 sy->out.push_back(syexp(ctx, out));
1189 static bool parser_close_call(parser_t *parser, shunt *sy)
1191 if (!parser->function)
1193 parseerror(parser, "cannot call functions from global scope");
1197 /* was a function call */
1198 ast_expression *fun;
1199 ast_value *funval = nullptr;
1203 size_t paramcount, i;
1206 fid = sy->ops.back().off;
1209 /* out[fid] is the function
1210 * everything above is parameters...
1212 if (sy->argc.empty()) {
1213 parseerror(parser, "internal error: no argument counter available");
1217 paramcount = sy->argc.back();
1218 sy->argc.pop_back();
1220 if (sy->out.size() < fid) {
1221 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1229 * TODO handle this at the intrinsic level with an ast_intrinsic
1232 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1234 if (fid+2 != sy->out.size() || sy->out.back().block) {
1235 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1238 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1239 ast_unref(sy->out.back().out);
1240 sy->out[fid] = syexp(sy->out.back().out->m_context,
1241 parser->m_fold.constgen_string(ty, false));
1247 * Now we need to determine if the function that is being called is
1248 * an intrinsic so we can evaluate if the arguments to it are constant
1249 * and than fruitfully fold them.
1251 #define fold_can_1(X) \
1252 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1253 ((X))->m_vtype != TYPE_FUNCTION)
1255 if (fid + 1 < sy->out.size())
1258 for (i = 0; i < paramcount; ++i) {
1259 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1266 * All is well which ends well, if we make it into here we can ignore the
1267 * intrinsic call and just evaluate it i.e constant fold it.
1269 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1270 std::vector<ast_expression*> exprs;
1271 ast_expression *foldval = nullptr;
1273 exprs.reserve(paramcount);
1274 for (i = 0; i < paramcount; i++)
1275 exprs.push_back(sy->out[fid+1 + i].out);
1277 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs.data()))) {
1282 * Blub: what sorts of unreffing and resizing of
1283 * sy->out should I be doing here?
1285 sy->out[fid] = syexp(foldval->m_context, foldval);
1286 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1292 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1297 if (fid+1 + paramcount != sy->out.size()) {
1298 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1305 for (i = 0; i < paramcount; ++i)
1306 call->m_params.push_back(sy->out[fid+1 + i].out);
1307 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1308 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1309 if (parser->max_param_count < paramcount)
1310 parser->max_param_count = paramcount;
1312 if (ast_istype(fun, ast_value)) {
1313 funval = (ast_value*)fun;
1314 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1315 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1317 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1321 /* overwrite fid, the function, with a call */
1322 sy->out[fid] = syexp(call->m_context, call);
1324 if (fun->m_vtype != TYPE_FUNCTION) {
1325 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1330 parseerror(parser, "could not determine function return type");
1333 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1335 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1337 return !parsewarning(parser, WARN_DEPRECATED,
1338 "call to function (which is marked deprecated)\n",
1339 "-> it has been declared here: %s:%i",
1340 fun->m_context.file, fun->m_context.line);
1342 if (!fval->m_desc.length()) {
1343 return !parsewarning(parser, WARN_DEPRECATED,
1344 "call to `%s` (which is marked deprecated)\n"
1345 "-> `%s` declared here: %s:%i",
1346 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1348 return !parsewarning(parser, WARN_DEPRECATED,
1349 "call to `%s` (deprecated: %s)\n"
1350 "-> `%s` declared here: %s:%i",
1351 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1352 fun->m_context.line);
1355 if (fun->m_type_params.size() != paramcount &&
1356 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1357 fun->m_type_params.size() < paramcount))
1359 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1361 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1362 "too %s parameters for call to %s: expected %i, got %i\n"
1363 " -> `%s` has been declared here: %s:%i",
1364 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1365 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1367 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1368 "too %s parameters for function call: expected %i, got %i\n"
1369 " -> it has been declared here: %s:%i",
1370 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1371 fun->m_context.file, (int)fun->m_context.line);
1378 static bool parser_close_paren(parser_t *parser, shunt *sy)
1380 if (sy->ops.empty()) {
1381 parseerror(parser, "unmatched closing paren");
1385 while (sy->ops.size()) {
1386 if (sy->ops.back().isparen) {
1387 if (sy->paren.back() == PAREN_FUNC) {
1388 sy->paren.pop_back();
1389 if (!parser_close_call(parser, sy))
1393 if (sy->paren.back() == PAREN_EXPR) {
1394 sy->paren.pop_back();
1395 if (sy->out.empty()) {
1396 compile_error(sy->ops.back().ctx, "empty paren expression");
1403 if (sy->paren.back() == PAREN_INDEX) {
1404 sy->paren.pop_back();
1405 // pop off the parenthesis
1407 /* then apply the index operator */
1408 if (!parser_sy_apply_operator(parser, sy))
1412 if (sy->paren.back() == PAREN_TERNARY1) {
1413 sy->paren.back() = PAREN_TERNARY2;
1414 // pop off the parenthesis
1418 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1421 if (!parser_sy_apply_operator(parser, sy))
1427 static void parser_reclassify_token(parser_t *parser)
1430 if (parser->tok >= TOKEN_START)
1432 for (i = 0; i < operator_count; ++i) {
1433 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1434 parser->tok = TOKEN_OPERATOR;
1440 static ast_expression* parse_vararg_do(parser_t *parser)
1442 ast_expression *idx, *out;
1444 ast_value *funtype = parser->function->m_function_type;
1445 lex_ctx_t ctx = parser_ctx(parser);
1447 if (!parser->function->m_varargs) {
1448 parseerror(parser, "function has no variable argument list");
1452 if (!parser_next(parser) || parser->tok != '(') {
1453 parseerror(parser, "expected parameter index and type in parenthesis");
1456 if (!parser_next(parser)) {
1457 parseerror(parser, "error parsing parameter index");
1461 idx = parse_expression_leave(parser, true, false, false);
1465 if (parser->tok != ',') {
1466 if (parser->tok != ')') {
1468 parseerror(parser, "expected comma after parameter index");
1471 // vararg piping: ...(start)
1472 out = new ast_argpipe(ctx, idx);
1476 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1478 parseerror(parser, "expected typename for vararg");
1482 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1488 if (parser->tok != ')') {
1491 parseerror(parser, "expected closing paren");
1495 if (funtype->m_varparam &&
1496 !typevar->compareType(*funtype->m_varparam))
1500 ast_type_to_string(typevar, ty1, sizeof(ty1));
1501 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1502 compile_error(typevar->m_context,
1503 "function was declared to take varargs of type `%s`, requested type is: %s",
1507 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1508 out->adoptType(*typevar);
1513 static ast_expression* parse_vararg(parser_t *parser)
1515 bool old_noops = parser->lex->flags.noops;
1517 ast_expression *out;
1519 parser->lex->flags.noops = true;
1520 out = parse_vararg_do(parser);
1522 parser->lex->flags.noops = old_noops;
1526 /* not to be exposed */
1527 bool ftepp_predef_exists(const char *name);
1528 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1530 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1531 parser->tok == TOKEN_IDENT &&
1532 !strcmp(parser_tokval(parser), "_"))
1534 /* a translatable string */
1537 parser->lex->flags.noops = true;
1538 if (!parser_next(parser) || parser->tok != '(') {
1539 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1542 parser->lex->flags.noops = false;
1543 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1544 parseerror(parser, "expected a constant string in translatable-string extension");
1547 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1550 sy->out.push_back(syexp(parser_ctx(parser), val));
1552 if (!parser_next(parser) || parser->tok != ')') {
1553 parseerror(parser, "expected closing paren after translatable string");
1558 else if (parser->tok == TOKEN_DOTS)
1561 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1562 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1565 va = parse_vararg(parser);
1568 sy->out.push_back(syexp(parser_ctx(parser), va));
1571 else if (parser->tok == TOKEN_FLOATCONST) {
1572 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1575 sy->out.push_back(syexp(parser_ctx(parser), val));
1578 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1579 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1582 sy->out.push_back(syexp(parser_ctx(parser), val));
1585 else if (parser->tok == TOKEN_STRINGCONST) {
1586 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1589 sy->out.push_back(syexp(parser_ctx(parser), val));
1592 else if (parser->tok == TOKEN_VECTORCONST) {
1593 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1596 sy->out.push_back(syexp(parser_ctx(parser), val));
1599 else if (parser->tok == TOKEN_IDENT)
1601 const char *ctoken = parser_tokval(parser);
1602 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1603 ast_expression *var;
1604 /* a_vector.{x,y,z} */
1605 if (sy->ops.empty() ||
1606 !sy->ops.back().etype ||
1607 operators[sy->ops.back().etype-1].id != opid1('.'))
1609 /* When adding more intrinsics, fix the above condition */
1612 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1614 var = parser->const_vec[ctoken[0]-'x'];
1616 var = parser_find_var(parser, parser_tokval(parser));
1618 var = parser_find_field(parser, parser_tokval(parser));
1620 if (!var && with_labels) {
1621 var = parser_find_label(parser, parser_tokval(parser));
1623 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1625 parser->labels.push_back(lbl);
1628 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1629 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1632 * now we try for the real intrinsic hashtable. If the string
1633 * begins with __builtin, we simply skip past it, otherwise we
1634 * use the identifier as is.
1636 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1637 var = parser->m_intrin.func(parser_tokval(parser));
1641 * Try it again, intrin_func deals with the alias method as well
1642 * the first one masks for __builtin though, we emit warning here.
1645 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1646 (void)!compile_warning(
1649 "using implicitly defined builtin `__builtin_%s' for `%s'",
1650 parser_tokval(parser),
1651 parser_tokval(parser)
1659 * sometimes people use preprocessing predefs without enabling them
1660 * i've done this thousands of times already myself. Lets check for
1661 * it in the predef table. And diagnose it better :)
1663 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1664 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1668 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1674 // promote these to norefs
1675 if (ast_istype(var, ast_value))
1677 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1679 else if (ast_istype(var, ast_member))
1681 ast_member *mem = (ast_member *)var;
1682 if (ast_istype(mem->m_owner, ast_value))
1683 ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1686 sy->out.push_back(syexp(parser_ctx(parser), var));
1689 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1693 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1695 ast_expression *expr = nullptr;
1697 bool wantop = false;
1698 /* only warn once about an assignment in a truth value because the current code
1699 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1701 bool warn_parenthesis = true;
1703 /* count the parens because an if starts with one, so the
1704 * end of a condition is an unmatched closing paren
1708 memset(&sy, 0, sizeof(sy));
1710 parser->lex->flags.noops = false;
1712 parser_reclassify_token(parser);
1716 if (parser->tok == TOKEN_TYPENAME) {
1717 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1721 if (parser->tok == TOKEN_OPERATOR)
1723 /* classify the operator */
1724 const oper_info *op;
1725 const oper_info *olast = nullptr;
1727 for (o = 0; o < operator_count; ++o) {
1728 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1729 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1730 !strcmp(parser_tokval(parser), operators[o].op))
1735 if (o == operator_count) {
1736 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1739 /* found an operator */
1742 /* when declaring variables, a comma starts a new variable */
1743 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1744 /* fixup the token */
1749 /* a colon without a pervious question mark cannot be a ternary */
1750 if (!ternaries && op->id == opid2(':','?')) {
1755 if (op->id == opid1(',')) {
1756 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1757 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1761 if (sy.ops.size() && !sy.ops.back().isparen)
1762 olast = &operators[sy.ops.back().etype-1];
1764 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1765 while (olast && op->prec < olast->prec)
1767 if (!parser_sy_apply_operator(parser, &sy))
1769 if (sy.ops.size() && !sy.ops.back().isparen)
1770 olast = &operators[sy.ops.back().etype-1];
1775 #define IsAssignOp(x) (\
1776 (x) == opid1('=') || \
1777 (x) == opid2('+','=') || \
1778 (x) == opid2('-','=') || \
1779 (x) == opid2('*','=') || \
1780 (x) == opid2('/','=') || \
1781 (x) == opid2('%','=') || \
1782 (x) == opid2('&','=') || \
1783 (x) == opid2('|','=') || \
1784 (x) == opid3('&','~','=') \
1786 if (warn_parenthesis) {
1787 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1788 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1789 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1792 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1793 warn_parenthesis = false;
1796 if (olast && olast->id != op->id) {
1797 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1798 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1800 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1801 warn_parenthesis = false;
1803 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1804 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1806 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1807 warn_parenthesis = false;
1813 (op->prec < olast->prec) ||
1814 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1816 if (!parser_sy_apply_operator(parser, &sy))
1818 if (sy.ops.size() && !sy.ops.back().isparen)
1819 olast = &operators[sy.ops.back().etype-1];
1824 if (op->id == opid1('(')) {
1826 size_t sycount = sy.out.size();
1827 /* we expected an operator, this is the function-call operator */
1828 sy.paren.push_back(PAREN_FUNC);
1829 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1830 sy.argc.push_back(0);
1832 sy.paren.push_back(PAREN_EXPR);
1833 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1836 } else if (op->id == opid1('[')) {
1838 parseerror(parser, "unexpected array subscript");
1841 sy.paren.push_back(PAREN_INDEX);
1842 /* push both the operator and the paren, this makes life easier */
1843 sy.ops.push_back(syop(parser_ctx(parser), op));
1844 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1846 } else if (op->id == opid2('?',':')) {
1847 sy.ops.push_back(syop(parser_ctx(parser), op));
1848 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1851 sy.paren.push_back(PAREN_TERNARY1);
1852 } else if (op->id == opid2(':','?')) {
1853 if (sy.paren.empty()) {
1854 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1857 if (sy.paren.back() != PAREN_TERNARY1) {
1858 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1861 if (!parser_close_paren(parser, &sy))
1863 sy.ops.push_back(syop(parser_ctx(parser), op));
1867 sy.ops.push_back(syop(parser_ctx(parser), op));
1868 wantop = !!(op->flags & OP_SUFFIX);
1871 else if (parser->tok == ')') {
1872 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1873 if (!parser_sy_apply_operator(parser, &sy))
1876 if (sy.paren.empty())
1879 if (sy.paren.back() == PAREN_TERNARY1) {
1880 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1883 if (!parser_close_paren(parser, &sy))
1886 /* must be a function call without parameters */
1887 if (sy.paren.back() != PAREN_FUNC) {
1888 parseerror(parser, "closing paren in invalid position");
1891 if (!parser_close_paren(parser, &sy))
1896 else if (parser->tok == '(') {
1897 parseerror(parser, "internal error: '(' should be classified as operator");
1900 else if (parser->tok == '[') {
1901 parseerror(parser, "internal error: '[' should be classified as operator");
1904 else if (parser->tok == ']') {
1905 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1906 if (!parser_sy_apply_operator(parser, &sy))
1909 if (sy.paren.empty())
1911 if (sy.paren.back() != PAREN_INDEX) {
1912 parseerror(parser, "mismatched parentheses, unexpected ']'");
1915 if (!parser_close_paren(parser, &sy))
1920 if (!parse_sya_operand(parser, &sy, with_labels))
1925 /* in this case we might want to allow constant string concatenation */
1926 bool concatenated = false;
1927 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1928 ast_expression *lexpr = sy.out.back().out;
1929 if (ast_istype(lexpr, ast_value)) {
1930 ast_value *last = (ast_value*)lexpr;
1931 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1932 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1934 char *newstr = nullptr;
1935 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1936 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1938 concatenated = true;
1942 if (!concatenated) {
1943 parseerror(parser, "expected operator or end of statement");
1948 if (!parser_next(parser)) {
1951 if (parser->tok == ';' ||
1952 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1953 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1959 while (sy.ops.size()) {
1960 if (!parser_sy_apply_operator(parser, &sy))
1964 parser->lex->flags.noops = true;
1965 if (sy.out.size() != 1) {
1966 parseerror(parser, "expression expected");
1969 expr = sy.out[0].out;
1970 if (sy.paren.size()) {
1971 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1977 parser->lex->flags.noops = true;
1978 for (auto &it : sy.out)
1979 if (it.out) ast_unref(it.out);
1983 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1985 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1988 if (parser->tok != ';') {
1989 parseerror(parser, "semicolon expected after expression");
1993 if (!parser_next(parser)) {
2000 static void parser_enterblock(parser_t *parser)
2002 parser->variables.push_back(util_htnew(PARSER_HT_SIZE));
2003 parser->_blocklocals.push_back(parser->_locals.size());
2004 parser->typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
2005 parser->_blocktypedefs.push_back(parser->_typedefs.size());
2006 parser->_block_ctx.push_back(parser_ctx(parser));
2009 static bool parser_leaveblock(parser_t *parser)
2012 size_t locals, typedefs;
2014 if (parser->variables.size() <= PARSER_HT_LOCALS) {
2015 parseerror(parser, "internal error: parser_leaveblock with no block");
2019 util_htdel(parser->variables.back());
2021 parser->variables.pop_back();
2022 if (!parser->_blocklocals.size()) {
2023 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2027 locals = parser->_blocklocals.back();
2028 parser->_blocklocals.pop_back();
2029 parser->_locals.resize(locals);
2031 typedefs = parser->_blocktypedefs.back();
2032 parser->_typedefs.resize(typedefs);
2033 util_htdel(parser->typedefs.back());
2034 parser->typedefs.pop_back();
2036 parser->_block_ctx.pop_back();
2041 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2043 parser->_locals.push_back(e);
2044 util_htset(parser->variables.back(), name, (void*)e);
2046 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2047 return parser_addlocal(parser, name.c_str(), e);
2050 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2052 parser->globals.push_back(e);
2053 util_htset(parser->htglobals, name, e);
2055 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2056 return parser_addglobal(parser, name.c_str(), e);
2059 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2063 ast_expression *prev;
2065 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2067 ast_type_to_string(cond, ty, sizeof(ty));
2068 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2071 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2074 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2077 parseerror(parser, "internal error: failed to process condition");
2082 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2084 /* vector types need to be cast to true booleans */
2085 ast_binary *bin = (ast_binary*)cond;
2086 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2088 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2090 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2093 parseerror(parser, "internal error: failed to process condition");
2100 unary = (ast_unary*)cond;
2101 /* ast_istype dereferences cond, should test here for safety */
2102 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2104 cond = unary->m_operand;
2105 unary->m_operand = nullptr;
2108 unary = (ast_unary*)cond;
2112 parseerror(parser, "internal error: failed to process condition");
2114 if (ifnot) *_ifnot = !*_ifnot;
2118 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2121 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2124 lex_ctx_t ctx = parser_ctx(parser);
2126 (void)block; /* not touching */
2128 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2129 if (!parser_next(parser)) {
2130 parseerror(parser, "expected condition or 'not'");
2133 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2135 if (!parser_next(parser)) {
2136 parseerror(parser, "expected condition in parenthesis");
2140 if (parser->tok != '(') {
2141 parseerror(parser, "expected 'if' condition in parenthesis");
2144 /* parse into the expression */
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "expected 'if' condition after opening paren");
2149 /* parse the condition */
2150 cond = parse_expression_leave(parser, false, true, false);
2154 if (parser->tok != ')') {
2155 parseerror(parser, "expected closing paren after 'if' condition");
2159 /* parse into the 'then' branch */
2160 if (!parser_next(parser)) {
2161 parseerror(parser, "expected statement for on-true branch of 'if'");
2165 if (!parse_statement_or_block(parser, &ontrue)) {
2170 ontrue = new ast_block(parser_ctx(parser));
2171 /* check for an else */
2172 if (!strcmp(parser_tokval(parser), "else")) {
2173 /* parse into the 'else' branch */
2174 if (!parser_next(parser)) {
2175 parseerror(parser, "expected on-false branch after 'else'");
2180 if (!parse_statement_or_block(parser, &onfalse)) {
2187 cond = process_condition(parser, cond, &ifnot);
2189 if (ontrue) delete ontrue;
2190 if (onfalse) delete onfalse;
2195 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2197 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2202 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2203 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2206 char *label = nullptr;
2208 /* skip the 'while' and get the body */
2209 if (!parser_next(parser)) {
2210 if (OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2213 parseerror(parser, "expected 'while' condition in parenthesis");
2217 if (parser->tok == ':') {
2218 if (!OPTS_FLAG(LOOP_LABELS))
2219 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2220 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2221 parseerror(parser, "expected loop label");
2224 label = util_strdup(parser_tokval(parser));
2225 if (!parser_next(parser)) {
2227 parseerror(parser, "expected 'while' condition in parenthesis");
2232 if (parser->tok != '(') {
2233 parseerror(parser, "expected 'while' condition in parenthesis");
2237 parser->breaks.push_back(label);
2238 parser->continues.push_back(label);
2240 rv = parse_while_go(parser, block, out);
2243 if (parser->breaks.back() != label || parser->continues.back() != label) {
2244 parseerror(parser, "internal error: label stack corrupted");
2250 parser->breaks.pop_back();
2251 parser->continues.pop_back();
2256 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2259 ast_expression *cond, *ontrue;
2263 lex_ctx_t ctx = parser_ctx(parser);
2265 (void)block; /* not touching */
2267 /* parse into the expression */
2268 if (!parser_next(parser)) {
2269 parseerror(parser, "expected 'while' condition after opening paren");
2272 /* parse the condition */
2273 cond = parse_expression_leave(parser, false, true, false);
2277 if (parser->tok != ')') {
2278 parseerror(parser, "expected closing paren after 'while' condition");
2282 /* parse into the 'then' branch */
2283 if (!parser_next(parser)) {
2284 parseerror(parser, "expected while-loop body");
2288 if (!parse_statement_or_block(parser, &ontrue)) {
2293 cond = process_condition(parser, cond, &ifnot);
2298 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2303 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2304 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2307 char *label = nullptr;
2309 /* skip the 'do' and get the body */
2310 if (!parser_next(parser)) {
2311 if (OPTS_FLAG(LOOP_LABELS))
2312 parseerror(parser, "expected loop label or body");
2314 parseerror(parser, "expected loop body");
2318 if (parser->tok == ':') {
2319 if (!OPTS_FLAG(LOOP_LABELS))
2320 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2321 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2322 parseerror(parser, "expected loop label");
2325 label = util_strdup(parser_tokval(parser));
2326 if (!parser_next(parser)) {
2328 parseerror(parser, "expected loop body");
2333 parser->breaks.push_back(label);
2334 parser->continues.push_back(label);
2336 rv = parse_dowhile_go(parser, block, out);
2339 if (parser->breaks.back() != label || parser->continues.back() != label) {
2340 parseerror(parser, "internal error: label stack corrupted");
2346 parser->breaks.pop_back();
2347 parser->continues.pop_back();
2352 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2355 ast_expression *cond, *ontrue;
2359 lex_ctx_t ctx = parser_ctx(parser);
2361 (void)block; /* not touching */
2363 if (!parse_statement_or_block(parser, &ontrue))
2366 /* expect the "while" */
2367 if (parser->tok != TOKEN_KEYWORD ||
2368 strcmp(parser_tokval(parser), "while"))
2370 parseerror(parser, "expected 'while' and condition");
2375 /* skip the 'while' and check for opening paren */
2376 if (!parser_next(parser) || parser->tok != '(') {
2377 parseerror(parser, "expected 'while' condition in parenthesis");
2381 /* parse into the expression */
2382 if (!parser_next(parser)) {
2383 parseerror(parser, "expected 'while' condition after opening paren");
2387 /* parse the condition */
2388 cond = parse_expression_leave(parser, false, true, false);
2392 if (parser->tok != ')') {
2393 parseerror(parser, "expected closing paren after 'while' condition");
2399 if (!parser_next(parser) || parser->tok != ';') {
2400 parseerror(parser, "expected semicolon after condition");
2406 if (!parser_next(parser)) {
2407 parseerror(parser, "parse error");
2413 cond = process_condition(parser, cond, &ifnot);
2418 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2423 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2424 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2427 char *label = nullptr;
2429 /* skip the 'for' and check for opening paren */
2430 if (!parser_next(parser)) {
2431 if (OPTS_FLAG(LOOP_LABELS))
2432 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2434 parseerror(parser, "expected 'for' expressions in parenthesis");
2438 if (parser->tok == ':') {
2439 if (!OPTS_FLAG(LOOP_LABELS))
2440 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2441 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2442 parseerror(parser, "expected loop label");
2445 label = util_strdup(parser_tokval(parser));
2446 if (!parser_next(parser)) {
2448 parseerror(parser, "expected 'for' expressions in parenthesis");
2453 if (parser->tok != '(') {
2454 parseerror(parser, "expected 'for' expressions in parenthesis");
2458 parser->breaks.push_back(label);
2459 parser->continues.push_back(label);
2461 rv = parse_for_go(parser, block, out);
2464 if (parser->breaks.back() != label || parser->continues.back() != label) {
2465 parseerror(parser, "internal error: label stack corrupted");
2471 parser->breaks.pop_back();
2472 parser->continues.pop_back();
2476 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2479 ast_expression *initexpr, *cond, *increment, *ontrue;
2484 lex_ctx_t ctx = parser_ctx(parser);
2486 parser_enterblock(parser);
2490 increment = nullptr;
2493 /* parse into the expression */
2494 if (!parser_next(parser)) {
2495 parseerror(parser, "expected 'for' initializer after opening paren");
2500 if (parser->tok == TOKEN_IDENT)
2501 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2503 if (typevar || parser->tok == TOKEN_TYPENAME) {
2504 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2507 else if (parser->tok != ';')
2509 initexpr = parse_expression_leave(parser, false, false, false);
2512 /* move on to condition */
2513 if (parser->tok != ';') {
2514 parseerror(parser, "expected semicolon after for-loop initializer");
2517 if (!parser_next(parser)) {
2518 parseerror(parser, "expected for-loop condition");
2521 } else if (!parser_next(parser)) {
2522 parseerror(parser, "expected for-loop condition");
2526 /* parse the condition */
2527 if (parser->tok != ';') {
2528 cond = parse_expression_leave(parser, false, true, false);
2532 /* move on to incrementor */
2533 if (parser->tok != ';') {
2534 parseerror(parser, "expected semicolon after for-loop initializer");
2537 if (!parser_next(parser)) {
2538 parseerror(parser, "expected for-loop condition");
2542 /* parse the incrementor */
2543 if (parser->tok != ')') {
2544 lex_ctx_t condctx = parser_ctx(parser);
2545 increment = parse_expression_leave(parser, false, false, false);
2548 if (!increment->m_side_effects) {
2549 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2555 if (parser->tok != ')') {
2556 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2559 /* parse into the 'then' branch */
2560 if (!parser_next(parser)) {
2561 parseerror(parser, "expected for-loop body");
2564 if (!parse_statement_or_block(parser, &ontrue))
2568 cond = process_condition(parser, cond, &ifnot);
2572 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2575 if (!parser_leaveblock(parser)) {
2581 if (initexpr) ast_unref(initexpr);
2582 if (cond) ast_unref(cond);
2583 if (increment) ast_unref(increment);
2584 (void)!parser_leaveblock(parser);
2588 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2590 ast_expression *exp = nullptr;
2591 ast_expression *var = nullptr;
2592 ast_return *ret = nullptr;
2593 ast_value *retval = parser->function->m_return_value;
2594 ast_value *expected = parser->function->m_function_type;
2596 lex_ctx_t ctx = parser_ctx(parser);
2598 (void)block; /* not touching */
2600 if (!parser_next(parser)) {
2601 parseerror(parser, "expected return expression");
2605 /* return assignments */
2606 if (parser->tok == '=') {
2607 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2608 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2612 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2614 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2615 parseerror(parser, "invalid return type: `%s'", ty1);
2619 if (!parser_next(parser)) {
2620 parseerror(parser, "expected return assignment expression");
2624 if (!(exp = parse_expression_leave(parser, false, false, false)))
2627 /* prepare the return value */
2629 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2630 retval->adoptType(*expected->m_next);
2631 parser->function->m_return_value = retval;
2632 parser->function->m_return_value->m_flags |= AST_FLAG_NOREF;
2635 if (!exp->compareType(*retval)) {
2636 char ty1[1024], ty2[1024];
2637 ast_type_to_string(exp, ty1, sizeof(ty1));
2638 ast_type_to_string(retval, ty2, sizeof(ty2));
2639 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2642 /* store to 'return' local variable */
2643 var = new ast_store(
2645 type_store_instr[expected->m_next->m_vtype],
2653 if (parser->tok != ';')
2654 parseerror(parser, "missing semicolon after return assignment");
2655 else if (!parser_next(parser))
2656 parseerror(parser, "parse error after return assignment");
2662 if (parser->tok != ';') {
2663 exp = parse_expression(parser, false, false);
2667 if (exp->m_vtype != TYPE_NIL &&
2668 exp->m_vtype != (expected)->m_next->m_vtype)
2670 parseerror(parser, "return with invalid expression");
2673 ret = new ast_return(ctx, exp);
2679 if (!parser_next(parser))
2680 parseerror(parser, "parse error");
2682 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2684 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2686 ret = new ast_return(ctx, retval);
2692 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2695 unsigned int levels = 0;
2696 lex_ctx_t ctx = parser_ctx(parser);
2697 auto &loops = (is_continue ? parser->continues : parser->breaks);
2699 (void)block; /* not touching */
2700 if (!parser_next(parser)) {
2701 parseerror(parser, "expected semicolon or loop label");
2705 if (loops.empty()) {
2707 parseerror(parser, "`continue` can only be used inside loops");
2709 parseerror(parser, "`break` can only be used inside loops or switches");
2712 if (parser->tok == TOKEN_IDENT) {
2713 if (!OPTS_FLAG(LOOP_LABELS))
2714 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2720 parseerror(parser, "no such loop to %s: `%s`",
2721 (is_continue ? "continue" : "break out of"),
2722 parser_tokval(parser));
2727 if (!parser_next(parser)) {
2728 parseerror(parser, "expected semicolon");
2733 if (parser->tok != ';') {
2734 parseerror(parser, "expected semicolon");
2738 if (!parser_next(parser))
2739 parseerror(parser, "parse error");
2741 *out = new ast_breakcont(ctx, is_continue, levels);
2745 /* returns true when it was a variable qualifier, false otherwise!
2746 * on error, cvq is set to CV_WRONG
2748 struct attribute_t {
2753 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2755 bool had_const = false;
2756 bool had_var = false;
2757 bool had_noref = false;
2758 bool had_attrib = false;
2759 bool had_static = false;
2762 static attribute_t attributes[] = {
2763 { "noreturn", AST_FLAG_NORETURN },
2764 { "inline", AST_FLAG_INLINE },
2765 { "eraseable", AST_FLAG_ERASEABLE },
2766 { "noerase", AST_FLAG_NOERASE },
2767 { "accumulate", AST_FLAG_ACCUMULATE },
2768 { "last", AST_FLAG_FINAL_DECL }
2775 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2777 /* parse an attribute */
2778 if (!parser_next(parser)) {
2779 parseerror(parser, "expected attribute after `[[`");
2784 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2785 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2786 flags |= attributes[i].flag;
2787 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2788 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2789 attributes[i].name);
2797 if (i != GMQCC_ARRAY_COUNT(attributes))
2800 if (!strcmp(parser_tokval(parser), "noref")) {
2802 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2803 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2808 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2809 flags |= AST_FLAG_ALIAS;
2812 if (!parser_next(parser)) {
2813 parseerror(parser, "parse error in attribute");
2817 if (parser->tok == '(') {
2818 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2819 parseerror(parser, "`alias` attribute missing parameter");
2823 *message = util_strdup(parser_tokval(parser));
2825 if (!parser_next(parser)) {
2826 parseerror(parser, "parse error in attribute");
2830 if (parser->tok != ')') {
2831 parseerror(parser, "`alias` attribute expected `)` after parameter");
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "parse error in attribute");
2841 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2842 parseerror(parser, "`alias` attribute expected `]]`");
2846 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2847 flags |= AST_FLAG_DEPRECATED;
2850 if (!parser_next(parser)) {
2851 parseerror(parser, "parse error in attribute");
2855 if (parser->tok == '(') {
2856 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2857 parseerror(parser, "`deprecated` attribute missing parameter");
2861 *message = util_strdup(parser_tokval(parser));
2863 if (!parser_next(parser)) {
2864 parseerror(parser, "parse error in attribute");
2868 if(parser->tok != ')') {
2869 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "parse error in attribute");
2879 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2880 parseerror(parser, "`deprecated` attribute expected `]]`");
2883 if (*message) mem_d(*message);
2889 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2890 flags |= AST_FLAG_COVERAGE;
2891 if (!parser_next(parser)) {
2893 parseerror(parser, "parse error in coverage attribute");
2897 if (parser->tok == '(') {
2898 if (!parser_next(parser)) {
2900 parseerror(parser, "invalid parameter for coverage() attribute\n"
2901 "valid are: block");
2905 if (parser->tok != ')') {
2907 if (parser->tok != TOKEN_IDENT)
2908 goto bad_coverage_arg;
2909 if (!strcmp(parser_tokval(parser), "block"))
2910 flags |= AST_FLAG_BLOCK_COVERAGE;
2911 else if (!strcmp(parser_tokval(parser), "none"))
2912 flags &= ~(AST_FLAG_COVERAGE_MASK);
2914 goto bad_coverage_arg;
2915 if (!parser_next(parser))
2916 goto error_in_coverage;
2917 if (parser->tok == ',') {
2918 if (!parser_next(parser))
2919 goto error_in_coverage;
2921 } while (parser->tok != ')');
2923 if (parser->tok != ')' || !parser_next(parser))
2924 goto error_in_coverage;
2926 /* without parameter [[coverage]] equals [[coverage(block)]] */
2927 flags |= AST_FLAG_BLOCK_COVERAGE;
2932 /* Skip tokens until we hit a ]] */
2933 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2934 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2935 if (!parser_next(parser)) {
2936 parseerror(parser, "error inside attribute");
2943 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2945 else if (!strcmp(parser_tokval(parser), "const"))
2947 else if (!strcmp(parser_tokval(parser), "var"))
2949 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2951 else if (!strcmp(parser_tokval(parser), "noref"))
2953 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2960 if (!parser_next(parser))
2970 *is_static = had_static;
2974 parseerror(parser, "parse error after variable qualifier");
2979 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2980 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2983 char *label = nullptr;
2985 /* skip the 'while' and get the body */
2986 if (!parser_next(parser)) {
2987 if (OPTS_FLAG(LOOP_LABELS))
2988 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2990 parseerror(parser, "expected 'switch' operand in parenthesis");
2994 if (parser->tok == ':') {
2995 if (!OPTS_FLAG(LOOP_LABELS))
2996 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2997 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2998 parseerror(parser, "expected loop label");
3001 label = util_strdup(parser_tokval(parser));
3002 if (!parser_next(parser)) {
3004 parseerror(parser, "expected 'switch' operand in parenthesis");
3009 if (parser->tok != '(') {
3010 parseerror(parser, "expected 'switch' operand in parenthesis");
3014 parser->breaks.push_back(label);
3016 rv = parse_switch_go(parser, block, out);
3019 if (parser->breaks.back() != label) {
3020 parseerror(parser, "internal error: label stack corrupted");
3026 parser->breaks.pop_back();
3031 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3033 ast_expression *operand;
3036 ast_switch *switchnode;
3037 ast_switch_case swcase;
3040 bool noref, is_static;
3041 uint32_t qflags = 0;
3043 lex_ctx_t ctx = parser_ctx(parser);
3045 (void)block; /* not touching */
3048 /* parse into the expression */
3049 if (!parser_next(parser)) {
3050 parseerror(parser, "expected switch operand");
3053 /* parse the operand */
3054 operand = parse_expression_leave(parser, false, false, false);
3058 switchnode = new ast_switch(ctx, operand);
3061 if (parser->tok != ')') {
3063 parseerror(parser, "expected closing paren after 'switch' operand");
3067 /* parse over the opening paren */
3068 if (!parser_next(parser) || parser->tok != '{') {
3070 parseerror(parser, "expected list of cases");
3074 if (!parser_next(parser)) {
3076 parseerror(parser, "expected 'case' or 'default'");
3080 /* new block; allow some variables to be declared here */
3081 parser_enterblock(parser);
3084 if (parser->tok == TOKEN_IDENT)
3085 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3086 if (typevar || parser->tok == TOKEN_TYPENAME) {
3087 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3093 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3095 if (cvq == CV_WRONG) {
3099 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3109 while (parser->tok != '}') {
3110 ast_block *caseblock;
3112 if (!strcmp(parser_tokval(parser), "case")) {
3113 if (!parser_next(parser)) {
3115 parseerror(parser, "expected expression for case");
3118 swcase.m_value = parse_expression_leave(parser, false, false, false);
3120 if (!operand->compareType(*swcase.m_value)) {
3124 ast_type_to_string(swcase.m_value, ty1, sizeof ty1);
3125 ast_type_to_string(operand, ty2, sizeof ty2);
3127 auto fnLiteral = [](ast_expression *expression) -> char* {
3128 if (!ast_istype(expression, ast_value))
3130 ast_value *value = (ast_value *)expression;
3131 if (!value->m_hasvalue)
3133 char *string = nullptr;
3134 basic_value_t *constval = &value->m_constval;
3135 switch (value->m_vtype)
3138 util_asprintf(&string, "%.2f", constval->vfloat);
3141 util_asprintf(&string, "'%.2f %.2f %.2f'",
3147 util_asprintf(&string, "\"%s\"", constval->vstring);
3155 char *literal = fnLiteral(swcase.m_value);
3157 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case `%s` expected `%s`", ty1, literal, ty2);
3159 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case expected `%s`", ty1, ty2);
3165 if (!swcase.m_value) {
3167 parseerror(parser, "expected expression for case");
3170 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3171 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3173 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3179 else if (!strcmp(parser_tokval(parser), "default")) {
3180 swcase.m_value = nullptr;
3181 if (!parser_next(parser)) {
3183 parseerror(parser, "expected colon");
3189 parseerror(parser, "expected 'case' or 'default'");
3193 /* Now the colon and body */
3194 if (parser->tok != ':') {
3195 if (swcase.m_value) ast_unref(swcase.m_value);
3197 parseerror(parser, "expected colon");
3201 if (!parser_next(parser)) {
3202 if (swcase.m_value) ast_unref(swcase.m_value);
3204 parseerror(parser, "expected statements or case");
3207 caseblock = new ast_block(parser_ctx(parser));
3209 if (swcase.m_value) ast_unref(swcase.m_value);
3213 swcase.m_code = caseblock;
3214 switchnode->m_cases.push_back(swcase);
3216 ast_expression *expr;
3217 if (parser->tok == '}')
3219 if (parser->tok == TOKEN_KEYWORD) {
3220 if (!strcmp(parser_tokval(parser), "case") ||
3221 !strcmp(parser_tokval(parser), "default"))
3226 if (!parse_statement(parser, caseblock, &expr, true)) {
3232 if (!caseblock->addExpr(expr)) {
3239 parser_leaveblock(parser);
3242 if (parser->tok != '}') {
3244 parseerror(parser, "expected closing paren of case list");
3247 if (!parser_next(parser)) {
3249 parseerror(parser, "parse error after switch");
3256 /* parse computed goto sides */
3257 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3258 ast_expression *on_true;
3259 ast_expression *on_false;
3260 ast_expression *cond;
3265 if (ast_istype(*side, ast_ternary)) {
3266 ast_ternary *tern = (ast_ternary*)*side;
3267 on_true = parse_goto_computed(parser, &tern->m_on_true);
3268 on_false = parse_goto_computed(parser, &tern->m_on_false);
3270 if (!on_true || !on_false) {
3271 parseerror(parser, "expected label or expression in ternary");
3272 if (on_true) ast_unref(on_true);
3273 if (on_false) ast_unref(on_false);
3277 cond = tern->m_cond;
3278 tern->m_cond = nullptr;
3281 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3282 } else if (ast_istype(*side, ast_label)) {
3283 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3284 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3291 static bool parse_goto(parser_t *parser, ast_expression **out)
3293 ast_goto *gt = nullptr;
3294 ast_expression *lbl;
3296 if (!parser_next(parser))
3299 if (parser->tok != TOKEN_IDENT) {
3300 ast_expression *expression;
3302 /* could be an expression i.e computed goto :-) */
3303 if (parser->tok != '(') {
3304 parseerror(parser, "expected label name after `goto`");
3308 /* failed to parse expression for goto */
3309 if (!(expression = parse_expression(parser, false, true)) ||
3310 !(*out = parse_goto_computed(parser, &expression))) {
3311 parseerror(parser, "invalid goto expression");
3313 ast_unref(expression);
3320 /* not computed goto */
3321 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3322 lbl = parser_find_label(parser, gt->m_name);
3324 if (!ast_istype(lbl, ast_label)) {
3325 parseerror(parser, "internal error: label is not an ast_label");
3329 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3332 parser->gotos.push_back(gt);
3334 if (!parser_next(parser) || parser->tok != ';') {
3335 parseerror(parser, "semicolon expected after goto label");
3338 if (!parser_next(parser)) {
3339 parseerror(parser, "parse error after goto");
3347 static bool parse_skipwhite(parser_t *parser)
3350 if (!parser_next(parser))
3352 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3353 return parser->tok < TOKEN_ERROR;
3356 static bool parse_eol(parser_t *parser)
3358 if (!parse_skipwhite(parser))
3360 return parser->tok == TOKEN_EOL;
3363 static bool parse_pragma_do(parser_t *parser)
3365 if (!parser_next(parser) ||
3366 parser->tok != TOKEN_IDENT ||
3367 strcmp(parser_tokval(parser), "pragma"))
3369 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3372 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3373 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3377 if (!strcmp(parser_tokval(parser), "noref")) {
3378 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3379 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3382 parser->noref = !!parser_token(parser)->constval.i;
3383 if (!parse_eol(parser)) {
3384 parseerror(parser, "parse error after `noref` pragma");
3390 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3393 while (!parse_eol(parser)) {
3394 parser_next(parser);
3403 static bool parse_pragma(parser_t *parser)
3406 parser->lex->flags.preprocessing = true;
3407 parser->lex->flags.mergelines = true;
3408 rv = parse_pragma_do(parser);
3409 if (parser->tok != TOKEN_EOL) {
3410 parseerror(parser, "junk after pragma");
3413 parser->lex->flags.preprocessing = false;
3414 parser->lex->flags.mergelines = false;
3415 if (!parser_next(parser)) {
3416 parseerror(parser, "parse error after pragma");
3422 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3424 bool noref, is_static;
3426 uint32_t qflags = 0;
3427 ast_value *typevar = nullptr;
3428 char *vstring = nullptr;
3432 if (parser->tok == TOKEN_IDENT)
3433 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3435 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3437 /* local variable */
3439 parseerror(parser, "cannot declare a variable from here");
3442 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3443 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3446 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3450 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3452 if (cvq == CV_WRONG)
3454 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3456 else if (parser->tok == TOKEN_KEYWORD)
3458 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3463 if (!parser_next(parser)) {
3464 parseerror(parser, "parse error after __builtin_debug_printtype");
3468 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3470 ast_type_to_string(tdef, ty, sizeof(ty));
3471 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3472 if (!parser_next(parser)) {
3473 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3479 if (!parse_statement(parser, block, out, allow_cases))
3482 con_out("__builtin_debug_printtype: got no output node\n");
3485 ast_type_to_string(*out, ty, sizeof(ty));
3486 con_out("__builtin_debug_printtype: `%s`\n", ty);
3491 else if (!strcmp(parser_tokval(parser), "return"))
3493 return parse_return(parser, block, out);
3495 else if (!strcmp(parser_tokval(parser), "if"))
3497 return parse_if(parser, block, out);
3499 else if (!strcmp(parser_tokval(parser), "while"))
3501 return parse_while(parser, block, out);
3503 else if (!strcmp(parser_tokval(parser), "do"))
3505 return parse_dowhile(parser, block, out);
3507 else if (!strcmp(parser_tokval(parser), "for"))
3509 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3510 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3513 return parse_for(parser, block, out);
3515 else if (!strcmp(parser_tokval(parser), "break"))
3517 return parse_break_continue(parser, block, out, false);
3519 else if (!strcmp(parser_tokval(parser), "continue"))
3521 return parse_break_continue(parser, block, out, true);
3523 else if (!strcmp(parser_tokval(parser), "switch"))
3525 return parse_switch(parser, block, out);
3527 else if (!strcmp(parser_tokval(parser), "case") ||
3528 !strcmp(parser_tokval(parser), "default"))
3531 parseerror(parser, "unexpected 'case' label");
3536 else if (!strcmp(parser_tokval(parser), "goto"))
3538 return parse_goto(parser, out);
3540 else if (!strcmp(parser_tokval(parser), "typedef"))
3542 if (!parser_next(parser)) {
3543 parseerror(parser, "expected type definition after 'typedef'");
3546 return parse_typedef(parser);
3548 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3551 else if (parser->tok == '{')
3554 inner = parse_block(parser);
3560 else if (parser->tok == ':')
3564 if (!parser_next(parser)) {
3565 parseerror(parser, "expected label name");
3568 if (parser->tok != TOKEN_IDENT) {
3569 parseerror(parser, "label must be an identifier");
3572 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3574 if (!label->m_undefined) {
3575 parseerror(parser, "label `%s` already defined", label->m_name);
3578 label->m_undefined = false;
3581 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3582 parser->labels.push_back(label);
3585 if (!parser_next(parser)) {
3586 parseerror(parser, "parse error after label");
3589 for (i = 0; i < parser->gotos.size(); ++i) {
3590 if (parser->gotos[i]->m_name == label->m_name) {
3591 parser->gotos[i]->setLabel(label);
3592 parser->gotos.erase(parser->gotos.begin() + i);
3598 else if (parser->tok == ';')
3600 if (!parser_next(parser)) {
3601 parseerror(parser, "parse error after empty statement");
3608 lex_ctx_t ctx = parser_ctx(parser);
3609 ast_expression *exp = parse_expression(parser, false, false);
3613 if (!exp->m_side_effects) {
3614 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3621 static bool parse_enum(parser_t *parser)
3624 bool reverse = false;
3626 ast_value *var = nullptr;
3628 std::vector<ast_value*> values;
3630 ast_expression *old;
3632 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3633 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3637 /* enumeration attributes (can add more later) */
3638 if (parser->tok == ':') {
3639 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3640 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3645 if (!strcmp(parser_tokval(parser), "flag")) {
3649 else if (!strcmp(parser_tokval(parser), "reverse")) {
3653 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3657 if (!parser_next(parser) || parser->tok != '{') {
3658 parseerror(parser, "expected `{` after enum attribute ");
3664 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3665 if (parser->tok == '}') {
3666 /* allow an empty enum */
3669 parseerror(parser, "expected identifier or `}`");
3673 old = parser_find_field(parser, parser_tokval(parser));
3675 old = parser_find_global(parser, parser_tokval(parser));
3677 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3678 parser_tokval(parser), old->m_context.file, old->m_context.line);
3682 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3683 values.push_back(var);
3684 var->m_cvq = CV_CONST;
3685 var->m_hasvalue = true;
3687 /* for flagged enumerations increment in POTs of TWO */
3688 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3689 parser_addglobal(parser, var->m_name, var);
3691 if (!parser_next(parser)) {
3692 parseerror(parser, "expected `=`, `}` or comma after identifier");
3696 if (parser->tok == ',')
3698 if (parser->tok == '}')
3700 if (parser->tok != '=') {
3701 parseerror(parser, "expected `=`, `}` or comma after identifier");
3705 if (!parser_next(parser)) {
3706 parseerror(parser, "expected expression after `=`");
3710 /* We got a value! */
3711 old = parse_expression_leave(parser, true, false, false);
3712 asvalue = (ast_value*)old;
3713 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3714 compile_error(var->m_context, "constant value or expression expected");
3717 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3719 if (parser->tok == '}')
3721 if (parser->tok != ',') {
3722 parseerror(parser, "expected `}` or comma after expression");
3727 /* patch them all (for reversed attribute) */
3730 for (i = 0; i < values.size(); i++)
3731 values[i]->m_constval.vfloat = values.size() - i - 1;
3734 if (parser->tok != '}') {
3735 parseerror(parser, "internal error: breaking without `}`");
3739 if (!parser_next(parser) || parser->tok != ';') {
3740 parseerror(parser, "expected semicolon after enumeration");
3744 if (!parser_next(parser)) {
3745 parseerror(parser, "parse error after enumeration");
3752 static bool parse_block_into(parser_t *parser, ast_block *block)
3756 parser_enterblock(parser);
3758 if (!parser_next(parser)) { /* skip the '{' */
3759 parseerror(parser, "expected function body");
3763 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3765 ast_expression *expr = nullptr;
3766 if (parser->tok == '}')
3769 if (!parse_statement(parser, block, &expr, false)) {
3770 /* parseerror(parser, "parse error"); */
3776 if (!block->addExpr(expr)) {
3783 if (parser->tok != '}') {
3786 (void)parser_next(parser);
3790 if (!parser_leaveblock(parser))
3792 return retval && !!block;
3795 static ast_block* parse_block(parser_t *parser)
3798 block = new ast_block(parser_ctx(parser));
3801 if (!parse_block_into(parser, block)) {
3808 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3810 if (parser->tok == '{') {
3811 *out = parse_block(parser);
3814 return parse_statement(parser, nullptr, out, false);
3817 static bool create_vector_members(ast_value *var, ast_member **me)
3820 size_t len = var->m_name.length();
3822 for (i = 0; i < 3; ++i) {
3823 char *name = (char*)mem_a(len+3);
3824 memcpy(name, var->m_name.c_str(), len);
3826 name[len+1] = 'x'+i;
3828 me[i] = ast_member::make(var->m_context, var, i, name);
3837 do { delete me[--i]; } while(i);
3841 static bool parse_function_body(parser_t *parser, ast_value *var)
3843 ast_block *block = nullptr;
3847 ast_expression *framenum = nullptr;
3848 ast_expression *nextthink = nullptr;
3849 /* None of the following have to be deleted */
3850 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3851 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3852 bool has_frame_think;
3856 has_frame_think = false;
3857 old = parser->function;
3859 if (var->m_flags & AST_FLAG_ALIAS) {
3860 parseerror(parser, "function aliases cannot have bodies");
3864 if (parser->gotos.size() || parser->labels.size()) {
3865 parseerror(parser, "gotos/labels leaking");
3869 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3870 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3871 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3877 if (parser->tok == '[') {
3878 /* got a frame definition: [ framenum, nextthink ]
3879 * this translates to:
3880 * self.frame = framenum;
3881 * self.nextthink = time + 0.1;
3882 * self.think = nextthink;
3884 nextthink = nullptr;
3886 fld_think = parser_find_field(parser, "think");
3887 fld_nextthink = parser_find_field(parser, "nextthink");
3888 fld_frame = parser_find_field(parser, "frame");
3889 if (!fld_think || !fld_nextthink || !fld_frame) {
3890 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3891 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3894 gbl_time = parser_find_global(parser, "time");
3895 gbl_self = parser_find_global(parser, "self");
3896 if (!gbl_time || !gbl_self) {
3897 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3898 parseerror(parser, "please declare the following globals: `time`, `self`");
3902 if (!parser_next(parser))
3905 framenum = parse_expression_leave(parser, true, false, false);
3907 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3910 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3911 ast_unref(framenum);
3912 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3916 if (parser->tok != ',') {
3917 ast_unref(framenum);
3918 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3919 parseerror(parser, "Got a %i\n", parser->tok);
3923 if (!parser_next(parser)) {
3924 ast_unref(framenum);
3928 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3930 /* qc allows the use of not-yet-declared functions here
3931 * - this automatically creates a prototype */
3932 ast_value *thinkfunc;
3933 ast_expression *functype = fld_think->m_next;
3935 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3936 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3937 ast_unref(framenum);
3938 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3941 thinkfunc->adoptType(*functype);
3943 if (!parser_next(parser)) {
3944 ast_unref(framenum);
3949 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3951 nextthink = thinkfunc;
3954 nextthink = parse_expression_leave(parser, true, false, false);
3956 ast_unref(framenum);
3957 parseerror(parser, "expected a think-function in [frame,think] notation");
3962 if (!ast_istype(nextthink, ast_value)) {
3963 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3967 if (retval && parser->tok != ']') {
3968 parseerror(parser, "expected closing `]` for [frame,think] notation");
3972 if (retval && !parser_next(parser)) {
3976 if (retval && parser->tok != '{') {
3977 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3982 ast_unref(nextthink);
3983 ast_unref(framenum);
3987 has_frame_think = true;
3990 block = new ast_block(parser_ctx(parser));
3992 parseerror(parser, "failed to allocate block");
3993 if (has_frame_think) {
3994 ast_unref(nextthink);
3995 ast_unref(framenum);
4000 if (has_frame_think) {
4001 if (!OPTS_FLAG(EMULATE_STATE)) {
4002 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
4003 if (!block->addExpr(state_op)) {
4004 parseerror(parser, "failed to generate state op for [frame,think]");
4005 ast_unref(nextthink);
4006 ast_unref(framenum);
4011 /* emulate OP_STATE in code: */
4013 ast_expression *self_frame;
4014 ast_expression *self_nextthink;
4015 ast_expression *self_think;
4016 ast_expression *time_plus_1;
4017 ast_store *store_frame;
4018 ast_store *store_nextthink;
4019 ast_store *store_think;
4021 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4023 ctx = parser_ctx(parser);
4024 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
4025 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4026 self_think = new ast_entfield(ctx, gbl_self, fld_think);
4028 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
4029 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4031 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4032 if (self_frame) delete self_frame;
4033 if (self_nextthink) delete self_nextthink;
4034 if (self_think) delete self_think;
4035 if (time_plus_1) delete time_plus_1;
4041 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4042 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4043 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4049 if (!store_nextthink) {
4050 delete self_nextthink;
4058 if (store_frame) delete store_frame;
4059 if (store_nextthink) delete store_nextthink;
4060 if (store_think) delete store_think;
4063 if (!block->addExpr(store_frame) ||
4064 !block->addExpr(store_nextthink) ||
4065 !block->addExpr(store_think))
4072 parseerror(parser, "failed to generate code for [frame,think]");
4073 ast_unref(nextthink);
4074 ast_unref(framenum);
4081 if (var->m_hasvalue) {
4082 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4083 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4087 func = var->m_constval.vfunc;
4090 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4095 func = ast_function::make(var->m_context, var->m_name, var);
4098 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4102 parser->functions.push_back(func);
4105 parser_enterblock(parser);
4107 for (auto &it : var->m_type_params) {
4111 if (it->m_vtype != TYPE_VECTOR &&
4112 (it->m_vtype != TYPE_FIELD ||
4113 it->m_next->m_vtype != TYPE_VECTOR))
4118 if (!create_vector_members(it.get(), me)) {
4123 for (e = 0; e < 3; ++e) {
4124 parser_addlocal(parser, me[e]->m_name, me[e]);
4125 block->collect(me[e]);
4129 if (var->m_argcounter && !func->m_argc) {
4130 ast_value *argc = new ast_value(var->m_context, var->m_argcounter, TYPE_FLOAT);
4131 parser_addlocal(parser, argc->m_name, argc);
4132 func->m_argc.reset(argc);
4135 if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4137 ast_value *varargs = new ast_value(var->m_context, "reserved:va_args", TYPE_ARRAY);
4138 varargs->m_flags |= AST_FLAG_IS_VARARG;
4139 varargs->m_next = new ast_value(var->m_context, "", TYPE_VECTOR);
4140 varargs->m_count = 0;
4141 util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name.c_str());
4142 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4147 util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name.c_str());
4148 if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4153 func->m_varargs.reset(varargs);
4154 func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4157 parser->function = func;
4158 if (!parse_block_into(parser, block)) {
4163 func->m_blocks.emplace_back(block);
4165 parser->function = old;
4166 if (!parser_leaveblock(parser))
4168 if (parser->variables.size() != PARSER_HT_LOCALS) {
4169 parseerror(parser, "internal error: local scopes left");
4173 if (parser->tok == ';')
4174 return parser_next(parser);
4175 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4176 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4180 (void)!parser_leaveblock(parser);
4181 parser->functions.pop_back();
4183 var->m_constval.vfunc = nullptr;
4186 parser->function = old;
4190 static ast_expression *array_accessor_split(
4195 ast_expression *left,
4196 ast_expression *right
4202 lex_ctx_t ctx = array->m_context;
4204 if (!left || !right) {
4205 if (left) delete left;
4206 if (right) delete right;
4210 cmp = new ast_binary(ctx, INSTR_LT,
4212 parser->m_fold.constgen_float(middle, false));
4216 parseerror(parser, "internal error: failed to create comparison for array setter");
4220 ifthen = new ast_ifthen(ctx, cmp, left, right);
4222 delete cmp; /* will delete left and right */
4223 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4230 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4232 lex_ctx_t ctx = array->m_context;
4234 if (from+1 == afterend) {
4235 /* set this value */
4238 ast_array_index *subscript;
4240 int assignop = type_store_instr[value->m_vtype];
4242 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4243 assignop = INSTR_STORE_V;
4245 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4249 st = new ast_store(ctx, assignop, subscript, value);
4255 block = new ast_block(ctx);
4261 if (!block->addExpr(st)) {
4266 ret = new ast_return(ctx, nullptr);
4272 if (!block->addExpr(ret)) {
4279 ast_expression *left, *right;
4280 size_t diff = afterend - from;
4281 size_t middle = from + diff/2;
4282 left = array_setter_node(parser, array, index, value, from, middle);
4283 right = array_setter_node(parser, array, index, value, middle, afterend);
4284 return array_accessor_split(parser, array, index, middle, left, right);
4288 static ast_expression *array_field_setter_node(
4297 lex_ctx_t ctx = array->m_context;
4299 if (from+1 == afterend) {
4300 /* set this value */
4303 ast_entfield *entfield;
4304 ast_array_index *subscript;
4306 int assignop = type_storep_instr[value->m_vtype];
4308 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4309 assignop = INSTR_STOREP_V;
4311 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4315 subscript->m_next = new ast_expression(ast_copy_type, subscript->m_context, *subscript);
4316 subscript->m_vtype = TYPE_FIELD;
4318 entfield = new ast_entfield(ctx, entity, subscript, subscript);
4324 st = new ast_store(ctx, assignop, entfield, value);
4330 block = new ast_block(ctx);
4336 if (!block->addExpr(st)) {
4341 ret = new ast_return(ctx, nullptr);
4347 if (!block->addExpr(ret)) {
4354 ast_expression *left, *right;
4355 size_t diff = afterend - from;
4356 size_t middle = from + diff/2;
4357 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4358 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4359 return array_accessor_split(parser, array, index, middle, left, right);
4363 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4365 lex_ctx_t ctx = array->m_context;
4367 if (from+1 == afterend) {
4369 ast_array_index *subscript;
4371 subscript = ast_array_index::make(ctx, array, parser->m_fold.constgen_float(from, false));
4375 ret = new ast_return(ctx, subscript);
4383 ast_expression *left, *right;
4384 size_t diff = afterend - from;
4385 size_t middle = from + diff/2;
4386 left = array_getter_node(parser, array, index, from, middle);
4387 right = array_getter_node(parser, array, index, middle, afterend);
4388 return array_accessor_split(parser, array, index, middle, left, right);
4392 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4394 ast_function *func = nullptr;
4395 ast_value *fval = nullptr;
4396 ast_block *body = nullptr;
4398 fval = new ast_value(array->m_context, funcname, TYPE_FUNCTION);
4400 parseerror(parser, "failed to create accessor function value");
4403 fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4405 func = ast_function::make(array->m_context, funcname, fval);
4408 parseerror(parser, "failed to create accessor function node");
4412 body = new ast_block(array->m_context);
4414 parseerror(parser, "failed to create block for array accessor");
4420 func->m_blocks.emplace_back(body);
4423 parser->accessors.push_back(fval);
4428 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4430 ast_value *index = nullptr;
4431 ast_value *value = nullptr;
4435 if (!ast_istype(array->m_next, ast_value)) {
4436 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4440 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4442 func = fval->m_constval.vfunc;
4443 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4445 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4446 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4448 if (!index || !value) {
4449 parseerror(parser, "failed to create locals for array accessor");
4452 value->m_name = "value"; // not important
4453 fval->m_type_params.emplace_back(index);
4454 fval->m_type_params.emplace_back(value);
4456 array->m_setter = fval;
4459 if (index) delete index;
4460 if (value) delete value;
4466 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4468 ast_expression *root = nullptr;
4469 root = array_setter_node(parser, array,
4470 array->m_setter->m_type_params[0].get(),
4471 array->m_setter->m_type_params[1].get(),
4474 parseerror(parser, "failed to build accessor search tree");
4477 if (!array->m_setter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4484 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4486 if (!parser_create_array_setter_proto(parser, array, funcname))
4488 return parser_create_array_setter_impl(parser, array);
4491 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4493 ast_expression *root = nullptr;
4494 ast_value *entity = nullptr;
4495 ast_value *index = nullptr;
4496 ast_value *value = nullptr;
4500 if (!ast_istype(array->m_next, ast_value)) {
4501 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4505 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4507 func = fval->m_constval.vfunc;
4508 fval->m_next = new ast_value(array->m_context, "<void>", TYPE_VOID);
4510 entity = new ast_value(array->m_context, "entity", TYPE_ENTITY);
4511 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4512 value = new ast_value(ast_copy_type, *(ast_value*)array->m_next);
4513 if (!entity || !index || !value) {
4514 parseerror(parser, "failed to create locals for array accessor");
4517 value->m_name = "value"; // not important
4518 fval->m_type_params.emplace_back(entity);
4519 fval->m_type_params.emplace_back(index);
4520 fval->m_type_params.emplace_back(value);
4522 root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4524 parseerror(parser, "failed to build accessor search tree");
4528 array->m_setter = fval;
4529 return func->m_blocks[0].get()->addExpr(root);
4531 if (entity) delete entity;
4532 if (index) delete index;
4533 if (value) delete value;
4534 if (root) delete root;
4540 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4542 ast_value *index = nullptr;
4546 /* NOTE: checking array->m_next rather than elemtype since
4547 * for fields elemtype is a temporary fieldtype.
4549 if (!ast_istype(array->m_next, ast_value)) {
4550 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4554 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4556 func = fval->m_constval.vfunc;
4557 fval->m_next = new ast_expression(ast_copy_type, array->m_context, *elemtype);
4559 index = new ast_value(array->m_context, "index", TYPE_FLOAT);
4562 parseerror(parser, "failed to create locals for array accessor");
4565 fval->m_type_params.emplace_back(index);
4567 array->m_getter = fval;
4570 if (index) delete index;
4576 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4578 ast_expression *root = nullptr;
4580 root = array_getter_node(parser, array, array->m_getter->m_type_params[0].get(), 0, array->m_count);
4582 parseerror(parser, "failed to build accessor search tree");
4585 if (!array->m_getter->m_constval.vfunc->m_blocks[0].get()->addExpr(root)) {
4592 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4594 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4596 return parser_create_array_getter_impl(parser, array);
4599 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4601 lex_ctx_t ctx = parser_ctx(parser);
4602 std::vector<std::unique_ptr<ast_value>> params;
4605 bool variadic = false;
4606 ast_value *varparam = nullptr;
4607 char *argcounter = nullptr;
4609 /* for the sake of less code we parse-in in this function */
4610 if (!parser_next(parser)) {
4612 parseerror(parser, "expected parameter list");
4616 /* parse variables until we hit a closing paren */
4617 while (parser->tok != ')') {
4618 bool is_varargs = false;
4621 /* there must be commas between them */
4622 if (parser->tok != ',') {
4623 parseerror(parser, "expected comma or end of parameter list");
4626 if (!parser_next(parser)) {
4627 parseerror(parser, "expected parameter");
4633 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4634 if (!param && !is_varargs)
4637 /* '...' indicates a varargs function */
4639 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4640 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4643 if (parser->tok == TOKEN_IDENT) {
4644 argcounter = util_strdup(parser_tokval(parser));
4645 if (!parser_next(parser) || parser->tok != ')') {
4646 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4651 params.emplace_back(param);
4652 if (param->m_vtype >= TYPE_VARIANT) {
4653 char tname[1024]; /* typename is reserved in C++ */
4654 ast_type_to_string(param, tname, sizeof(tname));
4655 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4658 /* type-restricted varargs */
4659 if (parser->tok == TOKEN_DOTS) {
4661 varparam = params.back().release();
4663 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4664 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4667 if (parser->tok == TOKEN_IDENT) {
4668 argcounter = util_strdup(parser_tokval(parser));
4669 param->m_name = argcounter;
4670 if (!parser_next(parser) || parser->tok != ')') {
4671 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4676 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4677 parseerror(parser, "parameter name omitted");
4683 if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4687 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4688 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4691 if (!parser_next(parser)) {
4692 parseerror(parser, "parse error after typename");
4696 /* now turn 'var' into a function type */
4697 fval = new ast_value(ctx, "<type()>", TYPE_FUNCTION);
4700 fval->m_flags |= AST_FLAG_VARIADIC;
4703 var->m_type_params = move(params);
4704 var->m_varparam = varparam;
4705 var->m_argcounter = argcounter;
4718 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4720 ast_expression *cexp;
4721 ast_value *cval, *tmp;
4724 ctx = parser_ctx(parser);
4726 if (!parser_next(parser)) {
4728 parseerror(parser, "expected array-size");
4732 if (parser->tok != ']') {
4733 cexp = parse_expression_leave(parser, true, false, false);
4735 if (!cexp || !ast_istype(cexp, ast_value)) {
4739 parseerror(parser, "expected array-size as constant positive integer");
4742 cval = (ast_value*)cexp;
4749 tmp = new ast_value(ctx, "<type[]>", TYPE_ARRAY);
4754 if (cval->m_vtype == TYPE_INTEGER)
4755 tmp->m_count = cval->m_constval.vint;
4756 else if (cval->m_vtype == TYPE_FLOAT)
4757 tmp->m_count = cval->m_constval.vfloat;
4761 parseerror(parser, "array-size must be a positive integer constant");
4768 var->m_flags |= AST_FLAG_ARRAY_INIT;
4771 if (parser->tok != ']') {
4773 parseerror(parser, "expected ']' after array-size");
4776 if (!parser_next(parser)) {
4778 parseerror(parser, "error after parsing array size");
4784 /* Parse a complete typename.
4785 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4786 * but when parsing variables separated by comma
4787 * 'storebase' should point to where the base-type should be kept.
4788 * The base type makes up every bit of type information which comes *before* the
4791 * NOTE: The value must either be named, have a nullptr name, or a name starting
4792 * with '<'. In the first case, this will be the actual variable or type
4793 * name, in the other cases it is assumed that the name will appear
4794 * later, and an error is generated otherwise.
4796 * The following will be parsed in its entirety:
4798 * The 'basetype' in this case is 'void()'
4799 * and if there's a comma after it, say:
4801 * then the type-information 'void()' can be stored in 'storebase'
4803 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4805 ast_value *var, *tmp;
4808 const char *name = nullptr;
4809 bool isfield = false;
4810 bool wasarray = false;
4811 size_t morefields = 0;
4813 bool vararg = (parser->tok == TOKEN_DOTS);
4815 ctx = parser_ctx(parser);
4817 /* types may start with a dot */
4818 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4820 if (parser->tok == TOKEN_DOTS)
4822 /* if we parsed a dot we need a typename now */
4823 if (!parser_next(parser)) {
4824 parseerror(parser, "expected typename for field definition");
4828 /* Further dots are handled seperately because they won't be part of the
4832 if (parser->tok == '.')
4834 else if (parser->tok == TOKEN_DOTS)
4839 if (!parser_next(parser)) {
4840 parseerror(parser, "expected typename for field definition");
4845 if (parser->tok == TOKEN_IDENT)
4846 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4847 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4848 if (vararg && is_vararg) {
4852 parseerror(parser, "expected typename");
4856 /* generate the basic type value */
4857 if (cached_typedef) {
4858 var = new ast_value(ast_copy_type, *cached_typedef);
4859 var->m_name = "<type(from_def)>";
4861 var = new ast_value(ctx, "<type>", parser_token(parser)->constval.t);
4863 for (; morefields; --morefields) {
4864 tmp = new ast_value(ctx, "<.type>", TYPE_FIELD);
4869 /* do not yet turn into a field - remember:
4870 * .void() foo; is a field too
4871 * .void()() foo; is a function
4875 if (!parser_next(parser)) {
4877 parseerror(parser, "parse error after typename");
4881 /* an opening paren now starts the parameter-list of a function
4882 * this is where original-QC has parameter lists.
4883 * We allow a single parameter list here.
4884 * Much like fteqcc we don't allow `float()() x`
4886 if (parser->tok == '(') {
4887 var = parse_parameter_list(parser, var);
4892 /* store the base if requested */
4894 *storebase = new ast_value(ast_copy_type, *var);
4896 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4897 tmp->m_next = *storebase;
4902 /* there may be a name now */
4903 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4904 if (!strcmp(parser_tokval(parser), "break"))
4905 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4906 else if (parser->tok == TOKEN_KEYWORD)
4909 name = util_strdup(parser_tokval(parser));
4912 if (!parser_next(parser)) {
4915 parseerror(parser, "error after variable or field declaration");
4921 /* now this may be an array */
4922 if (parser->tok == '[') {
4924 var = parse_arraysize(parser, var);
4926 if (name) mem_d(name);
4931 /* This is the point where we can turn it into a field */
4933 /* turn it into a field if desired */
4934 tmp = new ast_value(ctx, "<type:f>", TYPE_FIELD);
4939 /* now there may be function parens again */
4940 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4941 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4942 if (parser->tok == '(' && wasarray)
4943 parseerror(parser, "arrays as part of a return type is not supported");
4944 while (parser->tok == '(') {
4945 var = parse_parameter_list(parser, var);
4947 if (name) mem_d(name);
4952 /* finally name it */
4955 // free the name, ast_value_set_name duplicates
4962 static bool parse_typedef(parser_t *parser)
4964 ast_value *typevar, *oldtype;
4965 ast_expression *old;
4967 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4972 // while parsing types, the ast_value's get named '<something>'
4973 if (!typevar->m_name.length() || typevar->m_name[0] == '<') {
4974 parseerror(parser, "missing name in typedef");
4979 if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4980 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4981 " -> `%s` has been declared here: %s:%i",
4982 typevar->m_name, old->m_context.file, old->m_context.line);
4987 if ( (oldtype = parser_find_typedef(parser, typevar->m_name, parser->_blocktypedefs.back())) ) {
4988 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4989 typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
4994 parser->_typedefs.emplace_back(typevar);
4995 util_htset(parser->typedefs.back(), typevar->m_name.c_str(), typevar);
4997 if (parser->tok != ';') {
4998 parseerror(parser, "expected semicolon after typedef");
5001 if (!parser_next(parser)) {
5002 parseerror(parser, "parse error after typedef");
5009 static const char *cvq_to_str(int cvq) {
5011 case CV_NONE: return "none";
5012 case CV_VAR: return "`var`";
5013 case CV_CONST: return "`const`";
5014 default: return "<INVALID>";
5018 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5021 if (proto->m_cvq != var->m_cvq) {
5022 if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
5023 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5024 parser->tok == '='))
5026 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5027 "`%s` declared with different qualifiers: %s\n"
5028 " -> previous declaration here: %s:%i uses %s",
5029 var->m_name, cvq_to_str(var->m_cvq),
5030 proto->m_context.file, proto->m_context.line,
5031 cvq_to_str(proto->m_cvq));
5034 av = (var ->m_flags & AST_FLAG_NORETURN);
5035 ao = (proto->m_flags & AST_FLAG_NORETURN);
5037 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5038 "`%s` declared with different attributes%s\n"
5039 " -> previous declaration here: %s:%i",
5040 var->m_name, (av ? ": noreturn" : ""),
5041 proto->m_context.file, proto->m_context.line,
5042 (ao ? ": noreturn" : ""));
5047 static bool create_array_accessors(parser_t *parser, ast_value *var)
5050 util_snprintf(name, sizeof(name), "%s##SET", var->m_name.c_str());
5051 if (!parser_create_array_setter(parser, var, name))
5053 util_snprintf(name, sizeof(name), "%s##GET", var->m_name.c_str());
5054 if (!parser_create_array_getter(parser, var, var->m_next, name))
5059 static bool parse_array(parser_t *parser, ast_value *array)
5062 if (array->m_initlist.size()) {
5063 parseerror(parser, "array already initialized elsewhere");
5066 if (!parser_next(parser)) {
5067 parseerror(parser, "parse error in array initializer");
5071 while (parser->tok != '}') {
5072 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5075 if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5077 parseerror(parser, "initializing element must be a compile time constant");
5080 array->m_initlist.push_back(v->m_constval);
5081 if (v->m_vtype == TYPE_STRING) {
5082 array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5086 if (parser->tok == '}')
5088 if (parser->tok != ',' || !parser_next(parser)) {
5089 parseerror(parser, "expected comma or '}' in element list");
5093 if (!parser_next(parser) || parser->tok != ';') {
5094 parseerror(parser, "expected semicolon after initializer, got %s");
5098 if (!parser_next(parser)) {
5099 parseerror(parser, "parse error after initializer");
5104 if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5105 if (array->m_count != (size_t)-1) {
5106 parseerror(parser, "array `%s' has already been initialized with %u elements",
5107 array->m_name, (unsigned)array->m_count);
5109 array->m_count = array->m_initlist.size();
5110 if (!create_array_accessors(parser, array))
5116 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)
5120 ast_expression *old;
5124 ast_value *basetype = nullptr;
5126 bool isparam = false;
5127 bool isvector = false;
5128 bool cleanvar = true;
5129 bool wasarray = false;
5131 ast_member *me[3] = { nullptr, nullptr, nullptr };
5132 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5134 if (!localblock && is_static)
5135 parseerror(parser, "`static` qualifier is not supported in global scope");
5137 /* get the first complete variable */
5138 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5145 /* while parsing types, the ast_value's get named '<something>' */
5146 if (!var->m_name.length() || var->m_name[0] == '<') {
5147 parseerror(parser, "declaration does not declare anything");
5157 /* Part 0: finish the type */
5158 if (parser->tok == '(') {
5159 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5160 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5161 var = parse_parameter_list(parser, var);
5167 /* we only allow 1-dimensional arrays */
5168 if (parser->tok == '[') {
5170 var = parse_arraysize(parser, var);
5176 if (parser->tok == '(' && wasarray) {
5177 parseerror(parser, "arrays as part of a return type is not supported");
5178 /* we'll still parse the type completely for now */
5180 /* for functions returning functions */
5181 while (parser->tok == '(') {
5182 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5183 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5184 var = parse_parameter_list(parser, var);
5191 var->m_cvq = qualifier;
5192 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5193 var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5194 var->m_flags |= qflags;
5197 * store the vstring back to var for alias and
5198 * deprecation messages.
5200 if (var->m_flags & AST_FLAG_DEPRECATED || var->m_flags & AST_FLAG_ALIAS)
5201 var->m_desc = vstring;
5203 if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5204 parseerror(parser, "function aliases cannot be forward declared");
5211 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5212 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5213 * is then filled with the previous definition and the parameter-names replaced.
5215 if (var->m_name == "nil") {
5216 if (OPTS_FLAG(UNTYPED_NIL)) {
5217 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5218 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5220 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5223 /* Deal with end_sys_ vars */
5225 if (var->m_name == "end_sys_globals") {
5226 var->m_flags |= AST_FLAG_NOREF;
5227 parser->crc_globals = parser->globals.size();
5230 else if (var->m_name == "end_sys_fields") {
5231 var->m_flags |= AST_FLAG_NOREF;
5232 parser->crc_fields = parser->fields.size();
5235 if (was_end && var->m_vtype == TYPE_FIELD) {
5236 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5237 "global '%s' hint should not be a field",
5238 parser_tokval(parser)))
5245 if (!nofields && var->m_vtype == TYPE_FIELD)
5247 /* deal with field declarations */
5248 old = parser_find_field(parser, var->m_name);
5250 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5251 var->m_name, old->m_context.file, (int)old->m_context.line))
5260 parseerror(parser, "field `%s` already declared here: %s:%i",
5261 var->m_name, old->m_context.file, old->m_context.line);
5266 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5267 (old = parser_find_global(parser, var->m_name)))
5269 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5270 parseerror(parser, "field `%s` already declared here: %s:%i",
5271 var->m_name, old->m_context.file, old->m_context.line);
5278 /* deal with other globals */
5279 old = parser_find_global(parser, var->m_name);
5280 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5282 /* This is a function which had a prototype */
5283 if (!ast_istype(old, ast_value)) {
5284 parseerror(parser, "internal error: prototype is not an ast_value");
5288 proto = (ast_value*)old;
5289 proto->m_desc = var->m_desc;
5290 if (!proto->compareType(*var)) {
5291 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5293 proto->m_context.file, proto->m_context.line);
5297 /* we need the new parameter-names */
5298 for (i = 0; i < proto->m_type_params.size(); ++i)
5299 proto->m_type_params[i]->m_name = var->m_type_params[i]->m_name;
5300 if (!parser_check_qualifiers(parser, var, proto)) {
5305 proto->m_flags |= var->m_flags;
5313 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5314 "global `%s` already declared here: %s:%i",
5315 var->m_name, old->m_context.file, old->m_context.line))
5320 if (old->m_flags & AST_FLAG_FINAL_DECL) {
5321 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5322 var->m_name, old->m_context.file, old->m_context.line);
5326 proto = (ast_value*)old;
5327 if (!ast_istype(old, ast_value)) {
5328 parseerror(parser, "internal error: not an ast_value");
5333 if (!parser_check_qualifiers(parser, var, proto)) {
5338 proto->m_flags |= var->m_flags;
5339 /* copy the context for finals,
5340 * so the error can show where it was actually made 'final'
5342 if (proto->m_flags & AST_FLAG_FINAL_DECL)
5343 old->m_context = var->m_context;
5347 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5348 (old = parser_find_field(parser, var->m_name)))
5350 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5351 parseerror(parser, "global `%s` already declared here: %s:%i",
5352 var->m_name, old->m_context.file, old->m_context.line);
5359 else /* it's not a global */
5361 old = parser_find_local(parser, var->m_name, parser->variables.size()-1, &isparam);
5362 if (old && !isparam) {
5363 parseerror(parser, "local `%s` already declared here: %s:%i",
5364 var->m_name, old->m_context.file, (int)old->m_context.line);
5368 /* doing this here as the above is just for a single scope */
5369 old = parser_find_local(parser, var->m_name, 0, &isparam);
5370 if (old && isparam) {
5371 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5372 "local `%s` is shadowing a parameter", var->m_name))
5374 parseerror(parser, "local `%s` already declared here: %s:%i",
5375 var->m_name, old->m_context.file, (int)old->m_context.line);
5379 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5381 if (ast_istype(old, ast_value))
5382 var = proto = (ast_value*)old;
5391 if (noref || parser->noref)
5392 var->m_flags |= AST_FLAG_NOREF;
5395 * Create the global/local, and deal with vector types.
5398 if (var->m_vtype == TYPE_VECTOR)
5400 else if (var->m_vtype == TYPE_FIELD &&
5401 var->m_next->m_vtype == TYPE_VECTOR)
5405 if (!create_vector_members(var, me)) {
5412 /* deal with global variables, fields, functions */
5413 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5414 var->m_isfield = true;
5415 parser->fields.push_back(var);
5416 util_htset(parser->htfields, var->m_name.c_str(), var);
5418 for (i = 0; i < 3; ++i) {
5419 parser->fields.push_back(me[i]);
5420 util_htset(parser->htfields, me[i]->m_name.c_str(), me[i]);
5425 if (!(var->m_flags & AST_FLAG_ALIAS)) {
5426 parser_addglobal(parser, var->m_name, var);
5428 for (i = 0; i < 3; ++i) {
5429 parser_addglobal(parser, me[i]->m_name.c_str(), me[i]);
5433 ast_expression *find = parser_find_global(parser, var->m_desc);
5436 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5440 if (!var->compareType(*find)) {
5444 ast_type_to_string(find, ty1, sizeof(ty1));
5445 ast_type_to_string(var, ty2, sizeof(ty2));
5447 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5448 ty1, ty2, var->m_name
5453 util_htset(parser->aliases, var->m_name.c_str(), find);
5455 /* generate aliases for vector components */
5459 util_asprintf(&buffer[0], "%s_x", var->m_desc.c_str());
5460 util_asprintf(&buffer[1], "%s_y", var->m_desc.c_str());
5461 util_asprintf(&buffer[2], "%s_z", var->m_desc.c_str());
5463 util_htset(parser->aliases, me[0]->m_name.c_str(), parser_find_global(parser, buffer[0]));
5464 util_htset(parser->aliases, me[1]->m_name.c_str(), parser_find_global(parser, buffer[1]));
5465 util_htset(parser->aliases, me[2]->m_name.c_str(), parser_find_global(parser, buffer[2]));
5475 // a static adds itself to be generated like any other global
5476 // but is added to the local namespace instead
5477 std::string defname;
5481 defname = parser->function->m_name;
5482 defname.append(2, ':');
5484 // remember the length up to here
5485 prefix_len = defname.length();
5487 // Add it to the local scope
5488 util_htset(parser->variables.back(), var->m_name.c_str(), (void*)var);
5490 // now rename the global
5491 defname.append(var->m_name);
5492 // if a variable of that name already existed, add the
5494 // The counter is incremented either way.
5495 sn_size = parser->function->m_static_names.size();
5496 for (sn = 0; sn != sn_size; ++sn) {
5497 if (parser->function->m_static_names[sn] == var->m_name.c_str())
5500 if (sn != sn_size) {
5501 char *num = nullptr;
5502 int len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5503 defname.append(num, 0, len);
5507 parser->function->m_static_names.emplace_back(var->m_name);
5508 parser->function->m_static_count++;
5509 var->m_name = defname;
5511 // push it to the to-be-generated globals
5512 parser->globals.push_back(var);
5514 // same game for the vector members
5516 defname.erase(prefix_len);
5517 for (i = 0; i < 3; ++i) {
5518 util_htset(parser->variables.back(), me[i]->m_name.c_str(), (void*)(me[i]));
5519 me[i]->m_name = defname + me[i]->m_name;
5520 parser->globals.push_back(me[i]);
5524 localblock->m_locals.push_back(var);
5525 parser_addlocal(parser, var->m_name, var);
5527 for (i = 0; i < 3; ++i) {
5528 parser_addlocal(parser, me[i]->m_name, me[i]);
5529 localblock->collect(me[i]);
5535 memcpy(last_me, me, sizeof(me));
5536 me[0] = me[1] = me[2] = nullptr;
5541 if (var->m_vtype == TYPE_ARRAY) {
5542 if (var->m_count != (size_t)-1) {
5543 if (!create_array_accessors(parser, var))
5547 else if (!localblock && !nofields &&
5548 var->m_vtype == TYPE_FIELD &&
5549 var->m_next->m_vtype == TYPE_ARRAY)
5552 ast_expression *telem;
5554 ast_value *array = (ast_value*)var->m_next;
5556 if (!ast_istype(var->m_next, ast_value)) {
5557 parseerror(parser, "internal error: field element type must be an ast_value");
5561 util_snprintf(name, sizeof(name), "%s##SETF", var->m_name.c_str());
5562 if (!parser_create_array_field_setter(parser, array, name))
5565 telem = new ast_expression(ast_copy_type, var->m_context, *array->m_next);
5566 tfield = new ast_value(var->m_context, "<.type>", TYPE_FIELD);
5567 tfield->m_next = telem;
5568 util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name.c_str());
5569 if (!parser_create_array_getter(parser, array, tfield, name)) {
5577 if (parser->tok == ';') {
5579 if (!parser_next(parser)) {
5580 parseerror(parser, "error after variable declaration");
5586 if (parser->tok == ',')
5590 if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5593 parseerror(parser, "missing comma or semicolon while parsing variables");
5597 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5598 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5599 "initializing expression turns variable `%s` into a constant in this standard",
5606 if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) {
5607 if (parser->tok != '=') {
5608 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5612 if (!parser_next(parser)) {
5613 parseerror(parser, "error parsing initializer");
5617 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5618 parseerror(parser, "expected '=' before function body in this standard");
5621 if (parser->tok == '#') {
5622 ast_function *func = nullptr;
5623 ast_value *number = nullptr;
5629 parseerror(parser, "cannot declare builtins within functions");
5632 if (var->m_vtype != TYPE_FUNCTION) {
5633 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5636 if (!parser_next(parser)) {
5637 parseerror(parser, "expected builtin number");
5641 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5642 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5644 parseerror(parser, "builtin number expected");
5647 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5650 parseerror(parser, "builtin number must be a compile time constant");
5653 if (number->m_vtype == TYPE_INTEGER)
5654 builtin_num = number->m_constval.vint;
5655 else if (number->m_vtype == TYPE_FLOAT)
5656 builtin_num = number->m_constval.vfloat;
5659 parseerror(parser, "builtin number must be an integer constant");
5664 fractional = modff(builtin_num, &integral);
5665 if (builtin_num < 0 || fractional != 0) {
5666 parseerror(parser, "builtin number must be an integer greater than zero");
5670 /* we only want the integral part anyways */
5671 builtin_num = integral;
5672 } else if (parser->tok == TOKEN_INTCONST) {
5673 builtin_num = parser_token(parser)->constval.i;
5675 parseerror(parser, "builtin number must be a compile time constant");
5679 if (var->m_hasvalue) {
5680 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5681 "builtin `%s` has already been defined\n"
5682 " -> previous declaration here: %s:%i",
5683 var->m_name, var->m_context.file, (int)var->m_context.line);
5687 func = ast_function::make(var->m_context, var->m_name, var);
5689 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5692 parser->functions.push_back(func);
5694 func->m_builtin = -builtin_num-1;
5697 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5698 ? (parser->tok != ',' && parser->tok != ';')
5699 : (!parser_next(parser)))
5701 parseerror(parser, "expected comma or semicolon");
5703 var->m_constval.vfunc = nullptr;
5707 else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5710 /* Note that fteqcc and most others don't even *have*
5711 * local arrays, so this is not a high priority.
5713 parseerror(parser, "TODO: initializers for local arrays");
5717 var->m_hasvalue = true;
5718 if (!parse_array(parser, var))
5721 else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5724 parseerror(parser, "cannot declare functions within functions");
5729 proto->m_context = parser_ctx(parser);
5731 if (!parse_function_body(parser, var))
5734 for (auto &it : parser->gotos)
5735 parseerror(parser, "undefined label: `%s`", it->m_name);
5736 parser->gotos.clear();
5737 parser->labels.clear();
5740 ast_expression *cexp;
5742 bool folded_const = false;
5744 cexp = parse_expression_leave(parser, true, false, false);
5747 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5749 /* deal with foldable constants: */
5751 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5753 /* remove it from the current locals */
5755 for (i = 0; i < 3; ++i) {
5756 parser->_locals.pop_back();
5757 localblock->m_collect.pop_back();
5760 /* do sanity checking, this function really needs refactoring */
5761 if (parser->_locals.back() != var)
5762 parseerror(parser, "internal error: unexpected change in local variable handling");
5764 parser->_locals.pop_back();
5765 if (localblock->m_locals.back() != var)
5766 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5768 localblock->m_locals.pop_back();
5769 /* push it to the to-be-generated globals */
5770 parser->globals.push_back(var);
5772 for (i = 0; i < 3; ++i)
5773 parser->globals.push_back(last_me[i]);
5774 folded_const = true;
5777 if (folded_const || !localblock || is_static) {
5778 if (cval != parser->nil &&
5779 (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5782 parseerror(parser, "initializer is non constant");
5787 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5788 qualifier != CV_VAR)
5790 var->m_cvq = CV_CONST;
5792 if (cval == parser->nil)
5794 var->m_flags |= AST_FLAG_INITIALIZED;
5795 var->m_flags |= AST_FLAG_NOREF;
5799 var->m_hasvalue = true;
5800 if (cval->m_vtype == TYPE_STRING)
5801 var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5802 else if (cval->m_vtype == TYPE_FIELD)
5803 var->m_constval.vfield = cval;
5805 memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5813 var->m_cvq = CV_NONE;
5814 sy.out.push_back(syexp(var->m_context, var));
5815 sy.out.push_back(syexp(cexp->m_context, cexp));
5816 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5817 if (!parser_sy_apply_operator(parser, &sy))
5820 if (sy.out.size() != 1 && sy.ops.size() != 0)
5821 parseerror(parser, "internal error: leaked operands");
5822 if (!localblock->addExpr(sy.out[0].out))
5827 /* a constant initialized to an inexact value should be marked inexact:
5828 * const float x = <inexact>; should propagate the inexact flag
5830 if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5831 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5832 var->m_inexact = cval->m_inexact;
5837 if (parser->tok == ',') {
5838 if (!parser_next(parser)) {
5839 parseerror(parser, "expected another variable");
5843 if (parser->tok != TOKEN_IDENT) {
5844 parseerror(parser, "expected another variable");
5847 var = new ast_value(ast_copy_type, *basetype);
5849 var->m_name = parser_tokval(parser);
5850 if (!parser_next(parser)) {
5851 parseerror(parser, "error parsing variable declaration");
5857 if (parser->tok != ';') {
5858 parseerror(parser, "missing semicolon after variables");
5862 if (!parser_next(parser)) {
5863 parseerror(parser, "parse error after variable declaration");
5871 if (cleanvar && var)
5878 if (cleanvar && var)
5886 static bool parser_global_statement(parser_t *parser)
5890 bool is_static = false;
5891 uint32_t qflags = 0;
5892 ast_value *istype = nullptr;
5893 char *vstring = nullptr;
5895 if (parser->tok == TOKEN_IDENT)
5896 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5898 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5900 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5902 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5904 if (cvq == CV_WRONG)
5906 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5908 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5910 return parse_enum(parser);
5912 else if (parser->tok == TOKEN_KEYWORD)
5914 if (!strcmp(parser_tokval(parser), "typedef")) {
5915 if (!parser_next(parser)) {
5916 parseerror(parser, "expected type definition after 'typedef'");
5919 return parse_typedef(parser);
5921 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5924 else if (parser->tok == '#')
5926 return parse_pragma(parser);
5928 else if (parser->tok == '$')
5930 if (!parser_next(parser)) {
5931 parseerror(parser, "parse error");
5937 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5943 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5945 return util_crc16(old, str, strlen(str));
5948 static void progdefs_crc_file(const char *str)
5950 /* write to progdefs.h here */
5954 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5956 old = progdefs_crc_sum(old, str);
5957 progdefs_crc_file(str);
5961 static void generate_checksum(parser_t *parser, ir_builder *ir)
5963 uint16_t crc = 0xFFFF;
5967 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5968 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5970 progdefs_crc_file("\tint\tpad;\n");
5971 progdefs_crc_file("\tint\tofs_return[3];\n");
5972 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5973 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5974 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5975 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5976 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5977 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5978 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5979 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5981 for (i = 0; i < parser->crc_globals; ++i) {
5982 if (!ast_istype(parser->globals[i], ast_value))
5984 value = (ast_value*)(parser->globals[i]);
5985 switch (value->m_vtype) {
5986 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5987 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5988 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5989 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5991 crc = progdefs_crc_both(crc, "\tint\t");
5994 crc = progdefs_crc_both(crc, value->m_name.c_str());
5995 crc = progdefs_crc_both(crc, ";\n");
5997 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5998 for (i = 0; i < parser->crc_fields; ++i) {
5999 if (!ast_istype(parser->fields[i], ast_value))
6001 value = (ast_value*)(parser->fields[i]);
6002 switch (value->m_next->m_vtype) {
6003 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6004 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6005 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6006 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6008 crc = progdefs_crc_both(crc, "\tint\t");
6011 crc = progdefs_crc_both(crc, value->m_name.c_str());
6012 crc = progdefs_crc_both(crc, ";\n");
6014 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6015 ir->m_code->crc = crc;
6018 parser_t::parser_t()
6021 , ast_cleaned(false)
6026 , aliases(util_htnew(PARSER_HT_SIZE))
6027 , htfields(util_htnew(PARSER_HT_SIZE))
6028 , htglobals(util_htnew(PARSER_HT_SIZE))
6029 , assign_op(nullptr)
6031 , max_param_count(1)
6032 // finish initializing the rest of the parser before initializing
6033 // m_fold and m_intrin with the parser passed along
6037 variables.push_back(htfields);
6038 variables.push_back(htglobals);
6039 typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
6040 _blocktypedefs.push_back(0);
6042 lex_ctx_t empty_ctx;
6043 empty_ctx.file = "<internal>";
6045 empty_ctx.column = 0;
6046 nil = new ast_value(empty_ctx, "nil", TYPE_NIL);
6047 nil->m_cvq = CV_CONST;
6048 if (OPTS_FLAG(UNTYPED_NIL))
6049 util_htset(htglobals, "nil", (void*)nil);
6051 const_vec[0] = new ast_value(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6052 const_vec[1] = new ast_value(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6053 const_vec[2] = new ast_value(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6055 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6056 reserved_version = new ast_value(empty_ctx, "reserved:version", TYPE_STRING);
6057 reserved_version->m_cvq = CV_CONST;
6058 reserved_version->m_hasvalue = true;
6059 reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6060 reserved_version->m_flags |= AST_FLAG_NOREF;
6061 reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6063 reserved_version = nullptr;
6066 m_fold = fold(this);
6067 m_intrin = intrin(this);
6070 parser_t::~parser_t()
6075 parser_t *parser_create()
6080 parser = new parser_t;
6084 for (i = 0; i < operator_count; ++i) {
6085 if (operators[i].id == opid1('=')) {
6086 parser->assign_op = operators+i;
6090 if (!parser->assign_op) {
6091 con_err("internal error: initializing parser: failed to find assign operator\n");
6099 static bool parser_compile(parser_t *parser)
6101 /* initial lexer/parser state */
6102 parser->lex->flags.noops = true;
6104 if (parser_next(parser))
6106 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6108 if (!parser_global_statement(parser)) {
6109 if (parser->tok == TOKEN_EOF)
6110 parseerror(parser, "unexpected end of file");
6111 else if (compile_errors)
6112 parseerror(parser, "there have been errors, bailing out");
6113 lex_close(parser->lex);
6114 parser->lex = nullptr;
6119 parseerror(parser, "parse error");
6120 lex_close(parser->lex);
6121 parser->lex = nullptr;
6125 lex_close(parser->lex);
6126 parser->lex = nullptr;
6128 return !compile_errors;
6131 bool parser_compile_file(parser_t *parser, const char *filename)
6133 parser->lex = lex_open(filename);
6135 con_err("failed to open file \"%s\"\n", filename);
6138 return parser_compile(parser);
6141 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6143 parser->lex = lex_open_string(str, len, name);
6145 con_err("failed to create lexer for string \"%s\"\n", name);
6148 return parser_compile(parser);
6151 void parser_t::remove_ast()
6156 for (auto &it : accessors) {
6157 delete it->m_constval.vfunc;
6158 it->m_constval.vfunc = nullptr;
6161 for (auto &it : functions) delete it;
6162 for (auto &it : globals) delete it;
6163 for (auto &it : fields) delete it;
6165 for (auto &it : variables) util_htdel(it);
6167 _blocklocals.clear();
6171 for (auto &it : typedefs) util_htdel(it);
6173 _blocktypedefs.clear();
6179 delete const_vec[0];
6180 delete const_vec[1];
6181 delete const_vec[2];
6183 if (reserved_version)
6184 delete reserved_version;
6186 util_htdel(aliases);
6189 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6190 ast_expression *expr;
6194 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6198 for (auto &it : parser->functions) {
6199 if (it->m_name == "coverage") {
6205 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6206 con_out("coverage support requested but no coverage() builtin declared\n");
6213 cov = func->m_function_type;
6216 if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) {
6218 ast_type_to_string(expr, ty, sizeof(ty));
6219 con_out("invalid type for coverage(): %s\n", ty);
6224 ir->m_coverage_func = func->m_ir_func->m_value;
6228 bool parser_finish(parser_t *parser, const char *output)
6233 if (compile_errors) {
6234 con_out("*** there were compile errors\n");
6238 ir = new ir_builder("gmqcc_out");
6240 con_out("failed to allocate builder\n");
6244 for (auto &it : parser->fields) {
6246 if (!ast_istype(it, ast_value))
6248 ast_value *field = (ast_value*)it;
6249 hasvalue = field->m_hasvalue;
6250 field->m_hasvalue = false;
6251 if (!reinterpret_cast<ast_value*>(field)->generateGlobal(ir, true)) {
6252 con_out("failed to generate field %s\n", field->m_name.c_str());
6258 ast_expression *subtype;
6259 field->m_hasvalue = true;
6260 subtype = field->m_next;
6261 ifld = ir->createField(field->m_name, subtype->m_vtype);
6262 if (subtype->m_vtype == TYPE_FIELD)
6263 ifld->m_fieldtype = subtype->m_next->m_vtype;
6264 else if (subtype->m_vtype == TYPE_FUNCTION)
6265 ifld->m_outtype = subtype->m_next->m_vtype;
6266 (void)!field->m_ir_v->setField(ifld);
6269 for (auto &it : parser->globals) {
6271 if (!ast_istype(it, ast_value))
6273 asvalue = (ast_value*)it;
6274 if (!(asvalue->m_flags & AST_FLAG_NOREF) && asvalue->m_cvq != CV_CONST && asvalue->m_vtype != TYPE_FUNCTION) {
6275 retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE,
6276 "unused global: `%s`", asvalue->m_name);
6278 if (!asvalue->generateGlobal(ir, false)) {
6279 con_out("failed to generate global %s\n", asvalue->m_name.c_str());
6284 /* Build function vararg accessor ast tree now before generating
6285 * immediates, because the accessors may add new immediates
6287 for (auto &f : parser->functions) {
6289 if (parser->max_param_count > f->m_function_type->m_type_params.size()) {
6290 f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size();
6291 if (!parser_create_array_setter_impl(parser, f->m_varargs.get())) {
6292 con_out("failed to generate vararg setter for %s\n", f->m_name.c_str());
6296 if (!parser_create_array_getter_impl(parser, f->m_varargs.get())) {
6297 con_out("failed to generate vararg getter for %s\n", f->m_name.c_str());
6302 f->m_varargs = nullptr;
6306 /* Now we can generate immediates */
6307 if (!parser->m_fold.generate(ir))
6310 /* before generating any functions we need to set the coverage_func */
6311 if (!parser_set_coverage_func(parser, ir))
6313 for (auto &it : parser->globals) {
6314 if (!ast_istype(it, ast_value))
6316 ast_value *asvalue = (ast_value*)it;
6317 if (!(asvalue->m_flags & AST_FLAG_INITIALIZED))
6319 if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue)
6320 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT,
6321 "uninitialized constant: `%s`",
6323 else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue)
6324 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL,
6325 "uninitialized global: `%s`",
6328 if (!asvalue->generateAccessors(ir)) {
6333 for (auto &it : parser->fields) {
6334 ast_value *asvalue = (ast_value*)it->m_next;
6335 if (!ast_istype(asvalue, ast_value))
6337 if (asvalue->m_vtype != TYPE_ARRAY)
6339 if (!asvalue->generateAccessors(ir)) {
6344 if (parser->reserved_version &&
6345 !parser->reserved_version->generateGlobal(ir, false))
6347 con_out("failed to generate reserved::version");
6351 for (auto &f : parser->functions) {
6352 if (!f->generateFunction(ir)) {
6353 con_out("failed to generate function %s\n", f->m_name.c_str());
6359 generate_checksum(parser, ir);
6361 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6363 for (auto &it : parser->functions) {
6364 if (!ir_function_finalize(it->m_ir_func)) {
6365 con_out("failed to finalize function %s\n", it->m_name.c_str());
6370 parser->remove_ast();
6372 auto fnCheckWErrors = [&retval]() {
6373 if (compile_Werrors) {
6374 con_out("*** there were warnings treated as errors\n");
6375 compile_show_werrors();
6383 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6386 if (!ir->generate(output)) {
6387 con_out("*** failed to generate output file\n");
6392 // ir->generate can generate compiler warnings