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 /* was a function call */
1192 ast_expression *fun;
1193 ast_value *funval = nullptr;
1197 size_t paramcount, i;
1200 fid = sy->ops.back().off;
1203 /* out[fid] is the function
1204 * everything above is parameters...
1206 if (sy->argc.empty()) {
1207 parseerror(parser, "internal error: no argument counter available");
1211 paramcount = sy->argc.back();
1212 sy->argc.pop_back();
1214 if (sy->out.size() < fid) {
1215 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1223 * TODO handle this at the intrinsic level with an ast_intrinsic
1226 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1228 if (fid+2 != sy->out.size() || sy->out.back().block) {
1229 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1232 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1233 ast_unref(sy->out.back().out);
1234 sy->out[fid] = syexp(sy->out.back().out->m_context,
1235 parser->m_fold.constgen_string(ty, false));
1241 * Now we need to determine if the function that is being called is
1242 * an intrinsic so we can evaluate if the arguments to it are constant
1243 * and than fruitfully fold them.
1245 #define fold_can_1(X) \
1246 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1247 ((X))->m_vtype != TYPE_FUNCTION)
1249 if (fid + 1 < sy->out.size())
1252 for (i = 0; i < paramcount; ++i) {
1253 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1260 * All is well which ends well, if we make it into here we can ignore the
1261 * intrinsic call and just evaluate it i.e constant fold it.
1263 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1264 std::vector<ast_expression*> exprs;
1265 ast_expression *foldval = nullptr;
1267 exprs.reserve(paramcount);
1268 for (i = 0; i < paramcount; i++)
1269 exprs.push_back(sy->out[fid+1 + i].out);
1271 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs.data()))) {
1276 * Blub: what sorts of unreffing and resizing of
1277 * sy->out should I be doing here?
1279 sy->out[fid] = syexp(foldval->m_context, foldval);
1280 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1286 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1291 if (fid+1 + paramcount != sy->out.size()) {
1292 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1299 for (i = 0; i < paramcount; ++i)
1300 call->m_params.push_back(sy->out[fid+1 + i].out);
1301 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1302 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1303 if (parser->max_param_count < paramcount)
1304 parser->max_param_count = paramcount;
1306 if (ast_istype(fun, ast_value)) {
1307 funval = (ast_value*)fun;
1308 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1309 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1311 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1315 /* overwrite fid, the function, with a call */
1316 sy->out[fid] = syexp(call->m_context, call);
1318 if (fun->m_vtype != TYPE_FUNCTION) {
1319 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1324 parseerror(parser, "could not determine function return type");
1327 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1329 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1331 return !parsewarning(parser, WARN_DEPRECATED,
1332 "call to function (which is marked deprecated)\n",
1333 "-> it has been declared here: %s:%i",
1334 fun->m_context.file, fun->m_context.line);
1336 if (!fval->m_desc.length()) {
1337 return !parsewarning(parser, WARN_DEPRECATED,
1338 "call to `%s` (which is marked deprecated)\n"
1339 "-> `%s` declared here: %s:%i",
1340 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1342 return !parsewarning(parser, WARN_DEPRECATED,
1343 "call to `%s` (deprecated: %s)\n"
1344 "-> `%s` declared here: %s:%i",
1345 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1346 fun->m_context.line);
1349 if (fun->m_type_params.size() != paramcount &&
1350 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1351 fun->m_type_params.size() < paramcount))
1353 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1355 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1356 "too %s parameters for call to %s: expected %i, got %i\n"
1357 " -> `%s` has been declared here: %s:%i",
1358 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1359 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1361 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1362 "too %s parameters for function call: expected %i, got %i\n"
1363 " -> it has been declared here: %s:%i",
1364 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1365 fun->m_context.file, (int)fun->m_context.line);
1372 static bool parser_close_paren(parser_t *parser, shunt *sy)
1374 if (sy->ops.empty()) {
1375 parseerror(parser, "unmatched closing paren");
1379 while (sy->ops.size()) {
1380 if (sy->ops.back().isparen) {
1381 if (sy->paren.back() == PAREN_FUNC) {
1382 sy->paren.pop_back();
1383 if (!parser_close_call(parser, sy))
1387 if (sy->paren.back() == PAREN_EXPR) {
1388 sy->paren.pop_back();
1389 if (sy->out.empty()) {
1390 compile_error(sy->ops.back().ctx, "empty paren expression");
1397 if (sy->paren.back() == PAREN_INDEX) {
1398 sy->paren.pop_back();
1399 // pop off the parenthesis
1401 /* then apply the index operator */
1402 if (!parser_sy_apply_operator(parser, sy))
1406 if (sy->paren.back() == PAREN_TERNARY1) {
1407 sy->paren.back() = PAREN_TERNARY2;
1408 // pop off the parenthesis
1412 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1415 if (!parser_sy_apply_operator(parser, sy))
1421 static void parser_reclassify_token(parser_t *parser)
1424 if (parser->tok >= TOKEN_START)
1426 for (i = 0; i < operator_count; ++i) {
1427 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1428 parser->tok = TOKEN_OPERATOR;
1434 static ast_expression* parse_vararg_do(parser_t *parser)
1436 ast_expression *idx, *out;
1438 ast_value *funtype = parser->function->m_function_type;
1439 lex_ctx_t ctx = parser_ctx(parser);
1441 if (!parser->function->m_varargs) {
1442 parseerror(parser, "function has no variable argument list");
1446 if (!parser_next(parser) || parser->tok != '(') {
1447 parseerror(parser, "expected parameter index and type in parenthesis");
1450 if (!parser_next(parser)) {
1451 parseerror(parser, "error parsing parameter index");
1455 idx = parse_expression_leave(parser, true, false, false);
1459 if (parser->tok != ',') {
1460 if (parser->tok != ')') {
1462 parseerror(parser, "expected comma after parameter index");
1465 // vararg piping: ...(start)
1466 out = new ast_argpipe(ctx, idx);
1470 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1472 parseerror(parser, "expected typename for vararg");
1476 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1482 if (parser->tok != ')') {
1485 parseerror(parser, "expected closing paren");
1489 if (funtype->m_varparam &&
1490 !typevar->compareType(*funtype->m_varparam))
1494 ast_type_to_string(typevar, ty1, sizeof(ty1));
1495 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1496 compile_error(typevar->m_context,
1497 "function was declared to take varargs of type `%s`, requested type is: %s",
1501 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1502 out->adoptType(*typevar);
1507 static ast_expression* parse_vararg(parser_t *parser)
1509 bool old_noops = parser->lex->flags.noops;
1511 ast_expression *out;
1513 parser->lex->flags.noops = true;
1514 out = parse_vararg_do(parser);
1516 parser->lex->flags.noops = old_noops;
1520 /* not to be exposed */
1521 bool ftepp_predef_exists(const char *name);
1522 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1524 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1525 parser->tok == TOKEN_IDENT &&
1526 !strcmp(parser_tokval(parser), "_"))
1528 /* a translatable string */
1531 parser->lex->flags.noops = true;
1532 if (!parser_next(parser) || parser->tok != '(') {
1533 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1536 parser->lex->flags.noops = false;
1537 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1538 parseerror(parser, "expected a constant string in translatable-string extension");
1541 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1544 sy->out.push_back(syexp(parser_ctx(parser), val));
1546 if (!parser_next(parser) || parser->tok != ')') {
1547 parseerror(parser, "expected closing paren after translatable string");
1552 else if (parser->tok == TOKEN_DOTS)
1555 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1556 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1559 va = parse_vararg(parser);
1562 sy->out.push_back(syexp(parser_ctx(parser), va));
1565 else if (parser->tok == TOKEN_FLOATCONST) {
1566 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1569 sy->out.push_back(syexp(parser_ctx(parser), val));
1572 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1573 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1576 sy->out.push_back(syexp(parser_ctx(parser), val));
1579 else if (parser->tok == TOKEN_STRINGCONST) {
1580 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1583 sy->out.push_back(syexp(parser_ctx(parser), val));
1586 else if (parser->tok == TOKEN_VECTORCONST) {
1587 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1590 sy->out.push_back(syexp(parser_ctx(parser), val));
1593 else if (parser->tok == TOKEN_IDENT)
1595 const char *ctoken = parser_tokval(parser);
1596 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1597 ast_expression *var;
1598 /* a_vector.{x,y,z} */
1599 if (sy->ops.empty() ||
1600 !sy->ops.back().etype ||
1601 operators[sy->ops.back().etype-1].id != opid1('.'))
1603 /* When adding more intrinsics, fix the above condition */
1606 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1608 var = parser->const_vec[ctoken[0]-'x'];
1610 var = parser_find_var(parser, parser_tokval(parser));
1612 var = parser_find_field(parser, parser_tokval(parser));
1614 if (!var && with_labels) {
1615 var = parser_find_label(parser, parser_tokval(parser));
1617 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1619 parser->labels.push_back(lbl);
1622 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1623 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1626 * now we try for the real intrinsic hashtable. If the string
1627 * begins with __builtin, we simply skip past it, otherwise we
1628 * use the identifier as is.
1630 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1631 var = parser->m_intrin.func(parser_tokval(parser));
1635 * Try it again, intrin_func deals with the alias method as well
1636 * the first one masks for __builtin though, we emit warning here.
1639 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1640 (void)!compile_warning(
1643 "using implicitly defined builtin `__builtin_%s' for `%s'",
1644 parser_tokval(parser),
1645 parser_tokval(parser)
1653 * sometimes people use preprocessing predefs without enabling them
1654 * i've done this thousands of times already myself. Lets check for
1655 * it in the predef table. And diagnose it better :)
1657 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1658 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1662 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1668 // promote these to norefs
1669 if (ast_istype(var, ast_value))
1671 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1673 else if (ast_istype(var, ast_member))
1675 ast_member *mem = (ast_member *)var;
1676 if (ast_istype(mem->m_owner, ast_value))
1677 ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1680 sy->out.push_back(syexp(parser_ctx(parser), var));
1683 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1687 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1689 ast_expression *expr = nullptr;
1691 bool wantop = false;
1692 /* only warn once about an assignment in a truth value because the current code
1693 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1695 bool warn_parenthesis = true;
1697 /* count the parens because an if starts with one, so the
1698 * end of a condition is an unmatched closing paren
1702 memset(&sy, 0, sizeof(sy));
1704 parser->lex->flags.noops = false;
1706 parser_reclassify_token(parser);
1710 if (parser->tok == TOKEN_TYPENAME) {
1711 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1715 if (parser->tok == TOKEN_OPERATOR)
1717 /* classify the operator */
1718 const oper_info *op;
1719 const oper_info *olast = nullptr;
1721 for (o = 0; o < operator_count; ++o) {
1722 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1723 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1724 !strcmp(parser_tokval(parser), operators[o].op))
1729 if (o == operator_count) {
1730 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1733 /* found an operator */
1736 /* when declaring variables, a comma starts a new variable */
1737 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1738 /* fixup the token */
1743 /* a colon without a pervious question mark cannot be a ternary */
1744 if (!ternaries && op->id == opid2(':','?')) {
1749 if (op->id == opid1(',')) {
1750 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1751 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1755 if (sy.ops.size() && !sy.ops.back().isparen)
1756 olast = &operators[sy.ops.back().etype-1];
1758 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1759 while (olast && op->prec < olast->prec)
1761 if (!parser_sy_apply_operator(parser, &sy))
1763 if (sy.ops.size() && !sy.ops.back().isparen)
1764 olast = &operators[sy.ops.back().etype-1];
1769 #define IsAssignOp(x) (\
1770 (x) == opid1('=') || \
1771 (x) == opid2('+','=') || \
1772 (x) == opid2('-','=') || \
1773 (x) == opid2('*','=') || \
1774 (x) == opid2('/','=') || \
1775 (x) == opid2('%','=') || \
1776 (x) == opid2('&','=') || \
1777 (x) == opid2('|','=') || \
1778 (x) == opid3('&','~','=') \
1780 if (warn_parenthesis) {
1781 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1782 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1783 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1786 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1787 warn_parenthesis = false;
1790 if (olast && olast->id != op->id) {
1791 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1792 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1794 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1795 warn_parenthesis = false;
1797 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1798 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1800 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1801 warn_parenthesis = false;
1807 (op->prec < olast->prec) ||
1808 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1810 if (!parser_sy_apply_operator(parser, &sy))
1812 if (sy.ops.size() && !sy.ops.back().isparen)
1813 olast = &operators[sy.ops.back().etype-1];
1818 if (op->id == opid1('(')) {
1820 size_t sycount = sy.out.size();
1821 /* we expected an operator, this is the function-call operator */
1822 sy.paren.push_back(PAREN_FUNC);
1823 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1824 sy.argc.push_back(0);
1826 sy.paren.push_back(PAREN_EXPR);
1827 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1830 } else if (op->id == opid1('[')) {
1832 parseerror(parser, "unexpected array subscript");
1835 sy.paren.push_back(PAREN_INDEX);
1836 /* push both the operator and the paren, this makes life easier */
1837 sy.ops.push_back(syop(parser_ctx(parser), op));
1838 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1840 } else if (op->id == opid2('?',':')) {
1841 sy.ops.push_back(syop(parser_ctx(parser), op));
1842 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1845 sy.paren.push_back(PAREN_TERNARY1);
1846 } else if (op->id == opid2(':','?')) {
1847 if (sy.paren.empty()) {
1848 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1851 if (sy.paren.back() != PAREN_TERNARY1) {
1852 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1855 if (!parser_close_paren(parser, &sy))
1857 sy.ops.push_back(syop(parser_ctx(parser), op));
1861 sy.ops.push_back(syop(parser_ctx(parser), op));
1862 wantop = !!(op->flags & OP_SUFFIX);
1865 else if (parser->tok == ')') {
1866 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1867 if (!parser_sy_apply_operator(parser, &sy))
1870 if (sy.paren.empty())
1873 if (sy.paren.back() == PAREN_TERNARY1) {
1874 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1877 if (!parser_close_paren(parser, &sy))
1880 /* must be a function call without parameters */
1881 if (sy.paren.back() != PAREN_FUNC) {
1882 parseerror(parser, "closing paren in invalid position");
1885 if (!parser_close_paren(parser, &sy))
1890 else if (parser->tok == '(') {
1891 parseerror(parser, "internal error: '(' should be classified as operator");
1894 else if (parser->tok == '[') {
1895 parseerror(parser, "internal error: '[' should be classified as operator");
1898 else if (parser->tok == ']') {
1899 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1900 if (!parser_sy_apply_operator(parser, &sy))
1903 if (sy.paren.empty())
1905 if (sy.paren.back() != PAREN_INDEX) {
1906 parseerror(parser, "mismatched parentheses, unexpected ']'");
1909 if (!parser_close_paren(parser, &sy))
1914 if (!parse_sya_operand(parser, &sy, with_labels))
1919 /* in this case we might want to allow constant string concatenation */
1920 bool concatenated = false;
1921 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1922 ast_expression *lexpr = sy.out.back().out;
1923 if (ast_istype(lexpr, ast_value)) {
1924 ast_value *last = (ast_value*)lexpr;
1925 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1926 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1928 char *newstr = nullptr;
1929 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1930 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1932 concatenated = true;
1936 if (!concatenated) {
1937 parseerror(parser, "expected operator or end of statement");
1942 if (!parser_next(parser)) {
1945 if (parser->tok == ';' ||
1946 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1947 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1953 while (sy.ops.size()) {
1954 if (!parser_sy_apply_operator(parser, &sy))
1958 parser->lex->flags.noops = true;
1959 if (sy.out.size() != 1) {
1960 parseerror(parser, "expression expected");
1963 expr = sy.out[0].out;
1964 if (sy.paren.size()) {
1965 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1971 parser->lex->flags.noops = true;
1972 for (auto &it : sy.out)
1973 if (it.out) ast_unref(it.out);
1977 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1979 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1982 if (parser->tok != ';') {
1983 parseerror(parser, "semicolon expected after expression");
1987 if (!parser_next(parser)) {
1994 static void parser_enterblock(parser_t *parser)
1996 parser->variables.push_back(util_htnew(PARSER_HT_SIZE));
1997 parser->_blocklocals.push_back(parser->_locals.size());
1998 parser->typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
1999 parser->_blocktypedefs.push_back(parser->_typedefs.size());
2000 parser->_block_ctx.push_back(parser_ctx(parser));
2003 static bool parser_leaveblock(parser_t *parser)
2006 size_t locals, typedefs;
2008 if (parser->variables.size() <= PARSER_HT_LOCALS) {
2009 parseerror(parser, "internal error: parser_leaveblock with no block");
2013 util_htdel(parser->variables.back());
2015 parser->variables.pop_back();
2016 if (!parser->_blocklocals.size()) {
2017 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2021 locals = parser->_blocklocals.back();
2022 parser->_blocklocals.pop_back();
2023 parser->_locals.resize(locals);
2025 typedefs = parser->_blocktypedefs.back();
2026 parser->_typedefs.resize(typedefs);
2027 util_htdel(parser->typedefs.back());
2028 parser->typedefs.pop_back();
2030 parser->_block_ctx.pop_back();
2035 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2037 parser->_locals.push_back(e);
2038 util_htset(parser->variables.back(), name, (void*)e);
2040 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2041 return parser_addlocal(parser, name.c_str(), e);
2044 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2046 parser->globals.push_back(e);
2047 util_htset(parser->htglobals, name, e);
2049 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2050 return parser_addglobal(parser, name.c_str(), e);
2053 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2057 ast_expression *prev;
2059 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2061 ast_type_to_string(cond, ty, sizeof(ty));
2062 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2065 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2068 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2071 parseerror(parser, "internal error: failed to process condition");
2076 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2078 /* vector types need to be cast to true booleans */
2079 ast_binary *bin = (ast_binary*)cond;
2080 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2082 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2084 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2087 parseerror(parser, "internal error: failed to process condition");
2094 unary = (ast_unary*)cond;
2095 /* ast_istype dereferences cond, should test here for safety */
2096 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2098 cond = unary->m_operand;
2099 unary->m_operand = nullptr;
2102 unary = (ast_unary*)cond;
2106 parseerror(parser, "internal error: failed to process condition");
2108 if (ifnot) *_ifnot = !*_ifnot;
2112 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2115 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2118 lex_ctx_t ctx = parser_ctx(parser);
2120 (void)block; /* not touching */
2122 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2123 if (!parser_next(parser)) {
2124 parseerror(parser, "expected condition or 'not'");
2127 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2129 if (!parser_next(parser)) {
2130 parseerror(parser, "expected condition in parenthesis");
2134 if (parser->tok != '(') {
2135 parseerror(parser, "expected 'if' condition in parenthesis");
2138 /* parse into the expression */
2139 if (!parser_next(parser)) {
2140 parseerror(parser, "expected 'if' condition after opening paren");
2143 /* parse the condition */
2144 cond = parse_expression_leave(parser, false, true, false);
2148 if (parser->tok != ')') {
2149 parseerror(parser, "expected closing paren after 'if' condition");
2153 /* parse into the 'then' branch */
2154 if (!parser_next(parser)) {
2155 parseerror(parser, "expected statement for on-true branch of 'if'");
2159 if (!parse_statement_or_block(parser, &ontrue)) {
2164 ontrue = new ast_block(parser_ctx(parser));
2165 /* check for an else */
2166 if (!strcmp(parser_tokval(parser), "else")) {
2167 /* parse into the 'else' branch */
2168 if (!parser_next(parser)) {
2169 parseerror(parser, "expected on-false branch after 'else'");
2174 if (!parse_statement_or_block(parser, &onfalse)) {
2181 cond = process_condition(parser, cond, &ifnot);
2183 if (ontrue) delete ontrue;
2184 if (onfalse) delete onfalse;
2189 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2191 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2196 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2197 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2200 char *label = nullptr;
2202 /* skip the 'while' and get the body */
2203 if (!parser_next(parser)) {
2204 if (OPTS_FLAG(LOOP_LABELS))
2205 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2207 parseerror(parser, "expected 'while' condition in parenthesis");
2211 if (parser->tok == ':') {
2212 if (!OPTS_FLAG(LOOP_LABELS))
2213 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2214 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2215 parseerror(parser, "expected loop label");
2218 label = util_strdup(parser_tokval(parser));
2219 if (!parser_next(parser)) {
2221 parseerror(parser, "expected 'while' condition in parenthesis");
2226 if (parser->tok != '(') {
2227 parseerror(parser, "expected 'while' condition in parenthesis");
2231 parser->breaks.push_back(label);
2232 parser->continues.push_back(label);
2234 rv = parse_while_go(parser, block, out);
2237 if (parser->breaks.back() != label || parser->continues.back() != label) {
2238 parseerror(parser, "internal error: label stack corrupted");
2244 parser->breaks.pop_back();
2245 parser->continues.pop_back();
2250 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2253 ast_expression *cond, *ontrue;
2257 lex_ctx_t ctx = parser_ctx(parser);
2259 (void)block; /* not touching */
2261 /* parse into the expression */
2262 if (!parser_next(parser)) {
2263 parseerror(parser, "expected 'while' condition after opening paren");
2266 /* parse the condition */
2267 cond = parse_expression_leave(parser, false, true, false);
2271 if (parser->tok != ')') {
2272 parseerror(parser, "expected closing paren after 'while' condition");
2276 /* parse into the 'then' branch */
2277 if (!parser_next(parser)) {
2278 parseerror(parser, "expected while-loop body");
2282 if (!parse_statement_or_block(parser, &ontrue)) {
2287 cond = process_condition(parser, cond, &ifnot);
2292 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2297 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2298 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2301 char *label = nullptr;
2303 /* skip the 'do' and get the body */
2304 if (!parser_next(parser)) {
2305 if (OPTS_FLAG(LOOP_LABELS))
2306 parseerror(parser, "expected loop label or body");
2308 parseerror(parser, "expected loop body");
2312 if (parser->tok == ':') {
2313 if (!OPTS_FLAG(LOOP_LABELS))
2314 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2315 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2316 parseerror(parser, "expected loop label");
2319 label = util_strdup(parser_tokval(parser));
2320 if (!parser_next(parser)) {
2322 parseerror(parser, "expected loop body");
2327 parser->breaks.push_back(label);
2328 parser->continues.push_back(label);
2330 rv = parse_dowhile_go(parser, block, out);
2333 if (parser->breaks.back() != label || parser->continues.back() != label) {
2334 parseerror(parser, "internal error: label stack corrupted");
2340 parser->breaks.pop_back();
2341 parser->continues.pop_back();
2346 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2349 ast_expression *cond, *ontrue;
2353 lex_ctx_t ctx = parser_ctx(parser);
2355 (void)block; /* not touching */
2357 if (!parse_statement_or_block(parser, &ontrue))
2360 /* expect the "while" */
2361 if (parser->tok != TOKEN_KEYWORD ||
2362 strcmp(parser_tokval(parser), "while"))
2364 parseerror(parser, "expected 'while' and condition");
2369 /* skip the 'while' and check for opening paren */
2370 if (!parser_next(parser) || parser->tok != '(') {
2371 parseerror(parser, "expected 'while' condition in parenthesis");
2375 /* parse into the expression */
2376 if (!parser_next(parser)) {
2377 parseerror(parser, "expected 'while' condition after opening paren");
2381 /* parse the condition */
2382 cond = parse_expression_leave(parser, false, true, false);
2386 if (parser->tok != ')') {
2387 parseerror(parser, "expected closing paren after 'while' condition");
2393 if (!parser_next(parser) || parser->tok != ';') {
2394 parseerror(parser, "expected semicolon after condition");
2400 if (!parser_next(parser)) {
2401 parseerror(parser, "parse error");
2407 cond = process_condition(parser, cond, &ifnot);
2412 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2417 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2418 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2421 char *label = nullptr;
2423 /* skip the 'for' and check for opening paren */
2424 if (!parser_next(parser)) {
2425 if (OPTS_FLAG(LOOP_LABELS))
2426 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2428 parseerror(parser, "expected 'for' expressions in parenthesis");
2432 if (parser->tok == ':') {
2433 if (!OPTS_FLAG(LOOP_LABELS))
2434 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2435 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2436 parseerror(parser, "expected loop label");
2439 label = util_strdup(parser_tokval(parser));
2440 if (!parser_next(parser)) {
2442 parseerror(parser, "expected 'for' expressions in parenthesis");
2447 if (parser->tok != '(') {
2448 parseerror(parser, "expected 'for' expressions in parenthesis");
2452 parser->breaks.push_back(label);
2453 parser->continues.push_back(label);
2455 rv = parse_for_go(parser, block, out);
2458 if (parser->breaks.back() != label || parser->continues.back() != label) {
2459 parseerror(parser, "internal error: label stack corrupted");
2465 parser->breaks.pop_back();
2466 parser->continues.pop_back();
2470 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2473 ast_expression *initexpr, *cond, *increment, *ontrue;
2478 lex_ctx_t ctx = parser_ctx(parser);
2480 parser_enterblock(parser);
2484 increment = nullptr;
2487 /* parse into the expression */
2488 if (!parser_next(parser)) {
2489 parseerror(parser, "expected 'for' initializer after opening paren");
2494 if (parser->tok == TOKEN_IDENT)
2495 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2497 if (typevar || parser->tok == TOKEN_TYPENAME) {
2498 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2501 else if (parser->tok != ';')
2503 initexpr = parse_expression_leave(parser, false, false, false);
2506 /* move on to condition */
2507 if (parser->tok != ';') {
2508 parseerror(parser, "expected semicolon after for-loop initializer");
2511 if (!parser_next(parser)) {
2512 parseerror(parser, "expected for-loop condition");
2515 } else if (!parser_next(parser)) {
2516 parseerror(parser, "expected for-loop condition");
2520 /* parse the condition */
2521 if (parser->tok != ';') {
2522 cond = parse_expression_leave(parser, false, true, false);
2526 /* move on to incrementor */
2527 if (parser->tok != ';') {
2528 parseerror(parser, "expected semicolon after for-loop initializer");
2531 if (!parser_next(parser)) {
2532 parseerror(parser, "expected for-loop condition");
2536 /* parse the incrementor */
2537 if (parser->tok != ')') {
2538 lex_ctx_t condctx = parser_ctx(parser);
2539 increment = parse_expression_leave(parser, false, false, false);
2542 if (!increment->m_side_effects) {
2543 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2549 if (parser->tok != ')') {
2550 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2553 /* parse into the 'then' branch */
2554 if (!parser_next(parser)) {
2555 parseerror(parser, "expected for-loop body");
2558 if (!parse_statement_or_block(parser, &ontrue))
2562 cond = process_condition(parser, cond, &ifnot);
2566 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2569 if (!parser_leaveblock(parser)) {
2575 if (initexpr) ast_unref(initexpr);
2576 if (cond) ast_unref(cond);
2577 if (increment) ast_unref(increment);
2578 (void)!parser_leaveblock(parser);
2582 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2584 ast_expression *exp = nullptr;
2585 ast_expression *var = nullptr;
2586 ast_return *ret = nullptr;
2587 ast_value *retval = parser->function->m_return_value;
2588 ast_value *expected = parser->function->m_function_type;
2590 lex_ctx_t ctx = parser_ctx(parser);
2592 (void)block; /* not touching */
2594 if (!parser_next(parser)) {
2595 parseerror(parser, "expected return expression");
2599 /* return assignments */
2600 if (parser->tok == '=') {
2601 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2602 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2606 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2608 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2609 parseerror(parser, "invalid return type: `%s'", ty1);
2613 if (!parser_next(parser)) {
2614 parseerror(parser, "expected return assignment expression");
2618 if (!(exp = parse_expression_leave(parser, false, false, false)))
2621 /* prepare the return value */
2623 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2624 retval->adoptType(*expected->m_next);
2625 parser->function->m_return_value = retval;
2626 parser->function->m_return_value->m_flags |= AST_FLAG_NOREF;
2629 if (!exp->compareType(*retval)) {
2630 char ty1[1024], ty2[1024];
2631 ast_type_to_string(exp, ty1, sizeof(ty1));
2632 ast_type_to_string(retval, ty2, sizeof(ty2));
2633 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2636 /* store to 'return' local variable */
2637 var = new ast_store(
2639 type_store_instr[expected->m_next->m_vtype],
2647 if (parser->tok != ';')
2648 parseerror(parser, "missing semicolon after return assignment");
2649 else if (!parser_next(parser))
2650 parseerror(parser, "parse error after return assignment");
2656 if (parser->tok != ';') {
2657 exp = parse_expression(parser, false, false);
2661 if (exp->m_vtype != TYPE_NIL &&
2662 exp->m_vtype != (expected)->m_next->m_vtype)
2664 parseerror(parser, "return with invalid expression");
2667 ret = new ast_return(ctx, exp);
2673 if (!parser_next(parser))
2674 parseerror(parser, "parse error");
2676 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2678 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2680 ret = new ast_return(ctx, retval);
2686 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2689 unsigned int levels = 0;
2690 lex_ctx_t ctx = parser_ctx(parser);
2691 auto &loops = (is_continue ? parser->continues : parser->breaks);
2693 (void)block; /* not touching */
2694 if (!parser_next(parser)) {
2695 parseerror(parser, "expected semicolon or loop label");
2699 if (loops.empty()) {
2701 parseerror(parser, "`continue` can only be used inside loops");
2703 parseerror(parser, "`break` can only be used inside loops or switches");
2706 if (parser->tok == TOKEN_IDENT) {
2707 if (!OPTS_FLAG(LOOP_LABELS))
2708 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2711 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2714 parseerror(parser, "no such loop to %s: `%s`",
2715 (is_continue ? "continue" : "break out of"),
2716 parser_tokval(parser));
2721 if (!parser_next(parser)) {
2722 parseerror(parser, "expected semicolon");
2727 if (parser->tok != ';') {
2728 parseerror(parser, "expected semicolon");
2732 if (!parser_next(parser))
2733 parseerror(parser, "parse error");
2735 *out = new ast_breakcont(ctx, is_continue, levels);
2739 /* returns true when it was a variable qualifier, false otherwise!
2740 * on error, cvq is set to CV_WRONG
2742 struct attribute_t {
2747 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2749 bool had_const = false;
2750 bool had_var = false;
2751 bool had_noref = false;
2752 bool had_attrib = false;
2753 bool had_static = false;
2756 static attribute_t attributes[] = {
2757 { "noreturn", AST_FLAG_NORETURN },
2758 { "inline", AST_FLAG_INLINE },
2759 { "eraseable", AST_FLAG_ERASEABLE },
2760 { "accumulate", AST_FLAG_ACCUMULATE },
2761 { "last", AST_FLAG_FINAL_DECL }
2768 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2770 /* parse an attribute */
2771 if (!parser_next(parser)) {
2772 parseerror(parser, "expected attribute after `[[`");
2777 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2778 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2779 flags |= attributes[i].flag;
2780 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2781 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2782 attributes[i].name);
2790 if (i != GMQCC_ARRAY_COUNT(attributes))
2794 if (!strcmp(parser_tokval(parser), "noref")) {
2796 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2797 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2802 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2803 flags |= AST_FLAG_ALIAS;
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "parse error in attribute");
2811 if (parser->tok == '(') {
2812 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2813 parseerror(parser, "`alias` attribute missing parameter");
2817 *message = util_strdup(parser_tokval(parser));
2819 if (!parser_next(parser)) {
2820 parseerror(parser, "parse error in attribute");
2824 if (parser->tok != ')') {
2825 parseerror(parser, "`alias` attribute expected `)` after parameter");
2829 if (!parser_next(parser)) {
2830 parseerror(parser, "parse error in attribute");
2835 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2836 parseerror(parser, "`alias` attribute expected `]]`");
2840 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2841 flags |= AST_FLAG_DEPRECATED;
2844 if (!parser_next(parser)) {
2845 parseerror(parser, "parse error in attribute");
2849 if (parser->tok == '(') {
2850 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2851 parseerror(parser, "`deprecated` attribute missing parameter");
2855 *message = util_strdup(parser_tokval(parser));
2857 if (!parser_next(parser)) {
2858 parseerror(parser, "parse error in attribute");
2862 if(parser->tok != ')') {
2863 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2867 if (!parser_next(parser)) {
2868 parseerror(parser, "parse error in attribute");
2873 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2874 parseerror(parser, "`deprecated` attribute expected `]]`");
2877 if (*message) mem_d(*message);
2883 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2884 flags |= AST_FLAG_COVERAGE;
2885 if (!parser_next(parser)) {
2887 parseerror(parser, "parse error in coverage attribute");
2891 if (parser->tok == '(') {
2892 if (!parser_next(parser)) {
2894 parseerror(parser, "invalid parameter for coverage() attribute\n"
2895 "valid are: block");
2899 if (parser->tok != ')') {
2901 if (parser->tok != TOKEN_IDENT)
2902 goto bad_coverage_arg;
2903 if (!strcmp(parser_tokval(parser), "block"))
2904 flags |= AST_FLAG_BLOCK_COVERAGE;
2905 else if (!strcmp(parser_tokval(parser), "none"))
2906 flags &= ~(AST_FLAG_COVERAGE_MASK);
2908 goto bad_coverage_arg;
2909 if (!parser_next(parser))
2910 goto error_in_coverage;
2911 if (parser->tok == ',') {
2912 if (!parser_next(parser))
2913 goto error_in_coverage;
2915 } while (parser->tok != ')');
2917 if (parser->tok != ')' || !parser_next(parser))
2918 goto error_in_coverage;
2920 /* without parameter [[coverage]] equals [[coverage(block)]] */
2921 flags |= AST_FLAG_BLOCK_COVERAGE;
2926 /* Skip tokens until we hit a ]] */
2927 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2928 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2929 if (!parser_next(parser)) {
2930 parseerror(parser, "error inside attribute");
2937 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2939 else if (!strcmp(parser_tokval(parser), "const"))
2941 else if (!strcmp(parser_tokval(parser), "var"))
2943 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2945 else if (!strcmp(parser_tokval(parser), "noref"))
2947 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2954 if (!parser_next(parser))
2964 *is_static = had_static;
2968 parseerror(parser, "parse error after variable qualifier");
2973 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2974 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2977 char *label = nullptr;
2979 /* skip the 'while' and get the body */
2980 if (!parser_next(parser)) {
2981 if (OPTS_FLAG(LOOP_LABELS))
2982 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2984 parseerror(parser, "expected 'switch' operand in parenthesis");
2988 if (parser->tok == ':') {
2989 if (!OPTS_FLAG(LOOP_LABELS))
2990 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2991 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2992 parseerror(parser, "expected loop label");
2995 label = util_strdup(parser_tokval(parser));
2996 if (!parser_next(parser)) {
2998 parseerror(parser, "expected 'switch' operand in parenthesis");
3003 if (parser->tok != '(') {
3004 parseerror(parser, "expected 'switch' operand in parenthesis");
3008 parser->breaks.push_back(label);
3010 rv = parse_switch_go(parser, block, out);
3013 if (parser->breaks.back() != label) {
3014 parseerror(parser, "internal error: label stack corrupted");
3020 parser->breaks.pop_back();
3025 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3027 ast_expression *operand;
3030 ast_switch *switchnode;
3031 ast_switch_case swcase;
3034 bool noref, is_static;
3035 uint32_t qflags = 0;
3037 lex_ctx_t ctx = parser_ctx(parser);
3039 (void)block; /* not touching */
3042 /* parse into the expression */
3043 if (!parser_next(parser)) {
3044 parseerror(parser, "expected switch operand");
3047 /* parse the operand */
3048 operand = parse_expression_leave(parser, false, false, false);
3052 switchnode = new ast_switch(ctx, operand);
3055 if (parser->tok != ')') {
3057 parseerror(parser, "expected closing paren after 'switch' operand");
3061 /* parse over the opening paren */
3062 if (!parser_next(parser) || parser->tok != '{') {
3064 parseerror(parser, "expected list of cases");
3068 if (!parser_next(parser)) {
3070 parseerror(parser, "expected 'case' or 'default'");
3074 /* new block; allow some variables to be declared here */
3075 parser_enterblock(parser);
3078 if (parser->tok == TOKEN_IDENT)
3079 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3080 if (typevar || parser->tok == TOKEN_TYPENAME) {
3081 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3087 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3089 if (cvq == CV_WRONG) {
3093 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3103 while (parser->tok != '}') {
3104 ast_block *caseblock;
3106 if (!strcmp(parser_tokval(parser), "case")) {
3107 if (!parser_next(parser)) {
3109 parseerror(parser, "expected expression for case");
3112 swcase.m_value = parse_expression_leave(parser, false, false, false);
3114 if (!operand->compareType(*swcase.m_value)) {
3118 ast_type_to_string(swcase.m_value, ty1, sizeof ty1);
3119 ast_type_to_string(operand, ty2, sizeof ty2);
3121 auto fnLiteral = [](ast_expression *expression) -> char* {
3122 if (!ast_istype(expression, ast_value))
3124 ast_value *value = (ast_value *)expression;
3125 if (!value->m_hasvalue)
3127 char *string = nullptr;
3128 basic_value_t *constval = &value->m_constval;
3129 switch (value->m_vtype)
3132 util_asprintf(&string, "%.2f", constval->vfloat);
3135 util_asprintf(&string, "'%.2f %.2f %.2f'",
3141 util_asprintf(&string, "\"%s\"", constval->vstring);
3149 char *literal = fnLiteral(swcase.m_value);
3151 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case `%s` expected `%s`", ty1, literal, ty2);
3153 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case expected `%s`", ty1, ty2);
3159 if (!swcase.m_value) {
3161 parseerror(parser, "expected expression for case");
3164 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3165 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3167 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3173 else if (!strcmp(parser_tokval(parser), "default")) {
3174 swcase.m_value = nullptr;
3175 if (!parser_next(parser)) {
3177 parseerror(parser, "expected colon");
3183 parseerror(parser, "expected 'case' or 'default'");
3187 /* Now the colon and body */
3188 if (parser->tok != ':') {
3189 if (swcase.m_value) ast_unref(swcase.m_value);
3191 parseerror(parser, "expected colon");
3195 if (!parser_next(parser)) {
3196 if (swcase.m_value) ast_unref(swcase.m_value);
3198 parseerror(parser, "expected statements or case");
3201 caseblock = new ast_block(parser_ctx(parser));
3203 if (swcase.m_value) ast_unref(swcase.m_value);
3207 swcase.m_code = caseblock;
3208 switchnode->m_cases.push_back(swcase);
3210 ast_expression *expr;
3211 if (parser->tok == '}')
3213 if (parser->tok == TOKEN_KEYWORD) {
3214 if (!strcmp(parser_tokval(parser), "case") ||
3215 !strcmp(parser_tokval(parser), "default"))
3220 if (!parse_statement(parser, caseblock, &expr, true)) {
3226 if (!caseblock->addExpr(expr)) {
3233 parser_leaveblock(parser);
3236 if (parser->tok != '}') {
3238 parseerror(parser, "expected closing paren of case list");
3241 if (!parser_next(parser)) {
3243 parseerror(parser, "parse error after switch");
3250 /* parse computed goto sides */
3251 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3252 ast_expression *on_true;
3253 ast_expression *on_false;
3254 ast_expression *cond;
3259 if (ast_istype(*side, ast_ternary)) {
3260 ast_ternary *tern = (ast_ternary*)*side;
3261 on_true = parse_goto_computed(parser, &tern->m_on_true);
3262 on_false = parse_goto_computed(parser, &tern->m_on_false);
3264 if (!on_true || !on_false) {
3265 parseerror(parser, "expected label or expression in ternary");
3266 if (on_true) ast_unref(on_true);
3267 if (on_false) ast_unref(on_false);
3271 cond = tern->m_cond;
3272 tern->m_cond = nullptr;
3275 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3276 } else if (ast_istype(*side, ast_label)) {
3277 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3278 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3285 static bool parse_goto(parser_t *parser, ast_expression **out)
3287 ast_goto *gt = nullptr;
3288 ast_expression *lbl;
3290 if (!parser_next(parser))
3293 if (parser->tok != TOKEN_IDENT) {
3294 ast_expression *expression;
3296 /* could be an expression i.e computed goto :-) */
3297 if (parser->tok != '(') {
3298 parseerror(parser, "expected label name after `goto`");
3302 /* failed to parse expression for goto */
3303 if (!(expression = parse_expression(parser, false, true)) ||
3304 !(*out = parse_goto_computed(parser, &expression))) {
3305 parseerror(parser, "invalid goto expression");
3307 ast_unref(expression);
3314 /* not computed goto */
3315 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3316 lbl = parser_find_label(parser, gt->m_name);
3318 if (!ast_istype(lbl, ast_label)) {
3319 parseerror(parser, "internal error: label is not an ast_label");
3323 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3326 parser->gotos.push_back(gt);
3328 if (!parser_next(parser) || parser->tok != ';') {
3329 parseerror(parser, "semicolon expected after goto label");
3332 if (!parser_next(parser)) {
3333 parseerror(parser, "parse error after goto");
3341 static bool parse_skipwhite(parser_t *parser)
3344 if (!parser_next(parser))
3346 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3347 return parser->tok < TOKEN_ERROR;
3350 static bool parse_eol(parser_t *parser)
3352 if (!parse_skipwhite(parser))
3354 return parser->tok == TOKEN_EOL;
3357 static bool parse_pragma_do(parser_t *parser)
3359 if (!parser_next(parser) ||
3360 parser->tok != TOKEN_IDENT ||
3361 strcmp(parser_tokval(parser), "pragma"))
3363 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3366 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3367 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3371 if (!strcmp(parser_tokval(parser), "noref")) {
3372 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3373 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3376 parser->noref = !!parser_token(parser)->constval.i;
3377 if (!parse_eol(parser)) {
3378 parseerror(parser, "parse error after `noref` pragma");
3384 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3387 while (!parse_eol(parser)) {
3388 parser_next(parser);
3397 static bool parse_pragma(parser_t *parser)
3400 parser->lex->flags.preprocessing = true;
3401 parser->lex->flags.mergelines = true;
3402 rv = parse_pragma_do(parser);
3403 if (parser->tok != TOKEN_EOL) {
3404 parseerror(parser, "junk after pragma");
3407 parser->lex->flags.preprocessing = false;
3408 parser->lex->flags.mergelines = false;
3409 if (!parser_next(parser)) {
3410 parseerror(parser, "parse error after pragma");
3416 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3418 bool noref, is_static;
3420 uint32_t qflags = 0;
3421 ast_value *typevar = nullptr;
3422 char *vstring = nullptr;
3426 if (parser->tok == TOKEN_IDENT)
3427 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3429 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3431 /* local variable */
3433 parseerror(parser, "cannot declare a variable from here");
3436 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3437 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3440 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3444 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3446 if (cvq == CV_WRONG)
3448 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3450 else if (parser->tok == TOKEN_KEYWORD)
3452 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3457 if (!parser_next(parser)) {
3458 parseerror(parser, "parse error after __builtin_debug_printtype");
3462 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3464 ast_type_to_string(tdef, ty, sizeof(ty));
3465 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3466 if (!parser_next(parser)) {
3467 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3473 if (!parse_statement(parser, block, out, allow_cases))
3476 con_out("__builtin_debug_printtype: got no output node\n");
3479 ast_type_to_string(*out, ty, sizeof(ty));
3480 con_out("__builtin_debug_printtype: `%s`\n", ty);
3485 else if (!strcmp(parser_tokval(parser), "return"))
3487 return parse_return(parser, block, out);
3489 else if (!strcmp(parser_tokval(parser), "if"))
3491 return parse_if(parser, block, out);
3493 else if (!strcmp(parser_tokval(parser), "while"))
3495 return parse_while(parser, block, out);
3497 else if (!strcmp(parser_tokval(parser), "do"))
3499 return parse_dowhile(parser, block, out);
3501 else if (!strcmp(parser_tokval(parser), "for"))
3503 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3504 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3507 return parse_for(parser, block, out);
3509 else if (!strcmp(parser_tokval(parser), "break"))
3511 return parse_break_continue(parser, block, out, false);
3513 else if (!strcmp(parser_tokval(parser), "continue"))
3515 return parse_break_continue(parser, block, out, true);
3517 else if (!strcmp(parser_tokval(parser), "switch"))
3519 return parse_switch(parser, block, out);
3521 else if (!strcmp(parser_tokval(parser), "case") ||
3522 !strcmp(parser_tokval(parser), "default"))
3525 parseerror(parser, "unexpected 'case' label");
3530 else if (!strcmp(parser_tokval(parser), "goto"))
3532 return parse_goto(parser, out);
3534 else if (!strcmp(parser_tokval(parser), "typedef"))
3536 if (!parser_next(parser)) {
3537 parseerror(parser, "expected type definition after 'typedef'");
3540 return parse_typedef(parser);
3542 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3545 else if (parser->tok == '{')
3548 inner = parse_block(parser);
3554 else if (parser->tok == ':')
3558 if (!parser_next(parser)) {
3559 parseerror(parser, "expected label name");
3562 if (parser->tok != TOKEN_IDENT) {
3563 parseerror(parser, "label must be an identifier");
3566 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3568 if (!label->m_undefined) {
3569 parseerror(parser, "label `%s` already defined", label->m_name);
3572 label->m_undefined = false;
3575 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3576 parser->labels.push_back(label);
3579 if (!parser_next(parser)) {
3580 parseerror(parser, "parse error after label");
3583 for (i = 0; i < parser->gotos.size(); ++i) {
3584 if (parser->gotos[i]->m_name == label->m_name) {
3585 parser->gotos[i]->setLabel(label);
3586 parser->gotos.erase(parser->gotos.begin() + i);
3592 else if (parser->tok == ';')
3594 if (!parser_next(parser)) {
3595 parseerror(parser, "parse error after empty statement");
3602 lex_ctx_t ctx = parser_ctx(parser);
3603 ast_expression *exp = parse_expression(parser, false, false);
3607 if (!exp->m_side_effects) {
3608 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3615 static bool parse_enum(parser_t *parser)
3618 bool reverse = false;
3620 ast_value *var = nullptr;
3622 std::vector<ast_value*> values;
3624 ast_expression *old;
3626 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3627 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3631 /* enumeration attributes (can add more later) */
3632 if (parser->tok == ':') {
3633 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3634 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3639 if (!strcmp(parser_tokval(parser), "flag")) {
3643 else if (!strcmp(parser_tokval(parser), "reverse")) {
3647 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3651 if (!parser_next(parser) || parser->tok != '{') {
3652 parseerror(parser, "expected `{` after enum attribute ");
3658 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3659 if (parser->tok == '}') {
3660 /* allow an empty enum */
3663 parseerror(parser, "expected identifier or `}`");
3667 old = parser_find_field(parser, parser_tokval(parser));
3669 old = parser_find_global(parser, parser_tokval(parser));
3671 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3672 parser_tokval(parser), old->m_context.file, old->m_context.line);
3676 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3677 values.push_back(var);
3678 var->m_cvq = CV_CONST;
3679 var->m_hasvalue = true;
3681 /* for flagged enumerations increment in POTs of TWO */
3682 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3683 parser_addglobal(parser, var->m_name, var);
3685 if (!parser_next(parser)) {
3686 parseerror(parser, "expected `=`, `}` or comma after identifier");
3690 if (parser->tok == ',')
3692 if (parser->tok == '}')
3694 if (parser->tok != '=') {
3695 parseerror(parser, "expected `=`, `}` or comma after identifier");
3699 if (!parser_next(parser)) {
3700 parseerror(parser, "expected expression after `=`");
3704 /* We got a value! */
3705 old = parse_expression_leave(parser, true, false, false);
3706 asvalue = (ast_value*)old;
3707 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3708 compile_error(var->m_context, "constant value or expression expected");
3711 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3713 if (parser->tok == '}')
3715 if (parser->tok != ',') {
3716 parseerror(parser, "expected `}` or comma after expression");
3721 /* patch them all (for reversed attribute) */
3724 for (i = 0; i < values.size(); i++)
3725 values[i]->m_constval.vfloat = values.size() - i - 1;
3728 if (parser->tok != '}') {
3729 parseerror(parser, "internal error: breaking without `}`");
3733 if (!parser_next(parser) || parser->tok != ';') {
3734 parseerror(parser, "expected semicolon after enumeration");
3738 if (!parser_next(parser)) {
3739 parseerror(parser, "parse error after enumeration");
3746 static bool parse_block_into(parser_t *parser, ast_block *block)
3750 parser_enterblock(parser);
3752 if (!parser_next(parser)) { /* skip the '{' */
3753 parseerror(parser, "expected function body");
3757 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3759 ast_expression *expr = nullptr;
3760 if (parser->tok == '}')
3763 if (!parse_statement(parser, block, &expr, false)) {
3764 /* parseerror(parser, "parse error"); */
3770 if (!block->addExpr(expr)) {
3777 if (parser->tok != '}') {
3780 (void)parser_next(parser);
3784 if (!parser_leaveblock(parser))
3786 return retval && !!block;
3789 static ast_block* parse_block(parser_t *parser)
3792 block = new ast_block(parser_ctx(parser));
3795 if (!parse_block_into(parser, block)) {
3802 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3804 if (parser->tok == '{') {
3805 *out = parse_block(parser);
3808 return parse_statement(parser, nullptr, out, false);
3811 static bool create_vector_members(ast_value *var, ast_member **me)
3814 size_t len = var->m_name.length();
3816 for (i = 0; i < 3; ++i) {
3817 char *name = (char*)mem_a(len+3);
3818 memcpy(name, var->m_name.c_str(), len);
3820 name[len+1] = 'x'+i;
3822 me[i] = ast_member::make(var->m_context, var, i, name);
3831 do { delete me[--i]; } while(i);
3835 static bool parse_function_body(parser_t *parser, ast_value *var)
3837 ast_block *block = nullptr;
3841 ast_expression *framenum = nullptr;
3842 ast_expression *nextthink = nullptr;
3843 /* None of the following have to be deleted */
3844 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3845 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3846 bool has_frame_think;
3850 has_frame_think = false;
3851 old = parser->function;
3853 if (var->m_flags & AST_FLAG_ALIAS) {
3854 parseerror(parser, "function aliases cannot have bodies");
3858 if (parser->gotos.size() || parser->labels.size()) {
3859 parseerror(parser, "gotos/labels leaking");
3863 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3864 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3865 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3871 if (parser->tok == '[') {
3872 /* got a frame definition: [ framenum, nextthink ]
3873 * this translates to:
3874 * self.frame = framenum;
3875 * self.nextthink = time + 0.1;
3876 * self.think = nextthink;
3878 nextthink = nullptr;
3880 fld_think = parser_find_field(parser, "think");
3881 fld_nextthink = parser_find_field(parser, "nextthink");
3882 fld_frame = parser_find_field(parser, "frame");
3883 if (!fld_think || !fld_nextthink || !fld_frame) {
3884 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3885 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3888 gbl_time = parser_find_global(parser, "time");
3889 gbl_self = parser_find_global(parser, "self");
3890 if (!gbl_time || !gbl_self) {
3891 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3892 parseerror(parser, "please declare the following globals: `time`, `self`");
3896 if (!parser_next(parser))
3899 framenum = parse_expression_leave(parser, true, false, false);
3901 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3904 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3905 ast_unref(framenum);
3906 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3910 if (parser->tok != ',') {
3911 ast_unref(framenum);
3912 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3913 parseerror(parser, "Got a %i\n", parser->tok);
3917 if (!parser_next(parser)) {
3918 ast_unref(framenum);
3922 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3924 /* qc allows the use of not-yet-declared functions here
3925 * - this automatically creates a prototype */
3926 ast_value *thinkfunc;
3927 ast_expression *functype = fld_think->m_next;
3929 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3930 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3931 ast_unref(framenum);
3932 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3935 thinkfunc->adoptType(*functype);
3937 if (!parser_next(parser)) {
3938 ast_unref(framenum);
3943 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3945 nextthink = thinkfunc;
3948 nextthink = parse_expression_leave(parser, true, false, false);
3950 ast_unref(framenum);
3951 parseerror(parser, "expected a think-function in [frame,think] notation");
3956 if (!ast_istype(nextthink, ast_value)) {
3957 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3961 if (retval && parser->tok != ']') {
3962 parseerror(parser, "expected closing `]` for [frame,think] notation");
3966 if (retval && !parser_next(parser)) {
3970 if (retval && parser->tok != '{') {
3971 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3976 ast_unref(nextthink);
3977 ast_unref(framenum);
3981 has_frame_think = true;
3984 block = new ast_block(parser_ctx(parser));
3986 parseerror(parser, "failed to allocate block");
3987 if (has_frame_think) {
3988 ast_unref(nextthink);
3989 ast_unref(framenum);
3994 if (has_frame_think) {
3995 if (!OPTS_FLAG(EMULATE_STATE)) {
3996 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
3997 if (!block->addExpr(state_op)) {
3998 parseerror(parser, "failed to generate state op for [frame,think]");
3999 ast_unref(nextthink);
4000 ast_unref(framenum);
4005 /* emulate OP_STATE in code: */
4007 ast_expression *self_frame;
4008 ast_expression *self_nextthink;
4009 ast_expression *self_think;
4010 ast_expression *time_plus_1;
4011 ast_store *store_frame;
4012 ast_store *store_nextthink;
4013 ast_store *store_think;
4015 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4017 ctx = parser_ctx(parser);
4018 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
4019 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4020 self_think = new ast_entfield(ctx, gbl_self, fld_think);
4022 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
4023 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4025 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4026 if (self_frame) delete self_frame;
4027 if (self_nextthink) delete self_nextthink;
4028 if (self_think) delete self_think;
4029 if (time_plus_1) delete time_plus_1;
4035 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4036 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4037 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4043 if (!store_nextthink) {
4044 delete self_nextthink;
4052 if (store_frame) delete store_frame;
4053 if (store_nextthink) delete store_nextthink;
4054 if (store_think) delete store_think;
4057 if (!block->addExpr(store_frame) ||
4058 !block->addExpr(store_nextthink) ||
4059 !block->addExpr(store_think))
4066 parseerror(parser, "failed to generate code for [frame,think]");
4067 ast_unref(nextthink);
4068 ast_unref(framenum);
4075 if (var->m_hasvalue) {
4076 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4077 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4081 func = var->m_constval.vfunc;
4084 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4089 func = ast_function::make(var->m_context, var->m_name, var);
4092 parseerror(parser, "failed to allocate function for `%s`", var->m_name);