9 #define PARSER_HT_LOCALS 2
10 #define PARSER_HT_SIZE 512
11 #define TYPEDEF_HT_SIZE 512
13 static void parser_enterblock(parser_t *parser);
14 static bool parser_leaveblock(parser_t *parser);
15 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
16 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e);
17 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
18 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e);
19 static bool parse_typedef(parser_t *parser);
20 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
21 static ast_block* parse_block(parser_t *parser);
22 static bool parse_block_into(parser_t *parser, ast_block *block);
23 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
24 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
25 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
26 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
27 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
28 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
29 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
31 static void parseerror_(parser_t *parser, const char *fmt, ...)
35 vcompile_error(parser->lex->tok.ctx, fmt, ap);
39 template<typename... Ts>
40 static inline void parseerror(parser_t *parser, const char *fmt, const Ts&... ts) {
41 return parseerror_(parser, fmt, formatNormalize(ts)...);
44 // returns true if it counts as an error
45 static bool GMQCC_WARN parsewarning_(parser_t *parser, int warntype, const char *fmt, ...)
50 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
55 template<typename... Ts>
56 static inline bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, const Ts&... ts) {
57 return parsewarning_(parser, warntype, fmt, formatNormalize(ts)...);
60 /**********************************************************************
64 static bool parser_next(parser_t *parser)
66 /* lex_do kills the previous token */
67 parser->tok = lex_do(parser->lex);
68 if (parser->tok == TOKEN_EOF)
70 if (parser->tok >= TOKEN_ERROR) {
71 parseerror(parser, "lex error");
77 #define parser_tokval(p) ((p)->lex->tok.value)
78 #define parser_token(p) (&((p)->lex->tok))
80 char *parser_strdup(const char *str)
83 /* actually dup empty strings */
84 char *out = (char*)mem_a(1);
88 return util_strdup(str);
91 static ast_expression* parser_find_field(parser_t *parser, const char *name) {
92 return (ast_expression*)util_htget(parser->htfields, name);
94 static ast_expression* parser_find_field(parser_t *parser, const std::string &name) {
95 return parser_find_field(parser, name.c_str());
98 static ast_expression* parser_find_label(parser_t *parser, const char *name)
100 for (auto &it : parser->labels)
101 if (it->m_name == name)
105 static inline ast_expression* parser_find_label(parser_t *parser, const std::string &name) {
106 return parser_find_label(parser, name.c_str());
109 ast_expression* parser_find_global(parser_t *parser, const char *name)
111 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
114 return (ast_expression*)util_htget(parser->htglobals, name);
117 ast_expression* parser_find_global(parser_t *parser, const std::string &name) {
118 return parser_find_global(parser, name.c_str());
121 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->m_function_type;
127 for (auto &it : fun->m_type_params) {
128 if (it->m_name == name)
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = parser->variables.size(); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_local(parser_t *parser, const std::string &name, size_t upto, bool *isparam) {
152 return parser_find_local(parser, name.c_str(), upto, isparam);
155 static ast_expression* parser_find_var(parser_t *parser, const char *name)
159 v = parser_find_local(parser, name, 0, &dummy);
160 if (!v) v = parser_find_global(parser, name);
164 static inline ast_expression* parser_find_var(parser_t *parser, const std::string &name) {
165 return parser_find_var(parser, name.c_str());
168 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
172 hash = util_hthash(parser->typedefs[0], name);
174 for (i = parser->typedefs.size(); i > upto;) {
176 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
182 static ast_value* parser_find_typedef(parser_t *parser, const std::string &name, size_t upto) {
183 return parser_find_typedef(parser, name.c_str(), upto);
187 size_t etype; /* 0 = expression, others are operators */
191 ast_block *block; /* for commas and function calls */
204 std::vector<sy_elem> out;
205 std::vector<sy_elem> ops;
206 std::vector<size_t> argc;
207 std::vector<unsigned int> paren;
210 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
221 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
232 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
234 e.etype = 1 + (op - operators);
243 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
254 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
255 * so we need to rotate it to become ent.(foo[n]).
257 static bool rotate_entfield_array_index_nodes(ast_expression **out)
259 ast_array_index *index, *oldindex;
260 ast_entfield *entfield;
264 ast_expression *entity;
266 lex_ctx_t ctx = (*out)->m_context;
268 if (!ast_istype(*out, ast_array_index))
270 index = (ast_array_index*)*out;
272 if (!ast_istype(index->m_array, ast_entfield))
274 entfield = (ast_entfield*)index->m_array;
276 if (!ast_istype(entfield->m_field, ast_value))
278 field = (ast_value*)entfield->m_field;
280 sub = index->m_index;
281 entity = entfield->m_entity;
285 index = ast_array_index::make(ctx, field, sub);
286 entfield = new ast_entfield(ctx, entity, index);
289 oldindex->m_array = nullptr;
290 oldindex->m_index = nullptr;
296 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
298 if (ast_istype(expr, ast_value)) {
299 ast_value *val = (ast_value*)expr;
300 if (val->m_cvq == CV_CONST) {
301 if (val->m_name[0] == '#') {
302 compile_error(ctx, "invalid assignment to a literal constant");
306 * To work around quakeworld we must elide the error and make it
309 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
310 compile_error(ctx, "assignment to constant `%s`", val->m_name);
312 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
319 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
323 ast_expression *out = nullptr;
324 ast_expression *exprs[3];
325 ast_block *blocks[3];
326 ast_binstore *asbinstore;
327 size_t i, assignop, addop, subop;
328 qcint_t generated_op = 0;
333 if (sy->ops.empty()) {
334 parseerror(parser, "internal error: missing operator");
338 if (sy->ops.back().isparen) {
339 parseerror(parser, "unmatched parenthesis");
343 op = &operators[sy->ops.back().etype - 1];
344 ctx = sy->ops.back().ctx;
346 if (sy->out.size() < op->operands) {
347 if (op->flags & OP_PREFIX)
348 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
349 else /* this should have errored previously already */
350 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
356 /* op(:?) has no input and no output */
360 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
361 for (i = 0; i < op->operands; ++i) {
362 exprs[i] = sy->out[sy->out.size()+i].out;
363 blocks[i] = sy->out[sy->out.size()+i].block;
365 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
366 !(i != 0 && op->id == opid2('?',':')) &&
367 !(i == 1 && op->id == opid1('.')))
369 if (ast_istype(exprs[i], ast_label))
370 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
372 compile_error(exprs[i]->m_context, "not an expression");
373 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
377 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
378 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
382 #define NotSameType(T) \
383 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
384 exprs[0]->m_vtype != T)
389 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
393 if (exprs[0]->m_vtype == TYPE_VECTOR &&
394 exprs[1]->m_vtype == TYPE_NOEXPR)
396 if (exprs[1] == parser->const_vec[0])
397 out = ast_member::make(ctx, exprs[0], 0, "");
398 else if (exprs[1] == parser->const_vec[1])
399 out = ast_member::make(ctx, exprs[0], 1, "");
400 else if (exprs[1] == parser->const_vec[2])
401 out = ast_member::make(ctx, exprs[0], 2, "");
403 compile_error(ctx, "access to invalid vector component");
407 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
408 if (exprs[1]->m_vtype != TYPE_FIELD) {
409 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
412 out = new ast_entfield(ctx, exprs[0], exprs[1]);
414 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
415 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
419 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
425 if (exprs[0]->m_vtype != TYPE_ARRAY &&
426 !(exprs[0]->m_vtype == TYPE_FIELD &&
427 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
429 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
430 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
433 if (exprs[1]->m_vtype != TYPE_FLOAT) {
434 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
435 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
438 out = ast_array_index::make(ctx, exprs[0], exprs[1]);
439 rotate_entfield_array_index_nodes(&out);
443 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
444 sy->out.push_back(syexp(ctx, exprs[0]));
445 sy->out.push_back(syexp(ctx, exprs[1]));
450 if (!blocks[0]->addExpr(exprs[1]))
453 blocks[0] = new ast_block(ctx);
454 if (!blocks[0]->addExpr(exprs[0]) ||
455 !blocks[0]->addExpr(exprs[1]))
460 blocks[0]->setType(*exprs[1]);
462 sy->out.push_back(syblock(ctx, blocks[0]));
469 if ((out = parser->m_fold.op(op, exprs)))
472 if (exprs[0]->m_vtype != TYPE_FLOAT &&
473 exprs[0]->m_vtype != TYPE_VECTOR) {
474 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
475 type_name[exprs[0]->m_vtype]);
478 if (exprs[0]->m_vtype == TYPE_FLOAT)
479 out = ast_unary::make(ctx, VINSTR_NEG_F, exprs[0]);
481 out = ast_unary::make(ctx, VINSTR_NEG_V, exprs[0]);
485 if (!(out = parser->m_fold.op(op, exprs))) {
486 switch (exprs[0]->m_vtype) {
488 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
491 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[0]);
494 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
495 out = ast_unary::make(ctx, INSTR_NOT_F, exprs[0]);
497 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[0]);
499 /* we don't constant-fold NOT for these types */
501 out = ast_unary::make(ctx, INSTR_NOT_ENT, exprs[0]);
504 out = ast_unary::make(ctx, INSTR_NOT_FNC, exprs[0]);
507 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
508 type_name[exprs[0]->m_vtype]);
515 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
516 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
518 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
519 type_name[exprs[0]->m_vtype],
520 type_name[exprs[1]->m_vtype]);
523 if (!(out = parser->m_fold.op(op, exprs))) {
524 switch (exprs[0]->m_vtype) {
526 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
529 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
532 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
533 type_name[exprs[0]->m_vtype],
534 type_name[exprs[1]->m_vtype]);
540 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
541 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
543 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
544 type_name[exprs[1]->m_vtype],
545 type_name[exprs[0]->m_vtype]);
548 if (!(out = parser->m_fold.op(op, exprs))) {
549 switch (exprs[0]->m_vtype) {
551 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
554 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
557 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
558 type_name[exprs[1]->m_vtype],
559 type_name[exprs[0]->m_vtype]);
565 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
566 !(exprs[0]->m_vtype == TYPE_VECTOR &&
567 exprs[1]->m_vtype == TYPE_FLOAT) &&
568 !(exprs[1]->m_vtype == TYPE_VECTOR &&
569 exprs[0]->m_vtype == TYPE_FLOAT)
572 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
573 type_name[exprs[1]->m_vtype],
574 type_name[exprs[0]->m_vtype]);
577 if (!(out = parser->m_fold.op(op, exprs))) {
578 switch (exprs[0]->m_vtype) {
580 if (exprs[1]->m_vtype == TYPE_VECTOR)
581 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
583 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
586 if (exprs[1]->m_vtype == TYPE_FLOAT)
587 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
589 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
592 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
593 type_name[exprs[1]->m_vtype],
594 type_name[exprs[0]->m_vtype]);
601 if (exprs[1]->m_vtype != TYPE_FLOAT) {
602 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
603 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
604 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
607 if (!(out = parser->m_fold.op(op, exprs))) {
608 if (exprs[0]->m_vtype == TYPE_FLOAT)
609 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
611 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
612 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
613 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
620 if (NotSameType(TYPE_FLOAT)) {
621 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
622 type_name[exprs[0]->m_vtype],
623 type_name[exprs[1]->m_vtype]);
625 } else if (!(out = parser->m_fold.op(op, exprs))) {
626 /* generate a call to __builtin_mod */
627 ast_expression *mod = parser->m_intrin.func("mod");
628 ast_call *call = nullptr;
629 if (!mod) return false; /* can return null for missing floor */
631 call = ast_call::make(parser_ctx(parser), mod);
632 call->m_params.push_back(exprs[0]);
633 call->m_params.push_back(exprs[1]);
640 compile_error(ctx, "%= is unimplemented");
646 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
647 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
648 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
650 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
651 type_name[exprs[0]->m_vtype],
652 type_name[exprs[1]->m_vtype]);
656 if (!(out = parser->m_fold.op(op, exprs))) {
658 * IF the first expression is float, the following will be too
659 * since scalar ^ vector is not allowed.
661 if (exprs[0]->m_vtype == TYPE_FLOAT) {
662 out = fold::binary(ctx,
663 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
667 * The first is a vector: vector is allowed to bitop with vector and
668 * with scalar, branch here for the second operand.
670 if (exprs[1]->m_vtype == TYPE_VECTOR) {
672 * Bitop all the values of the vector components against the
673 * vectors components in question.
675 out = fold::binary(ctx,
676 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
679 out = fold::binary(ctx,
680 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
689 if (NotSameType(TYPE_FLOAT)) {
690 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
691 type_name[exprs[0]->m_vtype],
692 type_name[exprs[1]->m_vtype]);
696 if (!(out = parser->m_fold.op(op, exprs))) {
697 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
698 ast_call *call = ast_call::make(parser_ctx(parser), shift);
699 call->m_params.push_back(exprs[0]);
700 call->m_params.push_back(exprs[1]);
705 case opid3('<','<','='):
706 case opid3('>','>','='):
707 if (NotSameType(TYPE_FLOAT)) {
708 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
709 type_name[exprs[0]->m_vtype],
710 type_name[exprs[1]->m_vtype]);
714 if(!(out = parser->m_fold.op(op, exprs))) {
715 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
716 ast_call *call = ast_call::make(parser_ctx(parser), shift);
717 call->m_params.push_back(exprs[0]);
718 call->m_params.push_back(exprs[1]);
730 generated_op += 1; /* INSTR_OR */
733 generated_op += INSTR_AND;
734 if (!(out = parser->m_fold.op(op, exprs))) {
735 if (OPTS_FLAG(PERL_LOGIC) && !exprs[0]->compareType(*exprs[1])) {
736 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
737 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
738 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
741 for (i = 0; i < 2; ++i) {
742 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
743 out = ast_unary::make(ctx, INSTR_NOT_V, exprs[i]);
745 out = ast_unary::make(ctx, INSTR_NOT_F, out);
747 exprs[i] = out; out = nullptr;
748 if (OPTS_FLAG(PERL_LOGIC)) {
749 /* here we want to keep the right expressions' type */
753 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
754 out = ast_unary::make(ctx, INSTR_NOT_S, exprs[i]);
756 out = ast_unary::make(ctx, INSTR_NOT_F, out);
758 exprs[i] = out; out = nullptr;
759 if (OPTS_FLAG(PERL_LOGIC)) {
760 /* here we want to keep the right expressions' type */
765 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
770 if (sy->paren.back() != PAREN_TERNARY2) {
771 compile_error(ctx, "mismatched parenthesis/ternary");
774 sy->paren.pop_back();
775 if (!exprs[1]->compareType(*exprs[2])) {
776 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
777 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
778 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
781 if (!(out = parser->m_fold.op(op, exprs)))
782 out = new ast_ternary(ctx, exprs[0], exprs[1], exprs[2]);
785 case opid2('*', '*'):
786 if (NotSameType(TYPE_FLOAT)) {
787 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
788 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
789 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
794 if (!(out = parser->m_fold.op(op, exprs))) {
795 ast_call *gencall = ast_call::make(parser_ctx(parser), parser->m_intrin.func("pow"));
796 gencall->m_params.push_back(exprs[0]);
797 gencall->m_params.push_back(exprs[1]);
802 case opid2('>', '<'):
803 if (NotSameType(TYPE_VECTOR)) {
804 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
805 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
806 compile_error(ctx, "invalid types used in cross product: %s and %s",
811 if (!(out = parser->m_fold.op(op, exprs))) {
822 case opid3('<','=','>'): /* -1, 0, or 1 */
823 if (NotSameType(TYPE_FLOAT)) {
824 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
825 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
826 compile_error(ctx, "invalid types used in comparision: %s and %s",
832 if (!(out = parser->m_fold.op(op, exprs))) {
833 /* This whole block is NOT fold_binary safe */
834 ast_binary *eq = new ast_binary(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
836 eq->m_refs = AST_REF_NONE;
839 out = new ast_ternary(ctx,
840 new ast_binary(ctx, INSTR_LT, exprs[0], exprs[1]),
842 parser->m_fold.imm_float(2),
845 new ast_ternary(ctx, eq,
847 parser->m_fold.imm_float(0),
850 parser->m_fold.imm_float(1)
860 generated_op += 1; /* INSTR_GT */
863 generated_op += 1; /* INSTR_LT */
865 case opid2('>', '='):
866 generated_op += 1; /* INSTR_GE */
868 case opid2('<', '='):
869 generated_op += INSTR_LE;
870 if (NotSameType(TYPE_FLOAT)) {
871 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
872 type_name[exprs[0]->m_vtype],
873 type_name[exprs[1]->m_vtype]);
876 if (!(out = parser->m_fold.op(op, exprs)))
877 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
879 case opid2('!', '='):
880 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
881 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
882 type_name[exprs[0]->m_vtype],
883 type_name[exprs[1]->m_vtype]);
886 if (!(out = parser->m_fold.op(op, exprs)))
887 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
889 case opid2('=', '='):
890 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
891 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
892 type_name[exprs[0]->m_vtype],
893 type_name[exprs[1]->m_vtype]);
896 if (!(out = parser->m_fold.op(op, exprs)))
897 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
901 if (ast_istype(exprs[0], ast_entfield)) {
902 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
903 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
904 exprs[0]->m_vtype == TYPE_FIELD &&
905 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
907 assignop = type_storep_instr[TYPE_VECTOR];
910 assignop = type_storep_instr[exprs[0]->m_vtype];
911 if (assignop == VINSTR_END || !field->m_next->compareType(*exprs[1]))
913 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
914 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
915 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
916 field->m_next->m_vtype == TYPE_FUNCTION &&
917 exprs[1]->m_vtype == TYPE_FUNCTION)
919 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
920 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
923 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
928 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
929 exprs[0]->m_vtype == TYPE_FIELD &&
930 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
932 assignop = type_store_instr[TYPE_VECTOR];
935 assignop = type_store_instr[exprs[0]->m_vtype];
938 if (assignop == VINSTR_END) {
939 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
940 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
941 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
943 else if (!exprs[0]->compareType(*exprs[1]))
945 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
946 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
947 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
948 exprs[0]->m_vtype == TYPE_FUNCTION &&
949 exprs[1]->m_vtype == TYPE_FUNCTION)
951 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
952 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
955 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
958 (void)check_write_to(ctx, exprs[0]);
959 /* When we're a vector of part of an entity field we use STOREP */
960 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
961 assignop = INSTR_STOREP_F;
962 out = new ast_store(ctx, assignop, exprs[0], exprs[1]);
964 case opid3('+','+','P'):
965 case opid3('-','-','P'):
967 if (exprs[0]->m_vtype != TYPE_FLOAT) {
968 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
969 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
972 if (op->id == opid3('+','+','P'))
976 (void)check_write_to(exprs[0]->m_context, exprs[0]);
977 if (ast_istype(exprs[0], ast_entfield)) {
978 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
980 parser->m_fold.imm_float(1));
982 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
984 parser->m_fold.imm_float(1));
987 case opid3('S','+','+'):
988 case opid3('S','-','-'):
990 if (exprs[0]->m_vtype != TYPE_FLOAT) {
991 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
992 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
995 if (op->id == opid3('S','+','+')) {
1000 subop = INSTR_ADD_F;
1002 (void)check_write_to(exprs[0]->m_context, exprs[0]);
1003 if (ast_istype(exprs[0], ast_entfield)) {
1004 out = new ast_binstore(ctx, INSTR_STOREP_F, addop,
1006 parser->m_fold.imm_float(1));
1008 out = new ast_binstore(ctx, INSTR_STORE_F, addop,
1010 parser->m_fold.imm_float(1));
1014 out = fold::binary(ctx, subop,
1016 parser->m_fold.imm_float(1));
1019 case opid2('+','='):
1020 case opid2('-','='):
1021 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
1022 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
1024 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1025 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1026 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1030 (void)check_write_to(ctx, exprs[0]);
1031 if (ast_istype(exprs[0], ast_entfield))
1032 assignop = type_storep_instr[exprs[0]->m_vtype];
1034 assignop = type_store_instr[exprs[0]->m_vtype];
1035 switch (exprs[0]->m_vtype) {
1037 out = new ast_binstore(ctx, assignop,
1038 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1039 exprs[0], exprs[1]);
1042 out = new ast_binstore(ctx, assignop,
1043 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1044 exprs[0], exprs[1]);
1047 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1048 type_name[exprs[0]->m_vtype],
1049 type_name[exprs[1]->m_vtype]);
1053 case opid2('*','='):
1054 case opid2('/','='):
1055 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1056 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1057 exprs[0]->m_vtype == TYPE_VECTOR))
1059 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1060 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1061 compile_error(ctx, "invalid types used in expression: %s and %s",
1065 (void)check_write_to(ctx, exprs[0]);
1066 if (ast_istype(exprs[0], ast_entfield))
1067 assignop = type_storep_instr[exprs[0]->m_vtype];
1069 assignop = type_store_instr[exprs[0]->m_vtype];
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 if (ast_istype(exprs[0], ast_entfield))
1111 assignop = type_storep_instr[exprs[0]->m_vtype];
1113 assignop = type_store_instr[exprs[0]->m_vtype];
1114 if (exprs[0]->m_vtype == TYPE_FLOAT)
1115 out = new ast_binstore(ctx, assignop,
1116 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1117 exprs[0], exprs[1]);
1119 out = new ast_binstore(ctx, assignop,
1120 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1121 exprs[0], exprs[1]);
1123 case opid3('&','~','='):
1124 /* This is like: a &= ~(b);
1125 * But QC has no bitwise-not, so we implement it as
1128 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1129 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1130 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1131 compile_error(ctx, "invalid types used in expression: %s and %s",
1135 if (ast_istype(exprs[0], ast_entfield))
1136 assignop = type_storep_instr[exprs[0]->m_vtype];
1138 assignop = type_store_instr[exprs[0]->m_vtype];
1139 if (exprs[0]->m_vtype == TYPE_FLOAT)
1140 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1142 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1145 (void)check_write_to(ctx, exprs[0]);
1146 if (exprs[0]->m_vtype == TYPE_FLOAT)
1147 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1149 asbinstore = new ast_binstore(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1150 asbinstore->m_keep_dest = true;
1154 case opid3('l', 'e', 'n'):
1155 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1156 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1157 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1160 /* strings must be const, arrays are statically sized */
1161 if (exprs[0]->m_vtype == TYPE_STRING &&
1162 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1164 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1167 out = parser->m_fold.op(op, exprs);
1170 case opid2('~', 'P'):
1171 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1172 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1173 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1176 if (!(out = parser->m_fold.op(op, exprs))) {
1177 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1178 out = fold::binary(ctx, INSTR_SUB_F, parser->m_fold.imm_float(2), exprs[0]);
1180 out = fold::binary(ctx, INSTR_SUB_V, parser->m_fold.imm_vector(1), exprs[0]);
1187 compile_error(ctx, "failed to apply operator %s", op->op);
1191 sy->out.push_back(syexp(ctx, out));
1195 static bool parser_close_call(parser_t *parser, shunt *sy)
1197 /* was a function call */
1198 ast_expression *fun;
1199 ast_value *funval = nullptr;
1203 size_t paramcount, i;
1206 fid = sy->ops.back().off;
1209 /* out[fid] is the function
1210 * everything above is parameters...
1212 if (sy->argc.empty()) {
1213 parseerror(parser, "internal error: no argument counter available");
1217 paramcount = sy->argc.back();
1218 sy->argc.pop_back();
1220 if (sy->out.size() < fid) {
1221 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1229 * TODO handle this at the intrinsic level with an ast_intrinsic
1232 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1234 if (fid+2 != sy->out.size() || sy->out.back().block) {
1235 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1238 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1239 ast_unref(sy->out.back().out);
1240 sy->out[fid] = syexp(sy->out.back().out->m_context,
1241 parser->m_fold.constgen_string(ty, false));
1247 * Now we need to determine if the function that is being called is
1248 * an intrinsic so we can evaluate if the arguments to it are constant
1249 * and than fruitfully fold them.
1251 #define fold_can_1(X) \
1252 (ast_istype(((X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1253 ((X))->m_vtype != TYPE_FUNCTION)
1255 if (fid + 1 < sy->out.size())
1258 for (i = 0; i < paramcount; ++i) {
1259 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1266 * All is well which ends well, if we make it into here we can ignore the
1267 * intrinsic call and just evaluate it i.e constant fold it.
1269 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1270 std::vector<ast_expression*> exprs;
1271 ast_expression *foldval = nullptr;
1273 exprs.reserve(paramcount);
1274 for (i = 0; i < paramcount; i++)
1275 exprs.push_back(sy->out[fid+1 + i].out);
1277 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs.data()))) {
1282 * Blub: what sorts of unreffing and resizing of
1283 * sy->out should I be doing here?
1285 sy->out[fid] = syexp(foldval->m_context, foldval);
1286 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1292 call = ast_call::make(sy->ops[sy->ops.size()].ctx, fun);
1297 if (fid+1 + paramcount != sy->out.size()) {
1298 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1305 for (i = 0; i < paramcount; ++i)
1306 call->m_params.push_back(sy->out[fid+1 + i].out);
1307 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1308 (void)!call->checkTypes(parser->function->m_function_type->m_varparam);
1309 if (parser->max_param_count < paramcount)
1310 parser->max_param_count = paramcount;
1312 if (ast_istype(fun, ast_value)) {
1313 funval = (ast_value*)fun;
1314 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1315 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1317 call->m_va_count = parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1321 /* overwrite fid, the function, with a call */
1322 sy->out[fid] = syexp(call->m_context, call);
1324 if (fun->m_vtype != TYPE_FUNCTION) {
1325 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1330 parseerror(parser, "could not determine function return type");
1333 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1335 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1337 return !parsewarning(parser, WARN_DEPRECATED,
1338 "call to function (which is marked deprecated)\n",
1339 "-> it has been declared here: %s:%i",
1340 fun->m_context.file, fun->m_context.line);
1342 if (!fval->m_desc.length()) {
1343 return !parsewarning(parser, WARN_DEPRECATED,
1344 "call to `%s` (which is marked deprecated)\n"
1345 "-> `%s` declared here: %s:%i",
1346 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1348 return !parsewarning(parser, WARN_DEPRECATED,
1349 "call to `%s` (deprecated: %s)\n"
1350 "-> `%s` declared here: %s:%i",
1351 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1352 fun->m_context.line);
1355 if (fun->m_type_params.size() != paramcount &&
1356 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1357 fun->m_type_params.size() < paramcount))
1359 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1361 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1362 "too %s parameters for call to %s: expected %i, got %i\n"
1363 " -> `%s` has been declared here: %s:%i",
1364 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1365 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1367 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1368 "too %s parameters for function call: expected %i, got %i\n"
1369 " -> it has been declared here: %s:%i",
1370 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1371 fun->m_context.file, (int)fun->m_context.line);
1378 static bool parser_close_paren(parser_t *parser, shunt *sy)
1380 if (sy->ops.empty()) {
1381 parseerror(parser, "unmatched closing paren");
1385 while (sy->ops.size()) {
1386 if (sy->ops.back().isparen) {
1387 if (sy->paren.back() == PAREN_FUNC) {
1388 sy->paren.pop_back();
1389 if (!parser_close_call(parser, sy))
1393 if (sy->paren.back() == PAREN_EXPR) {
1394 sy->paren.pop_back();
1395 if (sy->out.empty()) {
1396 compile_error(sy->ops.back().ctx, "empty paren expression");
1403 if (sy->paren.back() == PAREN_INDEX) {
1404 sy->paren.pop_back();
1405 // pop off the parenthesis
1407 /* then apply the index operator */
1408 if (!parser_sy_apply_operator(parser, sy))
1412 if (sy->paren.back() == PAREN_TERNARY1) {
1413 sy->paren.back() = PAREN_TERNARY2;
1414 // pop off the parenthesis
1418 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1421 if (!parser_sy_apply_operator(parser, sy))
1427 static void parser_reclassify_token(parser_t *parser)
1430 if (parser->tok >= TOKEN_START)
1432 for (i = 0; i < operator_count; ++i) {
1433 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1434 parser->tok = TOKEN_OPERATOR;
1440 static ast_expression* parse_vararg_do(parser_t *parser)
1442 ast_expression *idx, *out;
1444 ast_value *funtype = parser->function->m_function_type;
1445 lex_ctx_t ctx = parser_ctx(parser);
1447 if (!parser->function->m_varargs) {
1448 parseerror(parser, "function has no variable argument list");
1452 if (!parser_next(parser) || parser->tok != '(') {
1453 parseerror(parser, "expected parameter index and type in parenthesis");
1456 if (!parser_next(parser)) {
1457 parseerror(parser, "error parsing parameter index");
1461 idx = parse_expression_leave(parser, true, false, false);
1465 if (parser->tok != ',') {
1466 if (parser->tok != ')') {
1468 parseerror(parser, "expected comma after parameter index");
1471 // vararg piping: ...(start)
1472 out = new ast_argpipe(ctx, idx);
1476 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1478 parseerror(parser, "expected typename for vararg");
1482 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1488 if (parser->tok != ')') {
1491 parseerror(parser, "expected closing paren");
1495 if (funtype->m_varparam &&
1496 !typevar->compareType(*funtype->m_varparam))
1500 ast_type_to_string(typevar, ty1, sizeof(ty1));
1501 ast_type_to_string(funtype->m_varparam, ty2, sizeof(ty2));
1502 compile_error(typevar->m_context,
1503 "function was declared to take varargs of type `%s`, requested type is: %s",
1507 out = ast_array_index::make(ctx, parser->function->m_varargs.get(), idx);
1508 out->adoptType(*typevar);
1513 static ast_expression* parse_vararg(parser_t *parser)
1515 bool old_noops = parser->lex->flags.noops;
1517 ast_expression *out;
1519 parser->lex->flags.noops = true;
1520 out = parse_vararg_do(parser);
1522 parser->lex->flags.noops = old_noops;
1526 /* not to be exposed */
1527 bool ftepp_predef_exists(const char *name);
1528 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1530 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1531 parser->tok == TOKEN_IDENT &&
1532 !strcmp(parser_tokval(parser), "_"))
1534 /* a translatable string */
1537 parser->lex->flags.noops = true;
1538 if (!parser_next(parser) || parser->tok != '(') {
1539 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1542 parser->lex->flags.noops = false;
1543 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1544 parseerror(parser, "expected a constant string in translatable-string extension");
1547 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1550 sy->out.push_back(syexp(parser_ctx(parser), val));
1552 if (!parser_next(parser) || parser->tok != ')') {
1553 parseerror(parser, "expected closing paren after translatable string");
1558 else if (parser->tok == TOKEN_DOTS)
1561 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1562 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1565 va = parse_vararg(parser);
1568 sy->out.push_back(syexp(parser_ctx(parser), va));
1571 else if (parser->tok == TOKEN_FLOATCONST) {
1572 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1575 sy->out.push_back(syexp(parser_ctx(parser), val));
1578 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1579 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1582 sy->out.push_back(syexp(parser_ctx(parser), val));
1585 else if (parser->tok == TOKEN_STRINGCONST) {
1586 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1589 sy->out.push_back(syexp(parser_ctx(parser), val));
1592 else if (parser->tok == TOKEN_VECTORCONST) {
1593 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1596 sy->out.push_back(syexp(parser_ctx(parser), val));
1599 else if (parser->tok == TOKEN_IDENT)
1601 const char *ctoken = parser_tokval(parser);
1602 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1603 ast_expression *var;
1604 /* a_vector.{x,y,z} */
1605 if (sy->ops.empty() ||
1606 !sy->ops.back().etype ||
1607 operators[sy->ops.back().etype-1].id != opid1('.'))
1609 /* When adding more intrinsics, fix the above condition */
1612 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1614 var = parser->const_vec[ctoken[0]-'x'];
1616 var = parser_find_var(parser, parser_tokval(parser));
1618 var = parser_find_field(parser, parser_tokval(parser));
1620 if (!var && with_labels) {
1621 var = parser_find_label(parser, parser_tokval(parser));
1623 ast_label *lbl = new ast_label(parser_ctx(parser), parser_tokval(parser), true);
1625 parser->labels.push_back(lbl);
1628 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1629 var = parser->m_fold.constgen_string(parser->function->m_name, false);
1632 * now we try for the real intrinsic hashtable. If the string
1633 * begins with __builtin, we simply skip past it, otherwise we
1634 * use the identifier as is.
1636 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1637 var = parser->m_intrin.func(parser_tokval(parser));
1641 * Try it again, intrin_func deals with the alias method as well
1642 * the first one masks for __builtin though, we emit warning here.
1645 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1646 (void)!compile_warning(
1649 "using implicitly defined builtin `__builtin_%s' for `%s'",
1650 parser_tokval(parser),
1651 parser_tokval(parser)
1659 * sometimes people use preprocessing predefs without enabling them
1660 * i've done this thousands of times already myself. Lets check for
1661 * it in the predef table. And diagnose it better :)
1663 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1664 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1668 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1674 // promote these to norefs
1675 if (ast_istype(var, ast_value))
1677 ((ast_value *)var)->m_flags |= AST_FLAG_NOREF;
1679 else if (ast_istype(var, ast_member))
1681 ast_member *mem = (ast_member *)var;
1682 if (ast_istype(mem->m_owner, ast_value))
1683 ((ast_value *)mem->m_owner)->m_flags |= AST_FLAG_NOREF;
1686 sy->out.push_back(syexp(parser_ctx(parser), var));
1689 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1693 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1695 ast_expression *expr = nullptr;
1697 bool wantop = false;
1698 /* only warn once about an assignment in a truth value because the current code
1699 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1701 bool warn_parenthesis = true;
1703 /* count the parens because an if starts with one, so the
1704 * end of a condition is an unmatched closing paren
1708 memset(&sy, 0, sizeof(sy));
1710 parser->lex->flags.noops = false;
1712 parser_reclassify_token(parser);
1716 if (parser->tok == TOKEN_TYPENAME) {
1717 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1721 if (parser->tok == TOKEN_OPERATOR)
1723 /* classify the operator */
1724 const oper_info *op;
1725 const oper_info *olast = nullptr;
1727 for (o = 0; o < operator_count; ++o) {
1728 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1729 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1730 !strcmp(parser_tokval(parser), operators[o].op))
1735 if (o == operator_count) {
1736 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1739 /* found an operator */
1742 /* when declaring variables, a comma starts a new variable */
1743 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1744 /* fixup the token */
1749 /* a colon without a pervious question mark cannot be a ternary */
1750 if (!ternaries && op->id == opid2(':','?')) {
1755 if (op->id == opid1(',')) {
1756 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1757 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1761 if (sy.ops.size() && !sy.ops.back().isparen)
1762 olast = &operators[sy.ops.back().etype-1];
1764 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1765 while (olast && op->prec < olast->prec)
1767 if (!parser_sy_apply_operator(parser, &sy))
1769 if (sy.ops.size() && !sy.ops.back().isparen)
1770 olast = &operators[sy.ops.back().etype-1];
1775 #define IsAssignOp(x) (\
1776 (x) == opid1('=') || \
1777 (x) == opid2('+','=') || \
1778 (x) == opid2('-','=') || \
1779 (x) == opid2('*','=') || \
1780 (x) == opid2('/','=') || \
1781 (x) == opid2('%','=') || \
1782 (x) == opid2('&','=') || \
1783 (x) == opid2('|','=') || \
1784 (x) == opid3('&','~','=') \
1786 if (warn_parenthesis) {
1787 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1788 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1789 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1792 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1793 warn_parenthesis = false;
1796 if (olast && olast->id != op->id) {
1797 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1798 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1800 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1801 warn_parenthesis = false;
1803 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1804 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1806 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1807 warn_parenthesis = false;
1813 (op->prec < olast->prec) ||
1814 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1816 if (!parser_sy_apply_operator(parser, &sy))
1818 if (sy.ops.size() && !sy.ops.back().isparen)
1819 olast = &operators[sy.ops.back().etype-1];
1824 if (op->id == opid1('(')) {
1826 size_t sycount = sy.out.size();
1827 /* we expected an operator, this is the function-call operator */
1828 sy.paren.push_back(PAREN_FUNC);
1829 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1830 sy.argc.push_back(0);
1832 sy.paren.push_back(PAREN_EXPR);
1833 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1836 } else if (op->id == opid1('[')) {
1838 parseerror(parser, "unexpected array subscript");
1841 sy.paren.push_back(PAREN_INDEX);
1842 /* push both the operator and the paren, this makes life easier */
1843 sy.ops.push_back(syop(parser_ctx(parser), op));
1844 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1846 } else if (op->id == opid2('?',':')) {
1847 sy.ops.push_back(syop(parser_ctx(parser), op));
1848 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1851 sy.paren.push_back(PAREN_TERNARY1);
1852 } else if (op->id == opid2(':','?')) {
1853 if (sy.paren.empty()) {
1854 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1857 if (sy.paren.back() != PAREN_TERNARY1) {
1858 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1861 if (!parser_close_paren(parser, &sy))
1863 sy.ops.push_back(syop(parser_ctx(parser), op));
1867 sy.ops.push_back(syop(parser_ctx(parser), op));
1868 wantop = !!(op->flags & OP_SUFFIX);
1871 else if (parser->tok == ')') {
1872 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1873 if (!parser_sy_apply_operator(parser, &sy))
1876 if (sy.paren.empty())
1879 if (sy.paren.back() == PAREN_TERNARY1) {
1880 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1883 if (!parser_close_paren(parser, &sy))
1886 /* must be a function call without parameters */
1887 if (sy.paren.back() != PAREN_FUNC) {
1888 parseerror(parser, "closing paren in invalid position");
1891 if (!parser_close_paren(parser, &sy))
1896 else if (parser->tok == '(') {
1897 parseerror(parser, "internal error: '(' should be classified as operator");
1900 else if (parser->tok == '[') {
1901 parseerror(parser, "internal error: '[' should be classified as operator");
1904 else if (parser->tok == ']') {
1905 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1906 if (!parser_sy_apply_operator(parser, &sy))
1909 if (sy.paren.empty())
1911 if (sy.paren.back() != PAREN_INDEX) {
1912 parseerror(parser, "mismatched parentheses, unexpected ']'");
1915 if (!parser_close_paren(parser, &sy))
1920 if (!parse_sya_operand(parser, &sy, with_labels))
1925 /* in this case we might want to allow constant string concatenation */
1926 bool concatenated = false;
1927 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1928 ast_expression *lexpr = sy.out.back().out;
1929 if (ast_istype(lexpr, ast_value)) {
1930 ast_value *last = (ast_value*)lexpr;
1931 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1932 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1934 char *newstr = nullptr;
1935 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1936 sy.out.back().out = parser->m_fold.constgen_string(newstr, false);
1938 concatenated = true;
1942 if (!concatenated) {
1943 parseerror(parser, "expected operator or end of statement");
1948 if (!parser_next(parser)) {
1951 if (parser->tok == ';' ||
1952 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1953 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1959 while (sy.ops.size()) {
1960 if (!parser_sy_apply_operator(parser, &sy))
1964 parser->lex->flags.noops = true;
1965 if (sy.out.size() != 1) {
1966 parseerror(parser, "expression expected");
1969 expr = sy.out[0].out;
1970 if (sy.paren.size()) {
1971 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1977 parser->lex->flags.noops = true;
1978 for (auto &it : sy.out)
1979 if (it.out) ast_unref(it.out);
1983 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1985 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1988 if (parser->tok != ';') {
1989 parseerror(parser, "semicolon expected after expression");
1993 if (!parser_next(parser)) {
2000 static void parser_enterblock(parser_t *parser)
2002 parser->variables.push_back(util_htnew(PARSER_HT_SIZE));
2003 parser->_blocklocals.push_back(parser->_locals.size());
2004 parser->typedefs.push_back(util_htnew(TYPEDEF_HT_SIZE));
2005 parser->_blocktypedefs.push_back(parser->_typedefs.size());
2006 parser->_block_ctx.push_back(parser_ctx(parser));
2009 static bool parser_leaveblock(parser_t *parser)
2012 size_t locals, typedefs;
2014 if (parser->variables.size() <= PARSER_HT_LOCALS) {
2015 parseerror(parser, "internal error: parser_leaveblock with no block");
2019 util_htdel(parser->variables.back());
2021 parser->variables.pop_back();
2022 if (!parser->_blocklocals.size()) {
2023 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2027 locals = parser->_blocklocals.back();
2028 parser->_blocklocals.pop_back();
2029 parser->_locals.resize(locals);
2031 typedefs = parser->_blocktypedefs.back();
2032 parser->_typedefs.resize(typedefs);
2033 util_htdel(parser->typedefs.back());
2034 parser->typedefs.pop_back();
2036 parser->_block_ctx.pop_back();
2041 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2043 parser->_locals.push_back(e);
2044 util_htset(parser->variables.back(), name, (void*)e);
2046 static void parser_addlocal(parser_t *parser, const std::string &name, ast_expression *e) {
2047 return parser_addlocal(parser, name.c_str(), e);
2050 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2052 parser->globals.push_back(e);
2053 util_htset(parser->htglobals, name, e);
2055 static void parser_addglobal(parser_t *parser, const std::string &name, ast_expression *e) {
2056 return parser_addglobal(parser, name.c_str(), e);
2059 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2063 ast_expression *prev;
2065 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2067 ast_type_to_string(cond, ty, sizeof(ty));
2068 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2071 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2074 cond = ast_unary::make(cond->m_context, INSTR_NOT_S, cond);
2077 parseerror(parser, "internal error: failed to process condition");
2082 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2084 /* vector types need to be cast to true booleans */
2085 ast_binary *bin = (ast_binary*)cond;
2086 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2088 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2090 cond = ast_unary::make(cond->m_context, INSTR_NOT_V, cond);
2093 parseerror(parser, "internal error: failed to process condition");
2100 unary = (ast_unary*)cond;
2101 /* ast_istype dereferences cond, should test here for safety */
2102 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2104 cond = unary->m_operand;
2105 unary->m_operand = nullptr;
2108 unary = (ast_unary*)cond;
2112 parseerror(parser, "internal error: failed to process condition");
2114 if (ifnot) *_ifnot = !*_ifnot;
2118 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2121 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2124 lex_ctx_t ctx = parser_ctx(parser);
2126 (void)block; /* not touching */
2128 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2129 if (!parser_next(parser)) {
2130 parseerror(parser, "expected condition or 'not'");
2133 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2135 if (!parser_next(parser)) {
2136 parseerror(parser, "expected condition in parenthesis");
2140 if (parser->tok != '(') {
2141 parseerror(parser, "expected 'if' condition in parenthesis");
2144 /* parse into the expression */
2145 if (!parser_next(parser)) {
2146 parseerror(parser, "expected 'if' condition after opening paren");
2149 /* parse the condition */
2150 cond = parse_expression_leave(parser, false, true, false);
2154 if (parser->tok != ')') {
2155 parseerror(parser, "expected closing paren after 'if' condition");
2159 /* parse into the 'then' branch */
2160 if (!parser_next(parser)) {
2161 parseerror(parser, "expected statement for on-true branch of 'if'");
2165 if (!parse_statement_or_block(parser, &ontrue)) {
2170 ontrue = new ast_block(parser_ctx(parser));
2171 /* check for an else */
2172 if (!strcmp(parser_tokval(parser), "else")) {
2173 /* parse into the 'else' branch */
2174 if (!parser_next(parser)) {
2175 parseerror(parser, "expected on-false branch after 'else'");
2180 if (!parse_statement_or_block(parser, &onfalse)) {
2187 cond = process_condition(parser, cond, &ifnot);
2189 if (ontrue) delete ontrue;
2190 if (onfalse) delete onfalse;
2195 ifthen = new ast_ifthen(ctx, cond, onfalse, ontrue);
2197 ifthen = new ast_ifthen(ctx, cond, ontrue, onfalse);
2202 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2203 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2206 char *label = nullptr;
2208 /* skip the 'while' and get the body */
2209 if (!parser_next(parser)) {
2210 if (OPTS_FLAG(LOOP_LABELS))
2211 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2213 parseerror(parser, "expected 'while' condition in parenthesis");
2217 if (parser->tok == ':') {
2218 if (!OPTS_FLAG(LOOP_LABELS))
2219 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2220 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2221 parseerror(parser, "expected loop label");
2224 label = util_strdup(parser_tokval(parser));
2225 if (!parser_next(parser)) {
2227 parseerror(parser, "expected 'while' condition in parenthesis");
2232 if (parser->tok != '(') {
2233 parseerror(parser, "expected 'while' condition in parenthesis");
2237 parser->breaks.push_back(label);
2238 parser->continues.push_back(label);
2240 rv = parse_while_go(parser, block, out);
2243 if (parser->breaks.back() != label || parser->continues.back() != label) {
2244 parseerror(parser, "internal error: label stack corrupted");
2250 parser->breaks.pop_back();
2251 parser->continues.pop_back();
2256 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2259 ast_expression *cond, *ontrue;
2263 lex_ctx_t ctx = parser_ctx(parser);
2265 (void)block; /* not touching */
2267 /* parse into the expression */
2268 if (!parser_next(parser)) {
2269 parseerror(parser, "expected 'while' condition after opening paren");
2272 /* parse the condition */
2273 cond = parse_expression_leave(parser, false, true, false);
2277 if (parser->tok != ')') {
2278 parseerror(parser, "expected closing paren after 'while' condition");
2282 /* parse into the 'then' branch */
2283 if (!parser_next(parser)) {
2284 parseerror(parser, "expected while-loop body");
2288 if (!parse_statement_or_block(parser, &ontrue)) {
2293 cond = process_condition(parser, cond, &ifnot);
2298 aloop = new ast_loop(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2303 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2304 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2307 char *label = nullptr;
2309 /* skip the 'do' and get the body */
2310 if (!parser_next(parser)) {
2311 if (OPTS_FLAG(LOOP_LABELS))
2312 parseerror(parser, "expected loop label or body");
2314 parseerror(parser, "expected loop body");
2318 if (parser->tok == ':') {
2319 if (!OPTS_FLAG(LOOP_LABELS))
2320 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2321 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2322 parseerror(parser, "expected loop label");
2325 label = util_strdup(parser_tokval(parser));
2326 if (!parser_next(parser)) {
2328 parseerror(parser, "expected loop body");
2333 parser->breaks.push_back(label);
2334 parser->continues.push_back(label);
2336 rv = parse_dowhile_go(parser, block, out);
2339 if (parser->breaks.back() != label || parser->continues.back() != label) {
2340 parseerror(parser, "internal error: label stack corrupted");
2346 parser->breaks.pop_back();
2347 parser->continues.pop_back();
2352 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2355 ast_expression *cond, *ontrue;
2359 lex_ctx_t ctx = parser_ctx(parser);
2361 (void)block; /* not touching */
2363 if (!parse_statement_or_block(parser, &ontrue))
2366 /* expect the "while" */
2367 if (parser->tok != TOKEN_KEYWORD ||
2368 strcmp(parser_tokval(parser), "while"))
2370 parseerror(parser, "expected 'while' and condition");
2375 /* skip the 'while' and check for opening paren */
2376 if (!parser_next(parser) || parser->tok != '(') {
2377 parseerror(parser, "expected 'while' condition in parenthesis");
2381 /* parse into the expression */
2382 if (!parser_next(parser)) {
2383 parseerror(parser, "expected 'while' condition after opening paren");
2387 /* parse the condition */
2388 cond = parse_expression_leave(parser, false, true, false);
2392 if (parser->tok != ')') {
2393 parseerror(parser, "expected closing paren after 'while' condition");
2399 if (!parser_next(parser) || parser->tok != ';') {
2400 parseerror(parser, "expected semicolon after condition");
2406 if (!parser_next(parser)) {
2407 parseerror(parser, "parse error");
2413 cond = process_condition(parser, cond, &ifnot);
2418 aloop = new ast_loop(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2423 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2424 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2427 char *label = nullptr;
2429 /* skip the 'for' and check for opening paren */
2430 if (!parser_next(parser)) {
2431 if (OPTS_FLAG(LOOP_LABELS))
2432 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2434 parseerror(parser, "expected 'for' expressions in parenthesis");
2438 if (parser->tok == ':') {
2439 if (!OPTS_FLAG(LOOP_LABELS))
2440 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2441 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2442 parseerror(parser, "expected loop label");
2445 label = util_strdup(parser_tokval(parser));
2446 if (!parser_next(parser)) {
2448 parseerror(parser, "expected 'for' expressions in parenthesis");
2453 if (parser->tok != '(') {
2454 parseerror(parser, "expected 'for' expressions in parenthesis");
2458 parser->breaks.push_back(label);
2459 parser->continues.push_back(label);
2461 rv = parse_for_go(parser, block, out);
2464 if (parser->breaks.back() != label || parser->continues.back() != label) {
2465 parseerror(parser, "internal error: label stack corrupted");
2471 parser->breaks.pop_back();
2472 parser->continues.pop_back();
2476 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2479 ast_expression *initexpr, *cond, *increment, *ontrue;
2484 lex_ctx_t ctx = parser_ctx(parser);
2486 parser_enterblock(parser);
2490 increment = nullptr;
2493 /* parse into the expression */
2494 if (!parser_next(parser)) {
2495 parseerror(parser, "expected 'for' initializer after opening paren");
2500 if (parser->tok == TOKEN_IDENT)
2501 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2503 if (typevar || parser->tok == TOKEN_TYPENAME) {
2504 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2507 else if (parser->tok != ';')
2509 initexpr = parse_expression_leave(parser, false, false, false);
2512 /* move on to condition */
2513 if (parser->tok != ';') {
2514 parseerror(parser, "expected semicolon after for-loop initializer");
2517 if (!parser_next(parser)) {
2518 parseerror(parser, "expected for-loop condition");
2521 } else if (!parser_next(parser)) {
2522 parseerror(parser, "expected for-loop condition");
2526 /* parse the condition */
2527 if (parser->tok != ';') {
2528 cond = parse_expression_leave(parser, false, true, false);
2532 /* move on to incrementor */
2533 if (parser->tok != ';') {
2534 parseerror(parser, "expected semicolon after for-loop initializer");
2537 if (!parser_next(parser)) {
2538 parseerror(parser, "expected for-loop condition");
2542 /* parse the incrementor */
2543 if (parser->tok != ')') {
2544 lex_ctx_t condctx = parser_ctx(parser);
2545 increment = parse_expression_leave(parser, false, false, false);
2548 if (!increment->m_side_effects) {
2549 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2555 if (parser->tok != ')') {
2556 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2559 /* parse into the 'then' branch */
2560 if (!parser_next(parser)) {
2561 parseerror(parser, "expected for-loop body");
2564 if (!parse_statement_or_block(parser, &ontrue))
2568 cond = process_condition(parser, cond, &ifnot);
2572 aloop = new ast_loop(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2575 if (!parser_leaveblock(parser)) {
2581 if (initexpr) ast_unref(initexpr);
2582 if (cond) ast_unref(cond);
2583 if (increment) ast_unref(increment);
2584 (void)!parser_leaveblock(parser);
2588 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2590 ast_expression *exp = nullptr;
2591 ast_expression *var = nullptr;
2592 ast_return *ret = nullptr;
2593 ast_value *retval = parser->function->m_return_value;
2594 ast_value *expected = parser->function->m_function_type;
2596 lex_ctx_t ctx = parser_ctx(parser);
2598 (void)block; /* not touching */
2600 if (!parser_next(parser)) {
2601 parseerror(parser, "expected return expression");
2605 /* return assignments */
2606 if (parser->tok == '=') {
2607 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2608 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2612 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2614 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2615 parseerror(parser, "invalid return type: `%s'", ty1);
2619 if (!parser_next(parser)) {
2620 parseerror(parser, "expected return assignment expression");
2624 if (!(exp = parse_expression_leave(parser, false, false, false)))
2627 /* prepare the return value */
2629 retval = new ast_value(ctx, "#LOCAL_RETURN", TYPE_VOID);
2630 retval->adoptType(*expected->m_next);
2631 parser->function->m_return_value = retval;
2632 parser->function->m_return_value->m_flags |= AST_FLAG_NOREF;
2635 if (!exp->compareType(*retval)) {
2636 char ty1[1024], ty2[1024];
2637 ast_type_to_string(exp, ty1, sizeof(ty1));
2638 ast_type_to_string(retval, ty2, sizeof(ty2));
2639 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2642 /* store to 'return' local variable */
2643 var = new ast_store(
2645 type_store_instr[expected->m_next->m_vtype],
2653 if (parser->tok != ';')
2654 parseerror(parser, "missing semicolon after return assignment");
2655 else if (!parser_next(parser))
2656 parseerror(parser, "parse error after return assignment");
2662 if (parser->tok != ';') {
2663 exp = parse_expression(parser, false, false);
2667 if (exp->m_vtype != TYPE_NIL &&
2668 exp->m_vtype != (expected)->m_next->m_vtype)
2670 parseerror(parser, "return with invalid expression");
2673 ret = new ast_return(ctx, exp);
2679 if (!parser_next(parser))
2680 parseerror(parser, "parse error");
2682 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2684 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2686 ret = new ast_return(ctx, retval);
2692 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2695 unsigned int levels = 0;
2696 lex_ctx_t ctx = parser_ctx(parser);
2697 auto &loops = (is_continue ? parser->continues : parser->breaks);
2699 (void)block; /* not touching */
2700 if (!parser_next(parser)) {
2701 parseerror(parser, "expected semicolon or loop label");
2705 if (loops.empty()) {
2707 parseerror(parser, "`continue` can only be used inside loops");
2709 parseerror(parser, "`break` can only be used inside loops or switches");
2712 if (parser->tok == TOKEN_IDENT) {
2713 if (!OPTS_FLAG(LOOP_LABELS))
2714 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2720 parseerror(parser, "no such loop to %s: `%s`",
2721 (is_continue ? "continue" : "break out of"),
2722 parser_tokval(parser));
2727 if (!parser_next(parser)) {
2728 parseerror(parser, "expected semicolon");
2733 if (parser->tok != ';') {
2734 parseerror(parser, "expected semicolon");
2738 if (!parser_next(parser))
2739 parseerror(parser, "parse error");
2741 *out = new ast_breakcont(ctx, is_continue, levels);
2745 /* returns true when it was a variable qualifier, false otherwise!
2746 * on error, cvq is set to CV_WRONG
2748 struct attribute_t {
2753 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2755 bool had_const = false;
2756 bool had_var = false;
2757 bool had_noref = false;
2758 bool had_attrib = false;
2759 bool had_static = false;
2762 static attribute_t attributes[] = {
2763 { "noreturn", AST_FLAG_NORETURN },
2764 { "inline", AST_FLAG_INLINE },
2765 { "eraseable", AST_FLAG_ERASEABLE },
2766 { "accumulate", AST_FLAG_ACCUMULATE },
2767 { "last", AST_FLAG_FINAL_DECL }
2774 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2776 /* parse an attribute */
2777 if (!parser_next(parser)) {
2778 parseerror(parser, "expected attribute after `[[`");
2783 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2784 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2785 flags |= attributes[i].flag;
2786 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2787 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2788 attributes[i].name);
2796 if (i != GMQCC_ARRAY_COUNT(attributes))
2800 if (!strcmp(parser_tokval(parser), "noref")) {
2802 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2803 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2808 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2809 flags |= AST_FLAG_ALIAS;
2812 if (!parser_next(parser)) {
2813 parseerror(parser, "parse error in attribute");
2817 if (parser->tok == '(') {
2818 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2819 parseerror(parser, "`alias` attribute missing parameter");
2823 *message = util_strdup(parser_tokval(parser));
2825 if (!parser_next(parser)) {
2826 parseerror(parser, "parse error in attribute");
2830 if (parser->tok != ')') {
2831 parseerror(parser, "`alias` attribute expected `)` after parameter");
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "parse error in attribute");
2841 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2842 parseerror(parser, "`alias` attribute expected `]]`");
2846 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2847 flags |= AST_FLAG_DEPRECATED;
2850 if (!parser_next(parser)) {
2851 parseerror(parser, "parse error in attribute");
2855 if (parser->tok == '(') {
2856 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2857 parseerror(parser, "`deprecated` attribute missing parameter");
2861 *message = util_strdup(parser_tokval(parser));
2863 if (!parser_next(parser)) {
2864 parseerror(parser, "parse error in attribute");
2868 if(parser->tok != ')') {
2869 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2873 if (!parser_next(parser)) {
2874 parseerror(parser, "parse error in attribute");
2879 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2880 parseerror(parser, "`deprecated` attribute expected `]]`");
2883 if (*message) mem_d(*message);
2889 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2890 flags |= AST_FLAG_COVERAGE;
2891 if (!parser_next(parser)) {
2893 parseerror(parser, "parse error in coverage attribute");
2897 if (parser->tok == '(') {
2898 if (!parser_next(parser)) {
2900 parseerror(parser, "invalid parameter for coverage() attribute\n"
2901 "valid are: block");
2905 if (parser->tok != ')') {
2907 if (parser->tok != TOKEN_IDENT)
2908 goto bad_coverage_arg;
2909 if (!strcmp(parser_tokval(parser), "block"))
2910 flags |= AST_FLAG_BLOCK_COVERAGE;
2911 else if (!strcmp(parser_tokval(parser), "none"))
2912 flags &= ~(AST_FLAG_COVERAGE_MASK);
2914 goto bad_coverage_arg;
2915 if (!parser_next(parser))
2916 goto error_in_coverage;
2917 if (parser->tok == ',') {
2918 if (!parser_next(parser))
2919 goto error_in_coverage;
2921 } while (parser->tok != ')');
2923 if (parser->tok != ')' || !parser_next(parser))
2924 goto error_in_coverage;
2926 /* without parameter [[coverage]] equals [[coverage(block)]] */
2927 flags |= AST_FLAG_BLOCK_COVERAGE;
2932 /* Skip tokens until we hit a ]] */
2933 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2934 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2935 if (!parser_next(parser)) {
2936 parseerror(parser, "error inside attribute");
2943 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2945 else if (!strcmp(parser_tokval(parser), "const"))
2947 else if (!strcmp(parser_tokval(parser), "var"))
2949 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2951 else if (!strcmp(parser_tokval(parser), "noref"))
2953 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2960 if (!parser_next(parser))
2970 *is_static = had_static;
2974 parseerror(parser, "parse error after variable qualifier");
2979 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2980 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2983 char *label = nullptr;
2985 /* skip the 'while' and get the body */
2986 if (!parser_next(parser)) {
2987 if (OPTS_FLAG(LOOP_LABELS))
2988 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2990 parseerror(parser, "expected 'switch' operand in parenthesis");
2994 if (parser->tok == ':') {
2995 if (!OPTS_FLAG(LOOP_LABELS))
2996 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2997 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2998 parseerror(parser, "expected loop label");
3001 label = util_strdup(parser_tokval(parser));
3002 if (!parser_next(parser)) {
3004 parseerror(parser, "expected 'switch' operand in parenthesis");
3009 if (parser->tok != '(') {
3010 parseerror(parser, "expected 'switch' operand in parenthesis");
3014 parser->breaks.push_back(label);
3016 rv = parse_switch_go(parser, block, out);
3019 if (parser->breaks.back() != label) {
3020 parseerror(parser, "internal error: label stack corrupted");
3026 parser->breaks.pop_back();
3031 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3033 ast_expression *operand;
3036 ast_switch *switchnode;
3037 ast_switch_case swcase;
3040 bool noref, is_static;
3041 uint32_t qflags = 0;
3043 lex_ctx_t ctx = parser_ctx(parser);
3045 (void)block; /* not touching */
3048 /* parse into the expression */
3049 if (!parser_next(parser)) {
3050 parseerror(parser, "expected switch operand");
3053 /* parse the operand */
3054 operand = parse_expression_leave(parser, false, false, false);
3058 switchnode = new ast_switch(ctx, operand);
3061 if (parser->tok != ')') {
3063 parseerror(parser, "expected closing paren after 'switch' operand");
3067 /* parse over the opening paren */
3068 if (!parser_next(parser) || parser->tok != '{') {
3070 parseerror(parser, "expected list of cases");
3074 if (!parser_next(parser)) {
3076 parseerror(parser, "expected 'case' or 'default'");
3080 /* new block; allow some variables to be declared here */
3081 parser_enterblock(parser);
3084 if (parser->tok == TOKEN_IDENT)
3085 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3086 if (typevar || parser->tok == TOKEN_TYPENAME) {
3087 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3093 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3095 if (cvq == CV_WRONG) {
3099 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3109 while (parser->tok != '}') {
3110 ast_block *caseblock;
3112 if (!strcmp(parser_tokval(parser), "case")) {
3113 if (!parser_next(parser)) {
3115 parseerror(parser, "expected expression for case");
3118 swcase.m_value = parse_expression_leave(parser, false, false, false);
3120 if (!operand->compareType(*swcase.m_value)) {
3124 ast_type_to_string(swcase.m_value, ty1, sizeof ty1);
3125 ast_type_to_string(operand, ty2, sizeof ty2);
3127 auto fnLiteral = [](ast_expression *expression) -> char* {
3128 if (!ast_istype(expression, ast_value))
3130 ast_value *value = (ast_value *)expression;
3131 if (!value->m_hasvalue)
3133 char *string = nullptr;
3134 basic_value_t *constval = &value->m_constval;
3135 switch (value->m_vtype)
3138 util_asprintf(&string, "%.2f", constval->vfloat);
3141 util_asprintf(&string, "'%.2f %.2f %.2f'",
3147 util_asprintf(&string, "\"%s\"", constval->vstring);
3155 char *literal = fnLiteral(swcase.m_value);
3157 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case `%s` expected `%s`", ty1, literal, ty2);
3159 compile_error(parser_ctx(parser), "incompatible type `%s` for switch case expected `%s`", ty1, ty2);
3165 if (!swcase.m_value) {
3167 parseerror(parser, "expected expression for case");
3170 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3171 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3172 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3178 else if (!strcmp(parser_tokval(parser), "default")) {
3179 swcase.m_value = nullptr;
3180 if (!parser_next(parser)) {
3182 parseerror(parser, "expected colon");
3188 parseerror(parser, "expected 'case' or 'default'");
3192 /* Now the colon and body */
3193 if (parser->tok != ':') {
3194 if (swcase.m_value) ast_unref(swcase.m_value);
3196 parseerror(parser, "expected colon");
3200 if (!parser_next(parser)) {
3201 if (swcase.m_value) ast_unref(swcase.m_value);
3203 parseerror(parser, "expected statements or case");
3206 caseblock = new ast_block(parser_ctx(parser));
3208 if (swcase.m_value) ast_unref(swcase.m_value);
3212 swcase.m_code = caseblock;
3213 switchnode->m_cases.push_back(swcase);
3215 ast_expression *expr;
3216 if (parser->tok == '}')
3218 if (parser->tok == TOKEN_KEYWORD) {
3219 if (!strcmp(parser_tokval(parser), "case") ||
3220 !strcmp(parser_tokval(parser), "default"))
3225 if (!parse_statement(parser, caseblock, &expr, true)) {
3231 if (!caseblock->addExpr(expr)) {
3238 parser_leaveblock(parser);
3241 if (parser->tok != '}') {
3243 parseerror(parser, "expected closing paren of case list");
3246 if (!parser_next(parser)) {
3248 parseerror(parser, "parse error after switch");
3255 /* parse computed goto sides */
3256 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3257 ast_expression *on_true;
3258 ast_expression *on_false;
3259 ast_expression *cond;
3264 if (ast_istype(*side, ast_ternary)) {
3265 ast_ternary *tern = (ast_ternary*)*side;
3266 on_true = parse_goto_computed(parser, &tern->m_on_true);
3267 on_false = parse_goto_computed(parser, &tern->m_on_false);
3269 if (!on_true || !on_false) {
3270 parseerror(parser, "expected label or expression in ternary");
3271 if (on_true) ast_unref(on_true);
3272 if (on_false) ast_unref(on_false);
3276 cond = tern->m_cond;
3277 tern->m_cond = nullptr;
3280 return new ast_ifthen(parser_ctx(parser), cond, on_true, on_false);
3281 } else if (ast_istype(*side, ast_label)) {
3282 ast_goto *gt = new ast_goto(parser_ctx(parser), ((ast_label*)*side)->m_name);
3283 gt->setLabel(reinterpret_cast<ast_label*>(*side));
3290 static bool parse_goto(parser_t *parser, ast_expression **out)
3292 ast_goto *gt = nullptr;
3293 ast_expression *lbl;
3295 if (!parser_next(parser))
3298 if (parser->tok != TOKEN_IDENT) {
3299 ast_expression *expression;
3301 /* could be an expression i.e computed goto :-) */
3302 if (parser->tok != '(') {
3303 parseerror(parser, "expected label name after `goto`");
3307 /* failed to parse expression for goto */
3308 if (!(expression = parse_expression(parser, false, true)) ||
3309 !(*out = parse_goto_computed(parser, &expression))) {
3310 parseerror(parser, "invalid goto expression");
3312 ast_unref(expression);
3319 /* not computed goto */
3320 gt = new ast_goto(parser_ctx(parser), parser_tokval(parser));
3321 lbl = parser_find_label(parser, gt->m_name);
3323 if (!ast_istype(lbl, ast_label)) {
3324 parseerror(parser, "internal error: label is not an ast_label");
3328 gt->setLabel(reinterpret_cast<ast_label*>(lbl));
3331 parser->gotos.push_back(gt);
3333 if (!parser_next(parser) || parser->tok != ';') {
3334 parseerror(parser, "semicolon expected after goto label");
3337 if (!parser_next(parser)) {
3338 parseerror(parser, "parse error after goto");
3346 static bool parse_skipwhite(parser_t *parser)
3349 if (!parser_next(parser))
3351 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3352 return parser->tok < TOKEN_ERROR;
3355 static bool parse_eol(parser_t *parser)
3357 if (!parse_skipwhite(parser))
3359 return parser->tok == TOKEN_EOL;
3362 static bool parse_pragma_do(parser_t *parser)
3364 if (!parser_next(parser) ||
3365 parser->tok != TOKEN_IDENT ||
3366 strcmp(parser_tokval(parser), "pragma"))
3368 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3371 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3372 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3376 if (!strcmp(parser_tokval(parser), "noref")) {
3377 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3378 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3381 parser->noref = !!parser_token(parser)->constval.i;
3382 if (!parse_eol(parser)) {
3383 parseerror(parser, "parse error after `noref` pragma");
3389 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3392 while (!parse_eol(parser)) {
3393 parser_next(parser);
3402 static bool parse_pragma(parser_t *parser)
3405 parser->lex->flags.preprocessing = true;
3406 parser->lex->flags.mergelines = true;
3407 rv = parse_pragma_do(parser);
3408 if (parser->tok != TOKEN_EOL) {
3409 parseerror(parser, "junk after pragma");
3412 parser->lex->flags.preprocessing = false;
3413 parser->lex->flags.mergelines = false;
3414 if (!parser_next(parser)) {
3415 parseerror(parser, "parse error after pragma");
3421 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3423 bool noref, is_static;
3425 uint32_t qflags = 0;
3426 ast_value *typevar = nullptr;
3427 char *vstring = nullptr;
3431 if (parser->tok == TOKEN_IDENT)
3432 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3434 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3436 /* local variable */
3438 parseerror(parser, "cannot declare a variable from here");
3441 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3442 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3445 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3449 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3451 if (cvq == CV_WRONG)
3453 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3455 else if (parser->tok == TOKEN_KEYWORD)
3457 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3462 if (!parser_next(parser)) {
3463 parseerror(parser, "parse error after __builtin_debug_printtype");
3467 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3469 ast_type_to_string(tdef, ty, sizeof(ty));
3470 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name.c_str(), ty);
3471 if (!parser_next(parser)) {
3472 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3478 if (!parse_statement(parser, block, out, allow_cases))
3481 con_out("__builtin_debug_printtype: got no output node\n");
3484 ast_type_to_string(*out, ty, sizeof(ty));
3485 con_out("__builtin_debug_printtype: `%s`\n", ty);
3490 else if (!strcmp(parser_tokval(parser), "return"))
3492 return parse_return(parser, block, out);
3494 else if (!strcmp(parser_tokval(parser), "if"))
3496 return parse_if(parser, block, out);
3498 else if (!strcmp(parser_tokval(parser), "while"))
3500 return parse_while(parser, block, out);
3502 else if (!strcmp(parser_tokval(parser), "do"))
3504 return parse_dowhile(parser, block, out);
3506 else if (!strcmp(parser_tokval(parser), "for"))
3508 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3509 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3512 return parse_for(parser, block, out);
3514 else if (!strcmp(parser_tokval(parser), "break"))
3516 return parse_break_continue(parser, block, out, false);
3518 else if (!strcmp(parser_tokval(parser), "continue"))
3520 return parse_break_continue(parser, block, out, true);
3522 else if (!strcmp(parser_tokval(parser), "switch"))
3524 return parse_switch(parser, block, out);
3526 else if (!strcmp(parser_tokval(parser), "case") ||
3527 !strcmp(parser_tokval(parser), "default"))
3530 parseerror(parser, "unexpected 'case' label");
3535 else if (!strcmp(parser_tokval(parser), "goto"))
3537 return parse_goto(parser, out);
3539 else if (!strcmp(parser_tokval(parser), "typedef"))
3541 if (!parser_next(parser)) {
3542 parseerror(parser, "expected type definition after 'typedef'");
3545 return parse_typedef(parser);
3547 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3550 else if (parser->tok == '{')
3553 inner = parse_block(parser);
3559 else if (parser->tok == ':')
3563 if (!parser_next(parser)) {
3564 parseerror(parser, "expected label name");
3567 if (parser->tok != TOKEN_IDENT) {
3568 parseerror(parser, "label must be an identifier");
3571 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3573 if (!label->m_undefined) {
3574 parseerror(parser, "label `%s` already defined", label->m_name);
3577 label->m_undefined = false;
3580 label = new ast_label(parser_ctx(parser), parser_tokval(parser), false);
3581 parser->labels.push_back(label);
3584 if (!parser_next(parser)) {
3585 parseerror(parser, "parse error after label");
3588 for (i = 0; i < parser->gotos.size(); ++i) {
3589 if (parser->gotos[i]->m_name == label->m_name) {
3590 parser->gotos[i]->setLabel(label);
3591 parser->gotos.erase(parser->gotos.begin() + i);
3597 else if (parser->tok == ';')
3599 if (!parser_next(parser)) {
3600 parseerror(parser, "parse error after empty statement");
3607 lex_ctx_t ctx = parser_ctx(parser);
3608 ast_expression *exp = parse_expression(parser, false, false);
3612 if (!exp->m_side_effects) {
3613 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3620 static bool parse_enum(parser_t *parser)
3623 bool reverse = false;
3625 ast_value *var = nullptr;
3627 std::vector<ast_value*> values;
3629 ast_expression *old;
3631 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3632 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3636 /* enumeration attributes (can add more later) */
3637 if (parser->tok == ':') {
3638 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3639 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3644 if (!strcmp(parser_tokval(parser), "flag")) {
3648 else if (!strcmp(parser_tokval(parser), "reverse")) {
3652 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3656 if (!parser_next(parser) || parser->tok != '{') {
3657 parseerror(parser, "expected `{` after enum attribute ");
3663 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3664 if (parser->tok == '}') {
3665 /* allow an empty enum */
3668 parseerror(parser, "expected identifier or `}`");
3672 old = parser_find_field(parser, parser_tokval(parser));
3674 old = parser_find_global(parser, parser_tokval(parser));
3676 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3677 parser_tokval(parser), old->m_context.file, old->m_context.line);
3681 var = new ast_value(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3682 values.push_back(var);
3683 var->m_cvq = CV_CONST;
3684 var->m_hasvalue = true;
3686 /* for flagged enumerations increment in POTs of TWO */
3687 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3688 parser_addglobal(parser, var->m_name, var);
3690 if (!parser_next(parser)) {
3691 parseerror(parser, "expected `=`, `}` or comma after identifier");
3695 if (parser->tok == ',')
3697 if (parser->tok == '}')
3699 if (parser->tok != '=') {
3700 parseerror(parser, "expected `=`, `}` or comma after identifier");
3704 if (!parser_next(parser)) {
3705 parseerror(parser, "expected expression after `=`");
3709 /* We got a value! */
3710 old = parse_expression_leave(parser, true, false, false);
3711 asvalue = (ast_value*)old;
3712 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3713 compile_error(var->m_context, "constant value or expression expected");
3716 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3718 if (parser->tok == '}')
3720 if (parser->tok != ',') {
3721 parseerror(parser, "expected `}` or comma after expression");
3726 /* patch them all (for reversed attribute) */
3729 for (i = 0; i < values.size(); i++)
3730 values[i]->m_constval.vfloat = values.size() - i - 1;
3733 if (parser->tok != '}') {
3734 parseerror(parser, "internal error: breaking without `}`");
3738 if (!parser_next(parser) || parser->tok != ';') {
3739 parseerror(parser, "expected semicolon after enumeration");
3743 if (!parser_next(parser)) {
3744 parseerror(parser, "parse error after enumeration");
3751 static bool parse_block_into(parser_t *parser, ast_block *block)
3755 parser_enterblock(parser);
3757 if (!parser_next(parser)) { /* skip the '{' */
3758 parseerror(parser, "expected function body");
3762 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3764 ast_expression *expr = nullptr;
3765 if (parser->tok == '}')
3768 if (!parse_statement(parser, block, &expr, false)) {
3769 /* parseerror(parser, "parse error"); */
3775 if (!block->addExpr(expr)) {
3782 if (parser->tok != '}') {
3785 (void)parser_next(parser);
3789 if (!parser_leaveblock(parser))
3791 return retval && !!block;
3794 static ast_block* parse_block(parser_t *parser)
3797 block = new ast_block(parser_ctx(parser));
3800 if (!parse_block_into(parser, block)) {
3807 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3809 if (parser->tok == '{') {
3810 *out = parse_block(parser);
3813 return parse_statement(parser, nullptr, out, false);
3816 static bool create_vector_members(ast_value *var, ast_member **me)
3819 size_t len = var->m_name.length();
3821 for (i = 0; i < 3; ++i) {
3822 char *name = (char*)mem_a(len+3);
3823 memcpy(name, var->m_name.c_str(), len);
3825 name[len+1] = 'x'+i;
3827 me[i] = ast_member::make(var->m_context, var, i, name);
3836 do { delete me[--i]; } while(i);
3840 static bool parse_function_body(parser_t *parser, ast_value *var)
3842 ast_block *block = nullptr;
3846 ast_expression *framenum = nullptr;
3847 ast_expression *nextthink = nullptr;
3848 /* None of the following have to be deleted */
3849 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3850 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3851 bool has_frame_think;
3855 has_frame_think = false;
3856 old = parser->function;
3858 if (var->m_flags & AST_FLAG_ALIAS) {
3859 parseerror(parser, "function aliases cannot have bodies");
3863 if (parser->gotos.size() || parser->labels.size()) {
3864 parseerror(parser, "gotos/labels leaking");
3868 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3869 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3870 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3876 if (parser->tok == '[') {
3877 /* got a frame definition: [ framenum, nextthink ]
3878 * this translates to:
3879 * self.frame = framenum;
3880 * self.nextthink = time + 0.1;
3881 * self.think = nextthink;
3883 nextthink = nullptr;
3885 fld_think = parser_find_field(parser, "think");
3886 fld_nextthink = parser_find_field(parser, "nextthink");
3887 fld_frame = parser_find_field(parser, "frame");
3888 if (!fld_think || !fld_nextthink || !fld_frame) {
3889 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3890 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3893 gbl_time = parser_find_global(parser, "time");
3894 gbl_self = parser_find_global(parser, "self");
3895 if (!gbl_time || !gbl_self) {
3896 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3897 parseerror(parser, "please declare the following globals: `time`, `self`");
3901 if (!parser_next(parser))
3904 framenum = parse_expression_leave(parser, true, false, false);
3906 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3909 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3910 ast_unref(framenum);
3911 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3915 if (parser->tok != ',') {
3916 ast_unref(framenum);
3917 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3918 parseerror(parser, "Got a %i\n", parser->tok);
3922 if (!parser_next(parser)) {
3923 ast_unref(framenum);
3927 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3929 /* qc allows the use of not-yet-declared functions here
3930 * - this automatically creates a prototype */
3931 ast_value *thinkfunc;
3932 ast_expression *functype = fld_think->m_next;
3934 thinkfunc = new ast_value(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3935 if (!thinkfunc) { /* || !thinkfunc->adoptType(*functype)*/
3936 ast_unref(framenum);
3937 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3940 thinkfunc->adoptType(*functype);
3942 if (!parser_next(parser)) {
3943 ast_unref(framenum);
3948 parser_addglobal(parser, thinkfunc->m_name, thinkfunc);
3950 nextthink = thinkfunc;
3953 nextthink = parse_expression_leave(parser, true, false, false);
3955 ast_unref(framenum);
3956 parseerror(parser, "expected a think-function in [frame,think] notation");
3961 if (!ast_istype(nextthink, ast_value)) {
3962 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3966 if (retval && parser->tok != ']') {
3967 parseerror(parser, "expected closing `]` for [frame,think] notation");
3971 if (retval && !parser_next(parser)) {
3975 if (retval && parser->tok != '{') {
3976 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3981 ast_unref(nextthink);
3982 ast_unref(framenum);
3986 has_frame_think = true;
3989 block = new ast_block(parser_ctx(parser));
3991 parseerror(parser, "failed to allocate block");
3992 if (has_frame_think) {
3993 ast_unref(nextthink);
3994 ast_unref(framenum);
3999 if (has_frame_think) {
4000 if (!OPTS_FLAG(EMULATE_STATE)) {
4001 ast_state *state_op = new ast_state(parser_ctx(parser), framenum, nextthink);
4002 if (!block->addExpr(state_op)) {
4003 parseerror(parser, "failed to generate state op for [frame,think]");
4004 ast_unref(nextthink);
4005 ast_unref(framenum);
4010 /* emulate OP_STATE in code: */
4012 ast_expression *self_frame;
4013 ast_expression *self_nextthink;
4014 ast_expression *self_think;
4015 ast_expression *time_plus_1;
4016 ast_store *store_frame;
4017 ast_store *store_nextthink;
4018 ast_store *store_think;
4020 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
4022 ctx = parser_ctx(parser);
4023 self_frame = new ast_entfield(ctx, gbl_self, fld_frame);
4024 self_nextthink = new ast_entfield(ctx, gbl_self, fld_nextthink);
4025 self_think = new ast_entfield(ctx, gbl_self, fld_think);
4027 time_plus_1 = new ast_binary(ctx, INSTR_ADD_F,
4028 gbl_time, parser->m_fold.constgen_float(frame_delta, false));
4030 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4031 if (self_frame) delete self_frame;
4032 if (self_nextthink) delete self_nextthink;
4033 if (self_think) delete self_think;
4034 if (time_plus_1) delete time_plus_1;
4040 store_frame = new ast_store(ctx, INSTR_STOREP_F, self_frame, framenum);
4041 store_nextthink = new ast_store(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4042 store_think = new ast_store(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4048 if (!store_nextthink) {
4049 delete self_nextthink;
4057 if (store_frame) delete store_frame;
4058 if (store_nextthink) delete store_nextthink;
4059 if (store_think) delete store_think;
4062 if (!block->addExpr(store_frame) ||
4063 !block->addExpr(store_nextthink) ||
4064 !block->addExpr(store_think))