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_addglobal(parser_t *parser, const char *name, ast_expression *e);
17 static bool parse_typedef(parser_t *parser);
18 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);
19 static ast_block* parse_block(parser_t *parser);
20 static bool parse_block_into(parser_t *parser, ast_block *block);
21 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
22 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
23 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
24 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
25 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
26 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
27 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
29 static void parseerror(parser_t *parser, const char *fmt, ...)
33 vcompile_error(parser->lex->tok.ctx, fmt, ap);
37 /* returns true if it counts as an error */
38 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
43 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
48 /**********************************************************************
52 static bool parser_next(parser_t *parser)
54 /* lex_do kills the previous token */
55 parser->tok = lex_do(parser->lex);
56 if (parser->tok == TOKEN_EOF)
58 if (parser->tok >= TOKEN_ERROR) {
59 parseerror(parser, "lex error");
65 #define parser_tokval(p) ((p)->lex->tok.value)
66 #define parser_token(p) (&((p)->lex->tok))
68 char *parser_strdup(const char *str)
71 /* actually dup empty strings */
72 char *out = (char*)mem_a(1);
76 return util_strdup(str);
79 static ast_expression* parser_find_field(parser_t *parser, const char *name)
81 return ( ast_expression*)util_htget(parser->htfields, name);
84 static ast_expression* parser_find_label(parser_t *parser, const char *name)
86 for (auto &it : parser->labels)
87 if (!strcmp(it->m_name, name))
88 return (ast_expression*)it;
92 ast_expression* parser_find_global(parser_t *parser, const char *name)
94 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
97 return (ast_expression*)util_htget(parser->htglobals, name);
100 static ast_expression* parser_find_param(parser_t *parser, const char *name)
103 if (!parser->function)
105 fun = parser->function->m_function_type;
106 for (auto &it : fun->m_type_params) {
107 if (!strcmp(it->m_name, name))
108 return (ast_expression*)it;
113 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
118 hash = util_hthash(parser->htglobals, name);
121 for (i = vec_size(parser->variables); i > upto;) {
123 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
127 return parser_find_param(parser, name);
130 static ast_expression* parser_find_var(parser_t *parser, const char *name)
134 v = parser_find_local(parser, name, 0, &dummy);
135 if (!v) v = parser_find_global(parser, name);
139 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
143 hash = util_hthash(parser->typedefs[0], name);
145 for (i = vec_size(parser->typedefs); i > upto;) {
147 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
154 size_t etype; /* 0 = expression, others are operators */
158 ast_block *block; /* for commas and function calls */
171 std::vector<sy_elem> out;
172 std::vector<sy_elem> ops;
173 std::vector<size_t> argc;
174 std::vector<unsigned int> paren;
177 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
188 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
192 e.out = (ast_expression*)v;
199 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
201 e.etype = 1 + (op - operators);
210 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
221 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
222 * so we need to rotate it to become ent.(foo[n]).
224 static bool rotate_entfield_array_index_nodes(ast_expression **out)
226 ast_array_index *index, *oldindex;
227 ast_entfield *entfield;
231 ast_expression *entity;
233 lex_ctx_t ctx = (*out)->m_context;
235 if (!ast_istype(*out, ast_array_index))
237 index = (ast_array_index*)*out;
239 if (!ast_istype(index->m_array, ast_entfield))
241 entfield = (ast_entfield*)index->m_array;
243 if (!ast_istype(entfield->m_field, ast_value))
245 field = (ast_value*)entfield->m_field;
247 sub = index->m_index;
248 entity = entfield->m_entity;
252 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
253 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
254 *out = (ast_expression*)entfield;
256 oldindex->m_array = nullptr;
257 oldindex->m_index = nullptr;
258 ast_delete(oldindex);
263 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
265 if (ast_istype(expr, ast_value)) {
266 ast_value *val = (ast_value*)expr;
267 if (val->m_cvq == CV_CONST) {
268 if (val->m_name[0] == '#') {
269 compile_error(ctx, "invalid assignment to a literal constant");
273 * To work around quakeworld we must elide the error and make it
276 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
277 compile_error(ctx, "assignment to constant `%s`", val->m_name);
279 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->m_name);
286 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
290 ast_expression *out = nullptr;
291 ast_expression *exprs[3];
292 ast_block *blocks[3];
293 ast_binstore *asbinstore;
294 size_t i, assignop, addop, subop;
295 qcint_t generated_op = 0;
300 if (sy->ops.empty()) {
301 parseerror(parser, "internal error: missing operator");
305 if (sy->ops.back().isparen) {
306 parseerror(parser, "unmatched parenthesis");
310 op = &operators[sy->ops.back().etype - 1];
311 ctx = sy->ops.back().ctx;
313 if (sy->out.size() < op->operands) {
314 if (op->flags & OP_PREFIX)
315 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
316 else /* this should have errored previously already */
317 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
323 /* op(:?) has no input and no output */
327 sy->out.erase(sy->out.end() - op->operands, sy->out.end());
328 for (i = 0; i < op->operands; ++i) {
329 exprs[i] = sy->out[sy->out.size()+i].out;
330 blocks[i] = sy->out[sy->out.size()+i].block;
332 if (exprs[i]->m_vtype == TYPE_NOEXPR &&
333 !(i != 0 && op->id == opid2('?',':')) &&
334 !(i == 1 && op->id == opid1('.')))
336 if (ast_istype(exprs[i], ast_label))
337 compile_error(exprs[i]->m_context, "expected expression, got an unknown identifier");
339 compile_error(exprs[i]->m_context, "not an expression");
340 (void)!compile_warning(exprs[i]->m_context, WARN_DEBUG, "expression %u\n", (unsigned int)i);
344 if (blocks[0] && blocks[0]->m_exprs.empty() && op->id != opid1(',')) {
345 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
349 #define NotSameType(T) \
350 (exprs[0]->m_vtype != exprs[1]->m_vtype || \
351 exprs[0]->m_vtype != T)
356 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
360 if (exprs[0]->m_vtype == TYPE_VECTOR &&
361 exprs[1]->m_vtype == TYPE_NOEXPR)
363 if (exprs[1] == (ast_expression*)parser->const_vec[0])
364 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, nullptr);
365 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
366 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, nullptr);
367 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
368 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, nullptr);
370 compile_error(ctx, "access to invalid vector component");
374 else if (exprs[0]->m_vtype == TYPE_ENTITY) {
375 if (exprs[1]->m_vtype != TYPE_FIELD) {
376 compile_error(exprs[1]->m_context, "type error: right hand of member-operand should be an entity-field");
379 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
381 else if (exprs[0]->m_vtype == TYPE_VECTOR) {
382 compile_error(exprs[1]->m_context, "vectors cannot be accessed this way");
386 compile_error(exprs[1]->m_context, "type error: member-of operator on something that is not an entity or vector");
392 if (exprs[0]->m_vtype != TYPE_ARRAY &&
393 !(exprs[0]->m_vtype == TYPE_FIELD &&
394 exprs[0]->m_next->m_vtype == TYPE_ARRAY))
396 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
397 compile_error(exprs[0]->m_context, "cannot index value of type %s", ty1);
400 if (exprs[1]->m_vtype != TYPE_FLOAT) {
401 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
402 compile_error(exprs[1]->m_context, "index must be of type float, not %s", ty1);
405 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
406 rotate_entfield_array_index_nodes(&out);
410 if (sy->paren.size() && sy->paren.back() == PAREN_FUNC) {
411 sy->out.push_back(syexp(ctx, exprs[0]));
412 sy->out.push_back(syexp(ctx, exprs[1]));
417 if (!ast_block_add_expr(blocks[0], exprs[1]))
420 blocks[0] = ast_block_new(ctx);
421 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
422 !ast_block_add_expr(blocks[0], exprs[1]))
427 ast_block_set_type(blocks[0], exprs[1]);
429 sy->out.push_back(syblock(ctx, blocks[0]));
436 if ((out = parser->m_fold.op(op, exprs)))
439 if (exprs[0]->m_vtype != TYPE_FLOAT &&
440 exprs[0]->m_vtype != TYPE_VECTOR) {
441 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
442 type_name[exprs[0]->m_vtype]);
445 if (exprs[0]->m_vtype == TYPE_FLOAT)
446 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
448 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
452 if (!(out = parser->m_fold.op(op, exprs))) {
453 switch (exprs[0]->m_vtype) {
455 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
458 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
461 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
462 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
464 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
466 /* we don't constant-fold NOT for these types */
468 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
471 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
474 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
475 type_name[exprs[0]->m_vtype]);
482 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
483 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
485 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
486 type_name[exprs[0]->m_vtype],
487 type_name[exprs[1]->m_vtype]);
490 if (!(out = parser->m_fold.op(op, exprs))) {
491 switch (exprs[0]->m_vtype) {
493 out = fold::binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
496 out = fold::binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
499 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
500 type_name[exprs[0]->m_vtype],
501 type_name[exprs[1]->m_vtype]);
507 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
508 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT))
510 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
511 type_name[exprs[1]->m_vtype],
512 type_name[exprs[0]->m_vtype]);
515 if (!(out = parser->m_fold.op(op, exprs))) {
516 switch (exprs[0]->m_vtype) {
518 out = fold::binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
521 out = fold::binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
524 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
525 type_name[exprs[1]->m_vtype],
526 type_name[exprs[0]->m_vtype]);
532 if (exprs[0]->m_vtype != exprs[1]->m_vtype &&
533 !(exprs[0]->m_vtype == TYPE_VECTOR &&
534 exprs[1]->m_vtype == TYPE_FLOAT) &&
535 !(exprs[1]->m_vtype == TYPE_VECTOR &&
536 exprs[0]->m_vtype == TYPE_FLOAT)
539 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
540 type_name[exprs[1]->m_vtype],
541 type_name[exprs[0]->m_vtype]);
544 if (!(out = parser->m_fold.op(op, exprs))) {
545 switch (exprs[0]->m_vtype) {
547 if (exprs[1]->m_vtype == TYPE_VECTOR)
548 out = fold::binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
550 out = fold::binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
553 if (exprs[1]->m_vtype == TYPE_FLOAT)
554 out = fold::binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
556 out = fold::binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
559 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
560 type_name[exprs[1]->m_vtype],
561 type_name[exprs[0]->m_vtype]);
568 if (exprs[1]->m_vtype != TYPE_FLOAT) {
569 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
570 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
571 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
574 if (!(out = parser->m_fold.op(op, exprs))) {
575 if (exprs[0]->m_vtype == TYPE_FLOAT)
576 out = fold::binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
578 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
579 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
580 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
587 if (NotSameType(TYPE_FLOAT)) {
588 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
589 type_name[exprs[0]->m_vtype],
590 type_name[exprs[1]->m_vtype]);
592 } else if (!(out = parser->m_fold.op(op, exprs))) {
593 /* generate a call to __builtin_mod */
594 ast_expression *mod = parser->m_intrin.func("mod");
595 ast_call *call = nullptr;
596 if (!mod) return false; /* can return null for missing floor */
598 call = ast_call_new(parser_ctx(parser), mod);
599 call->m_params.push_back(exprs[0]);
600 call->m_params.push_back(exprs[1]);
602 out = (ast_expression*)call;
607 compile_error(ctx, "%= is unimplemented");
613 if ( !(exprs[0]->m_vtype == TYPE_FLOAT && exprs[1]->m_vtype == TYPE_FLOAT) &&
614 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_FLOAT) &&
615 !(exprs[0]->m_vtype == TYPE_VECTOR && exprs[1]->m_vtype == TYPE_VECTOR))
617 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
618 type_name[exprs[0]->m_vtype],
619 type_name[exprs[1]->m_vtype]);
623 if (!(out = parser->m_fold.op(op, exprs))) {
625 * IF the first expression is float, the following will be too
626 * since scalar ^ vector is not allowed.
628 if (exprs[0]->m_vtype == TYPE_FLOAT) {
629 out = fold::binary(ctx,
630 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
634 * The first is a vector: vector is allowed to bitop with vector and
635 * with scalar, branch here for the second operand.
637 if (exprs[1]->m_vtype == TYPE_VECTOR) {
639 * Bitop all the values of the vector components against the
640 * vectors components in question.
642 out = fold::binary(ctx,
643 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
646 out = fold::binary(ctx,
647 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
656 if (NotSameType(TYPE_FLOAT)) {
657 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
658 type_name[exprs[0]->m_vtype],
659 type_name[exprs[1]->m_vtype]);
663 if (!(out = parser->m_fold.op(op, exprs))) {
664 ast_expression *shift = parser->m_intrin.func((op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
665 ast_call *call = ast_call_new(parser_ctx(parser), shift);
666 call->m_params.push_back(exprs[0]);
667 call->m_params.push_back(exprs[1]);
668 out = (ast_expression*)call;
672 case opid3('<','<','='):
673 case opid3('>','>','='):
674 if (NotSameType(TYPE_FLOAT)) {
675 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
676 type_name[exprs[0]->m_vtype],
677 type_name[exprs[1]->m_vtype]);
681 if(!(out = parser->m_fold.op(op, exprs))) {
682 ast_expression *shift = parser->m_intrin.func((op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
683 ast_call *call = ast_call_new(parser_ctx(parser), shift);
684 call->m_params.push_back(exprs[0]);
685 call->m_params.push_back(exprs[1]);
686 out = (ast_expression*)ast_store_new(
690 (ast_expression*)call
697 generated_op += 1; /* INSTR_OR */
699 generated_op += INSTR_AND;
700 if (!(out = parser->m_fold.op(op, exprs))) {
701 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
702 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
703 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
704 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
707 for (i = 0; i < 2; ++i) {
708 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->m_vtype == TYPE_VECTOR) {
709 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
711 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
713 exprs[i] = out; out = nullptr;
714 if (OPTS_FLAG(PERL_LOGIC)) {
715 /* here we want to keep the right expressions' type */
719 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->m_vtype == TYPE_STRING) {
720 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
724 exprs[i] = out; out = nullptr;
725 if (OPTS_FLAG(PERL_LOGIC)) {
726 /* here we want to keep the right expressions' type */
731 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
736 if (sy->paren.back() != PAREN_TERNARY2) {
737 compile_error(ctx, "mismatched parenthesis/ternary");
740 sy->paren.pop_back();
741 if (!ast_compare_type(exprs[1], exprs[2])) {
742 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
743 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
744 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
747 if (!(out = parser->m_fold.op(op, exprs)))
748 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
751 case opid2('*', '*'):
752 if (NotSameType(TYPE_FLOAT)) {
753 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
754 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
755 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
760 if (!(out = parser->m_fold.op(op, exprs))) {
761 ast_call *gencall = ast_call_new(parser_ctx(parser), parser->m_intrin.func("pow"));
762 gencall->m_params.push_back(exprs[0]);
763 gencall->m_params.push_back(exprs[1]);
764 out = (ast_expression*)gencall;
768 case opid2('>', '<'):
769 if (NotSameType(TYPE_VECTOR)) {
770 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
771 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
772 compile_error(ctx, "invalid types used in cross product: %s and %s",
777 if (!(out = parser->m_fold.op(op, exprs))) {
788 case opid3('<','=','>'): /* -1, 0, or 1 */
789 if (NotSameType(TYPE_FLOAT)) {
790 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
791 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
792 compile_error(ctx, "invalid types used in comparision: %s and %s",
798 if (!(out = parser->m_fold.op(op, exprs))) {
799 /* This whole block is NOT fold_binary safe */
800 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
802 eq->m_refs = AST_REF_NONE;
805 out = (ast_expression*)ast_ternary_new(ctx,
806 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
808 (ast_expression*)parser->m_fold.imm_float(2),
811 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
813 (ast_expression*)parser->m_fold.imm_float(0),
816 (ast_expression*)parser->m_fold.imm_float(1)
826 generated_op += 1; /* INSTR_GT */
828 generated_op += 1; /* INSTR_LT */
829 case opid2('>', '='):
830 generated_op += 1; /* INSTR_GE */
831 case opid2('<', '='):
832 generated_op += INSTR_LE;
833 if (NotSameType(TYPE_FLOAT)) {
834 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
835 type_name[exprs[0]->m_vtype],
836 type_name[exprs[1]->m_vtype]);
839 if (!(out = parser->m_fold.op(op, exprs)))
840 out = fold::binary(ctx, generated_op, exprs[0], exprs[1]);
842 case opid2('!', '='):
843 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
844 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
845 type_name[exprs[0]->m_vtype],
846 type_name[exprs[1]->m_vtype]);
849 if (!(out = parser->m_fold.op(op, exprs)))
850 out = fold::binary(ctx, type_ne_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
852 case opid2('=', '='):
853 if (exprs[0]->m_vtype != exprs[1]->m_vtype) {
854 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
855 type_name[exprs[0]->m_vtype],
856 type_name[exprs[1]->m_vtype]);
859 if (!(out = parser->m_fold.op(op, exprs)))
860 out = fold::binary(ctx, type_eq_instr[exprs[0]->m_vtype], exprs[0], exprs[1]);
864 if (ast_istype(exprs[0], ast_entfield)) {
865 ast_expression *field = ((ast_entfield*)exprs[0])->m_field;
866 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
867 exprs[0]->m_vtype == TYPE_FIELD &&
868 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
870 assignop = type_storep_instr[TYPE_VECTOR];
873 assignop = type_storep_instr[exprs[0]->m_vtype];
874 if (assignop == VINSTR_END || !ast_compare_type(field->m_next, exprs[1]))
876 ast_type_to_string(field->m_next, ty1, sizeof(ty1));
877 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
878 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
879 field->m_next->m_vtype == TYPE_FUNCTION &&
880 exprs[1]->m_vtype == TYPE_FUNCTION)
882 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
883 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
886 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
891 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
892 exprs[0]->m_vtype == TYPE_FIELD &&
893 exprs[0]->m_next->m_vtype == TYPE_VECTOR)
895 assignop = type_store_instr[TYPE_VECTOR];
898 assignop = type_store_instr[exprs[0]->m_vtype];
901 if (assignop == VINSTR_END) {
902 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
903 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
904 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
906 else if (!ast_compare_type(exprs[0], exprs[1]))
908 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
909 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
910 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
911 exprs[0]->m_vtype == TYPE_FUNCTION &&
912 exprs[1]->m_vtype == TYPE_FUNCTION)
914 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
915 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
918 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
921 (void)check_write_to(ctx, exprs[0]);
922 /* When we're a vector of part of an entity field we use STOREP */
923 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->m_owner, ast_entfield))
924 assignop = INSTR_STOREP_F;
925 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
927 case opid3('+','+','P'):
928 case opid3('-','-','P'):
930 if (exprs[0]->m_vtype != TYPE_FLOAT) {
931 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
932 compile_error(exprs[0]->m_context, "invalid type for prefix increment: %s", ty1);
935 if (op->id == opid3('+','+','P'))
939 (void)check_write_to(exprs[0]->m_context, exprs[0]);
940 if (ast_istype(exprs[0], ast_entfield)) {
941 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
943 (ast_expression*)parser->m_fold.imm_float(1));
945 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
947 (ast_expression*)parser->m_fold.imm_float(1));
950 case opid3('S','+','+'):
951 case opid3('S','-','-'):
953 if (exprs[0]->m_vtype != TYPE_FLOAT) {
954 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
955 compile_error(exprs[0]->m_context, "invalid type for suffix increment: %s", ty1);
958 if (op->id == opid3('S','+','+')) {
965 (void)check_write_to(exprs[0]->m_context, exprs[0]);
966 if (ast_istype(exprs[0], ast_entfield)) {
967 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
969 (ast_expression*)parser->m_fold.imm_float(1));
971 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
973 (ast_expression*)parser->m_fold.imm_float(1));
977 out = fold::binary(ctx, subop,
979 (ast_expression*)parser->m_fold.imm_float(1));
984 if (exprs[0]->m_vtype != exprs[1]->m_vtype ||
985 (exprs[0]->m_vtype != TYPE_VECTOR && exprs[0]->m_vtype != TYPE_FLOAT) )
987 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
988 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
989 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
993 (void)check_write_to(ctx, exprs[0]);
994 if (ast_istype(exprs[0], ast_entfield))
995 assignop = type_storep_instr[exprs[0]->m_vtype];
997 assignop = type_store_instr[exprs[0]->m_vtype];
998 switch (exprs[0]->m_vtype) {
1000 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1001 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1002 exprs[0], exprs[1]);
1005 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1006 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1007 exprs[0], exprs[1]);
1010 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1011 type_name[exprs[0]->m_vtype],
1012 type_name[exprs[1]->m_vtype]);
1016 case opid2('*','='):
1017 case opid2('/','='):
1018 if (exprs[1]->m_vtype != TYPE_FLOAT ||
1019 !(exprs[0]->m_vtype == TYPE_FLOAT ||
1020 exprs[0]->m_vtype == TYPE_VECTOR))
1022 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1023 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1024 compile_error(ctx, "invalid types used in expression: %s and %s",
1028 (void)check_write_to(ctx, exprs[0]);
1029 if (ast_istype(exprs[0], ast_entfield))
1030 assignop = type_storep_instr[exprs[0]->m_vtype];
1032 assignop = type_store_instr[exprs[0]->m_vtype];
1033 switch (exprs[0]->m_vtype) {
1035 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1036 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1037 exprs[0], exprs[1]);
1040 if (op->id == opid2('*','=')) {
1041 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1042 exprs[0], exprs[1]);
1044 out = fold::binary(ctx, INSTR_DIV_F,
1045 (ast_expression*)parser->m_fold.imm_float(1),
1048 compile_error(ctx, "internal error: failed to generate division");
1051 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1056 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1057 type_name[exprs[0]->m_vtype],
1058 type_name[exprs[1]->m_vtype]);
1062 case opid2('&','='):
1063 case opid2('|','='):
1064 case opid2('^','='):
1065 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1066 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1067 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1068 compile_error(ctx, "invalid types used in expression: %s and %s",
1072 (void)check_write_to(ctx, exprs[0]);
1073 if (ast_istype(exprs[0], ast_entfield))
1074 assignop = type_storep_instr[exprs[0]->m_vtype];
1076 assignop = type_store_instr[exprs[0]->m_vtype];
1077 if (exprs[0]->m_vtype == TYPE_FLOAT)
1078 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1079 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1080 exprs[0], exprs[1]);
1082 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1083 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1084 exprs[0], exprs[1]);
1086 case opid3('&','~','='):
1087 /* This is like: a &= ~(b);
1088 * But QC has no bitwise-not, so we implement it as
1091 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1092 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1094 compile_error(ctx, "invalid types used in expression: %s and %s",
1098 if (ast_istype(exprs[0], ast_entfield))
1099 assignop = type_storep_instr[exprs[0]->m_vtype];
1101 assignop = type_store_instr[exprs[0]->m_vtype];
1102 if (exprs[0]->m_vtype == TYPE_FLOAT)
1103 out = fold::binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1105 out = fold::binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1108 (void)check_write_to(ctx, exprs[0]);
1109 if (exprs[0]->m_vtype == TYPE_FLOAT)
1110 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1112 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1113 asbinstore->m_keep_dest = true;
1114 out = (ast_expression*)asbinstore;
1117 case opid3('l', 'e', 'n'):
1118 if (exprs[0]->m_vtype != TYPE_STRING && exprs[0]->m_vtype != TYPE_ARRAY) {
1119 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1120 compile_error(exprs[0]->m_context, "invalid type for length operator: %s", ty1);
1123 /* strings must be const, arrays are statically sized */
1124 if (exprs[0]->m_vtype == TYPE_STRING &&
1125 !(((ast_value*)exprs[0])->m_hasvalue && ((ast_value*)exprs[0])->m_cvq == CV_CONST))
1127 compile_error(exprs[0]->m_context, "operand of length operator not a valid constant expression");
1130 out = parser->m_fold.op(op, exprs);
1133 case opid2('~', 'P'):
1134 if (exprs[0]->m_vtype != TYPE_FLOAT && exprs[0]->m_vtype != TYPE_VECTOR) {
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 compile_error(exprs[0]->m_context, "invalid type for bit not: %s", ty1);
1139 if (!(out = parser->m_fold.op(op, exprs))) {
1140 if (exprs[0]->m_vtype == TYPE_FLOAT) {
1141 out = fold::binary(ctx, INSTR_SUB_F, (ast_expression*)parser->m_fold.imm_float(2), exprs[0]);
1143 out = fold::binary(ctx, INSTR_SUB_V, (ast_expression*)parser->m_fold.imm_vector(1), exprs[0]);
1150 compile_error(ctx, "failed to apply operator %s", op->op);
1154 sy->out.push_back(syexp(ctx, out));
1158 static bool parser_close_call(parser_t *parser, shunt *sy)
1160 /* was a function call */
1161 ast_expression *fun;
1162 ast_value *funval = nullptr;
1166 size_t paramcount, i;
1169 fid = sy->ops.back().off;
1172 /* out[fid] is the function
1173 * everything above is parameters...
1175 if (sy->argc.empty()) {
1176 parseerror(parser, "internal error: no argument counter available");
1180 paramcount = sy->argc.back();
1181 sy->argc.pop_back();
1183 if (sy->out.size() < fid) {
1184 parseerror(parser, "internal error: broken function call %zu < %zu+%zu\n",
1192 * TODO handle this at the intrinsic level with an ast_intrinsic
1195 if ((fun = sy->out[fid].out) == parser->m_intrin.debug_typestring()) {
1197 if (fid+2 != sy->out.size() || sy->out.back().block) {
1198 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1201 ast_type_to_string(sy->out.back().out, ty, sizeof(ty));
1202 ast_unref(sy->out.back().out);
1203 sy->out[fid] = syexp(sy->out.back().out->m_context,
1204 (ast_expression*)parser->m_fold.constgen_string(ty, false));
1210 * Now we need to determine if the function that is being called is
1211 * an intrinsic so we can evaluate if the arguments to it are constant
1212 * and than fruitfully fold them.
1214 #define fold_can_1(X) \
1215 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->m_hasvalue && ((X)->m_cvq == CV_CONST) && \
1216 ((ast_expression*)(X))->m_vtype != TYPE_FUNCTION)
1218 if (fid + 1 < sy->out.size())
1221 for (i = 0; i < paramcount; ++i) {
1222 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1229 * All is well which ends well, if we make it into here we can ignore the
1230 * intrinsic call and just evaluate it i.e constant fold it.
1232 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->m_intrinsic) {
1233 ast_expression **exprs = nullptr;
1234 ast_expression *foldval = nullptr;
1236 for (i = 0; i < paramcount; i++)
1237 vec_push(exprs, sy->out[fid+1 + i].out);
1239 if (!(foldval = parser->m_intrin.do_fold((ast_value*)fun, exprs))) {
1245 * Blub: what sorts of unreffing and resizing of
1246 * sy->out should I be doing here?
1248 sy->out[fid] = syexp(foldval->m_context, foldval);
1249 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1256 call = ast_call_new(sy->ops[sy->ops.size()].ctx, fun);
1261 if (fid+1 + paramcount != sy->out.size()) {
1262 parseerror(parser, "internal error: parameter count mismatch: (%zu+1+%zu), %zu",
1269 for (i = 0; i < paramcount; ++i)
1270 call->m_params.push_back(sy->out[fid+1 + i].out);
1271 sy->out.erase(sy->out.end() - paramcount, sy->out.end());
1272 (void)!ast_call_check_types(call, parser->function->m_function_type->m_varparam);
1273 if (parser->max_param_count < paramcount)
1274 parser->max_param_count = paramcount;
1276 if (ast_istype(fun, ast_value)) {
1277 funval = (ast_value*)fun;
1278 if ((fun->m_flags & AST_FLAG_VARIADIC) &&
1279 !(/*funval->m_cvq == CV_CONST && */ funval->m_hasvalue && funval->m_constval.vfunc->m_builtin))
1281 call->m_va_count = (ast_expression*)parser->m_fold.constgen_float((qcfloat_t)paramcount, false);
1285 /* overwrite fid, the function, with a call */
1286 sy->out[fid] = syexp(call->m_context, (ast_expression*)call);
1288 if (fun->m_vtype != TYPE_FUNCTION) {
1289 parseerror(parser, "not a function (%s)", type_name[fun->m_vtype]);
1294 parseerror(parser, "could not determine function return type");
1297 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : nullptr);
1299 if (fun->m_flags & AST_FLAG_DEPRECATED) {
1301 return !parsewarning(parser, WARN_DEPRECATED,
1302 "call to function (which is marked deprecated)\n",
1303 "-> it has been declared here: %s:%i",
1304 fun->m_context.file, fun->m_context.line);
1306 if (!fval->m_desc) {
1307 return !parsewarning(parser, WARN_DEPRECATED,
1308 "call to `%s` (which is marked deprecated)\n"
1309 "-> `%s` declared here: %s:%i",
1310 fval->m_name, fval->m_name, fun->m_context.file, fun->m_context.line);
1312 return !parsewarning(parser, WARN_DEPRECATED,
1313 "call to `%s` (deprecated: %s)\n"
1314 "-> `%s` declared here: %s:%i",
1315 fval->m_name, fval->m_desc, fval->m_name, fun->m_context.file,
1316 fun->m_context.line);
1319 if (fun->m_type_params.size() != paramcount &&
1320 !((fun->m_flags & AST_FLAG_VARIADIC) &&
1321 fun->m_type_params.size() < paramcount))
1323 const char *fewmany = (fun->m_type_params.size() > paramcount) ? "few" : "many";
1325 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1326 "too %s parameters for call to %s: expected %i, got %i\n"
1327 " -> `%s` has been declared here: %s:%i",
1328 fewmany, fval->m_name, (int)fun->m_type_params.size(), (int)paramcount,
1329 fval->m_name, fun->m_context.file, (int)fun->m_context.line);
1331 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1332 "too %s parameters for function call: expected %i, got %i\n"
1333 " -> it has been declared here: %s:%i",
1334 fewmany, (int)fun->m_type_params.size(), (int)paramcount,
1335 fun->m_context.file, (int)fun->m_context.line);
1342 static bool parser_close_paren(parser_t *parser, shunt *sy)
1344 if (sy->ops.empty()) {
1345 parseerror(parser, "unmatched closing paren");
1349 while (sy->ops.size()) {
1350 if (sy->ops.back().isparen) {
1351 if (sy->paren.back() == PAREN_FUNC) {
1352 sy->paren.pop_back();
1353 if (!parser_close_call(parser, sy))
1357 if (sy->paren.back() == PAREN_EXPR) {
1358 sy->paren.pop_back();
1359 if (sy->out.empty()) {
1360 compile_error(sy->ops.back().ctx, "empty paren expression");
1367 if (sy->paren.back() == PAREN_INDEX) {
1368 sy->paren.pop_back();
1369 // pop off the parenthesis
1371 /* then apply the index operator */
1372 if (!parser_sy_apply_operator(parser, sy))
1376 if (sy->paren.back() == PAREN_TERNARY1) {
1377 sy->paren.back() = PAREN_TERNARY2;
1378 // pop off the parenthesis
1382 compile_error(sy->ops.back().ctx, "invalid parenthesis");
1385 if (!parser_sy_apply_operator(parser, sy))
1391 static void parser_reclassify_token(parser_t *parser)
1394 if (parser->tok >= TOKEN_START)
1396 for (i = 0; i < operator_count; ++i) {
1397 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1398 parser->tok = TOKEN_OPERATOR;
1404 static ast_expression* parse_vararg_do(parser_t *parser)
1406 ast_expression *idx, *out;
1408 ast_value *funtype = parser->function->m_function_type;
1409 lex_ctx_t ctx = parser_ctx(parser);
1411 if (!parser->function->m_varargs) {
1412 parseerror(parser, "function has no variable argument list");
1416 if (!parser_next(parser) || parser->tok != '(') {
1417 parseerror(parser, "expected parameter index and type in parenthesis");
1420 if (!parser_next(parser)) {
1421 parseerror(parser, "error parsing parameter index");
1425 idx = parse_expression_leave(parser, true, false, false);
1429 if (parser->tok != ',') {
1430 if (parser->tok != ')') {
1432 parseerror(parser, "expected comma after parameter index");
1435 /* vararg piping: ...(start) */
1436 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1440 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1442 parseerror(parser, "expected typename for vararg");
1446 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
1452 if (parser->tok != ')') {
1454 ast_delete(typevar);
1455 parseerror(parser, "expected closing paren");
1459 if (funtype->m_varparam &&
1460 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->m_varparam))
1464 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1465 ast_type_to_string((ast_expression*)funtype->m_varparam, ty2, sizeof(ty2));
1466 compile_error(typevar->m_context,
1467 "function was declared to take varargs of type `%s`, requested type is: %s",
1471 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->m_varargs), idx);
1472 ast_type_adopt(out, typevar);
1473 ast_delete(typevar);
1477 static ast_expression* parse_vararg(parser_t *parser)
1479 bool old_noops = parser->lex->flags.noops;
1481 ast_expression *out;
1483 parser->lex->flags.noops = true;
1484 out = parse_vararg_do(parser);
1486 parser->lex->flags.noops = old_noops;
1490 /* not to be exposed */
1491 bool ftepp_predef_exists(const char *name);
1492 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1494 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1495 parser->tok == TOKEN_IDENT &&
1496 !strcmp(parser_tokval(parser), "_"))
1498 /* a translatable string */
1501 parser->lex->flags.noops = true;
1502 if (!parser_next(parser) || parser->tok != '(') {
1503 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1506 parser->lex->flags.noops = false;
1507 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1508 parseerror(parser, "expected a constant string in translatable-string extension");
1511 val = (ast_value*)parser->m_fold.constgen_string(parser_tokval(parser), true);
1514 sy->out.push_back(syexp(parser_ctx(parser), (ast_expression*)val));
1516 if (!parser_next(parser) || parser->tok != ')') {
1517 parseerror(parser, "expected closing paren after translatable string");
1522 else if (parser->tok == TOKEN_DOTS)
1525 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1526 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1529 va = parse_vararg(parser);
1532 sy->out.push_back(syexp(parser_ctx(parser), va));
1535 else if (parser->tok == TOKEN_FLOATCONST) {
1536 ast_expression *val = parser->m_fold.constgen_float((parser_token(parser)->constval.f), false);
1539 sy->out.push_back(syexp(parser_ctx(parser), val));
1542 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1543 ast_expression *val = parser->m_fold.constgen_float((qcfloat_t)(parser_token(parser)->constval.i), false);
1546 sy->out.push_back(syexp(parser_ctx(parser), val));
1549 else if (parser->tok == TOKEN_STRINGCONST) {
1550 ast_expression *val = parser->m_fold.constgen_string(parser_tokval(parser), false);
1553 sy->out.push_back(syexp(parser_ctx(parser), val));
1556 else if (parser->tok == TOKEN_VECTORCONST) {
1557 ast_expression *val = parser->m_fold.constgen_vector(parser_token(parser)->constval.v);
1560 sy->out.push_back(syexp(parser_ctx(parser), val));
1563 else if (parser->tok == TOKEN_IDENT)
1565 const char *ctoken = parser_tokval(parser);
1566 ast_expression *prev = sy->out.size() ? sy->out.back().out : nullptr;
1567 ast_expression *var;
1568 /* a_vector.{x,y,z} */
1569 if (sy->ops.empty() ||
1570 !sy->ops.back().etype ||
1571 operators[sy->ops.back().etype-1].id != opid1('.'))
1573 /* When adding more intrinsics, fix the above condition */
1576 if (prev && prev->m_vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1578 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1580 var = parser_find_var(parser, parser_tokval(parser));
1582 var = parser_find_field(parser, parser_tokval(parser));
1584 if (!var && with_labels) {
1585 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1587 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1588 var = (ast_expression*)lbl;
1589 parser->labels.push_back(lbl);
1592 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1593 var = (ast_expression*)parser->m_fold.constgen_string(parser->function->m_name, false);
1596 * now we try for the real intrinsic hashtable. If the string
1597 * begins with __builtin, we simply skip past it, otherwise we
1598 * use the identifier as is.
1600 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1601 var = parser->m_intrin.func(parser_tokval(parser));
1605 * Try it again, intrin_func deals with the alias method as well
1606 * the first one masks for __builtin though, we emit warning here.
1609 if ((var = parser->m_intrin.func(parser_tokval(parser)))) {
1610 (void)!compile_warning(
1613 "using implicitly defined builtin `__builtin_%s' for `%s'",
1614 parser_tokval(parser),
1615 parser_tokval(parser)
1623 * sometimes people use preprocessing predefs without enabling them
1624 * i've done this thousands of times already myself. Lets check for
1625 * it in the predef table. And diagnose it better :)
1627 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1628 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1632 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1638 if (ast_istype(var, ast_value)) {
1639 ((ast_value*)var)->m_uses++;
1641 else if (ast_istype(var, ast_member)) {
1642 ast_member *mem = (ast_member*)var;
1643 if (ast_istype(mem->m_owner, ast_value))
1644 ((ast_value*)(mem->m_owner))->m_uses++;
1647 sy->out.push_back(syexp(parser_ctx(parser), var));
1650 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1654 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1656 ast_expression *expr = nullptr;
1658 bool wantop = false;
1659 /* only warn once about an assignment in a truth value because the current code
1660 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1662 bool warn_parenthesis = true;
1664 /* count the parens because an if starts with one, so the
1665 * end of a condition is an unmatched closing paren
1669 memset(&sy, 0, sizeof(sy));
1671 parser->lex->flags.noops = false;
1673 parser_reclassify_token(parser);
1677 if (parser->tok == TOKEN_TYPENAME) {
1678 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1682 if (parser->tok == TOKEN_OPERATOR)
1684 /* classify the operator */
1685 const oper_info *op;
1686 const oper_info *olast = nullptr;
1688 for (o = 0; o < operator_count; ++o) {
1689 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1690 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1691 !strcmp(parser_tokval(parser), operators[o].op))
1696 if (o == operator_count) {
1697 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1700 /* found an operator */
1703 /* when declaring variables, a comma starts a new variable */
1704 if (op->id == opid1(',') && sy.paren.empty() && stopatcomma) {
1705 /* fixup the token */
1710 /* a colon without a pervious question mark cannot be a ternary */
1711 if (!ternaries && op->id == opid2(':','?')) {
1716 if (op->id == opid1(',')) {
1717 if (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1718 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1722 if (sy.ops.size() && !sy.ops.back().isparen)
1723 olast = &operators[sy.ops.back().etype-1];
1725 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1726 while (olast && op->prec < olast->prec)
1728 if (!parser_sy_apply_operator(parser, &sy))
1730 if (sy.ops.size() && !sy.ops.back().isparen)
1731 olast = &operators[sy.ops.back().etype-1];
1736 #define IsAssignOp(x) (\
1737 (x) == opid1('=') || \
1738 (x) == opid2('+','=') || \
1739 (x) == opid2('-','=') || \
1740 (x) == opid2('*','=') || \
1741 (x) == opid2('/','=') || \
1742 (x) == opid2('%','=') || \
1743 (x) == opid2('&','=') || \
1744 (x) == opid2('|','=') || \
1745 (x) == opid3('&','~','=') \
1747 if (warn_parenthesis) {
1748 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1749 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1750 (truthvalue && sy.paren.empty() && IsAssignOp(op->id))
1753 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1754 warn_parenthesis = false;
1757 if (olast && olast->id != op->id) {
1758 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1759 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1761 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1762 warn_parenthesis = false;
1764 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1765 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1767 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1768 warn_parenthesis = false;
1774 (op->prec < olast->prec) ||
1775 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1777 if (!parser_sy_apply_operator(parser, &sy))
1779 if (sy.ops.size() && !sy.ops.back().isparen)
1780 olast = &operators[sy.ops.back().etype-1];
1785 if (op->id == opid1('(')) {
1787 size_t sycount = sy.out.size();
1788 /* we expected an operator, this is the function-call operator */
1789 sy.paren.push_back(PAREN_FUNC);
1790 sy.ops.push_back(syparen(parser_ctx(parser), sycount-1));
1791 sy.argc.push_back(0);
1793 sy.paren.push_back(PAREN_EXPR);
1794 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1797 } else if (op->id == opid1('[')) {
1799 parseerror(parser, "unexpected array subscript");
1802 sy.paren.push_back(PAREN_INDEX);
1803 /* push both the operator and the paren, this makes life easier */
1804 sy.ops.push_back(syop(parser_ctx(parser), op));
1805 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1807 } else if (op->id == opid2('?',':')) {
1808 sy.ops.push_back(syop(parser_ctx(parser), op));
1809 sy.ops.push_back(syparen(parser_ctx(parser), 0));
1812 sy.paren.push_back(PAREN_TERNARY1);
1813 } else if (op->id == opid2(':','?')) {
1814 if (sy.paren.empty()) {
1815 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1818 if (sy.paren.back() != PAREN_TERNARY1) {
1819 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1822 if (!parser_close_paren(parser, &sy))
1824 sy.ops.push_back(syop(parser_ctx(parser), op));
1828 sy.ops.push_back(syop(parser_ctx(parser), op));
1829 wantop = !!(op->flags & OP_SUFFIX);
1832 else if (parser->tok == ')') {
1833 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1834 if (!parser_sy_apply_operator(parser, &sy))
1837 if (sy.paren.empty())
1840 if (sy.paren.back() == PAREN_TERNARY1) {
1841 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1844 if (!parser_close_paren(parser, &sy))
1847 /* must be a function call without parameters */
1848 if (sy.paren.back() != PAREN_FUNC) {
1849 parseerror(parser, "closing paren in invalid position");
1852 if (!parser_close_paren(parser, &sy))
1857 else if (parser->tok == '(') {
1858 parseerror(parser, "internal error: '(' should be classified as operator");
1861 else if (parser->tok == '[') {
1862 parseerror(parser, "internal error: '[' should be classified as operator");
1865 else if (parser->tok == ']') {
1866 while (sy.paren.size() && sy.paren.back() == PAREN_TERNARY2) {
1867 if (!parser_sy_apply_operator(parser, &sy))
1870 if (sy.paren.empty())
1872 if (sy.paren.back() != PAREN_INDEX) {
1873 parseerror(parser, "mismatched parentheses, unexpected ']'");
1876 if (!parser_close_paren(parser, &sy))
1881 if (!parse_sya_operand(parser, &sy, with_labels))
1886 /* in this case we might want to allow constant string concatenation */
1887 bool concatenated = false;
1888 if (parser->tok == TOKEN_STRINGCONST && sy.out.size()) {
1889 ast_expression *lexpr = sy.out.back().out;
1890 if (ast_istype(lexpr, ast_value)) {
1891 ast_value *last = (ast_value*)lexpr;
1892 if (last->m_isimm == true && last->m_cvq == CV_CONST &&
1893 last->m_hasvalue && last->m_vtype == TYPE_STRING)
1895 char *newstr = nullptr;
1896 util_asprintf(&newstr, "%s%s", last->m_constval.vstring, parser_tokval(parser));
1897 sy.out.back().out = (ast_expression*)parser->m_fold.constgen_string(newstr, false);
1899 concatenated = true;
1903 if (!concatenated) {
1904 parseerror(parser, "expected operator or end of statement");
1909 if (!parser_next(parser)) {
1912 if (parser->tok == ';' ||
1913 ((sy.paren.empty() || (sy.paren.size() == 1 && sy.paren.back() == PAREN_TERNARY2)) &&
1914 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1920 while (sy.ops.size()) {
1921 if (!parser_sy_apply_operator(parser, &sy))
1925 parser->lex->flags.noops = true;
1926 if (sy.out.size() != 1) {
1927 parseerror(parser, "expression expected");
1930 expr = sy.out[0].out;
1931 if (sy.paren.size()) {
1932 parseerror(parser, "internal error: sy.paren.size() = %zu", sy.paren.size());
1938 parser->lex->flags.noops = true;
1939 for (auto &it : sy.out)
1940 if (it.out) ast_unref(it.out);
1944 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1946 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1949 if (parser->tok != ';') {
1950 parseerror(parser, "semicolon expected after expression");
1954 if (!parser_next(parser)) {
1961 static void parser_enterblock(parser_t *parser)
1963 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1964 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1965 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1966 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1967 vec_push(parser->_block_ctx, parser_ctx(parser));
1970 static bool parser_leaveblock(parser_t *parser)
1973 size_t locals, typedefs;
1975 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1976 parseerror(parser, "internal error: parser_leaveblock with no block");
1980 util_htdel(vec_last(parser->variables));
1982 vec_pop(parser->variables);
1983 if (!vec_size(parser->_blocklocals)) {
1984 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1988 locals = vec_last(parser->_blocklocals);
1989 vec_pop(parser->_blocklocals);
1990 while (vec_size(parser->_locals) != locals) {
1991 ast_expression *e = vec_last(parser->_locals);
1992 ast_value *v = (ast_value*)e;
1993 vec_pop(parser->_locals);
1994 if (ast_istype(e, ast_value) && !v->m_uses) {
1995 if (compile_warning(v->m_context, WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->m_name))
2000 typedefs = vec_last(parser->_blocktypedefs);
2001 while (vec_size(parser->_typedefs) != typedefs) {
2002 ast_delete(vec_last(parser->_typedefs));
2003 vec_pop(parser->_typedefs);
2005 util_htdel(vec_last(parser->typedefs));
2006 vec_pop(parser->typedefs);
2008 vec_pop(parser->_block_ctx);
2013 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2015 vec_push(parser->_locals, e);
2016 util_htset(vec_last(parser->variables), name, (void*)e);
2019 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2021 parser->globals.push_back(e);
2022 util_htset(parser->htglobals, name, e);
2025 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2029 ast_expression *prev;
2031 if (cond->m_vtype == TYPE_VOID || cond->m_vtype >= TYPE_VARIANT) {
2033 ast_type_to_string(cond, ty, sizeof(ty));
2034 compile_error(cond->m_context, "invalid type for if() condition: %s", ty);
2037 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->m_vtype == TYPE_STRING)
2040 cond = (ast_expression*)ast_unary_new(cond->m_context, INSTR_NOT_S, cond);
2043 parseerror(parser, "internal error: failed to process condition");
2048 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->m_vtype == TYPE_VECTOR)
2050 /* vector types need to be cast to true booleans */
2051 ast_binary *bin = (ast_binary*)cond;
2052 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->m_op == INSTR_AND || bin->m_op == INSTR_OR))
2054 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2056 cond = (ast_expression*)ast_unary_new(cond->m_context, INSTR_NOT_V, cond);
2059 parseerror(parser, "internal error: failed to process condition");
2066 unary = (ast_unary*)cond;
2067 /* ast_istype dereferences cond, should test here for safety */
2068 while (cond && ast_istype(cond, ast_unary) && unary->m_op == INSTR_NOT_F)
2070 cond = unary->m_operand;
2071 unary->m_operand = nullptr;
2074 unary = (ast_unary*)cond;
2078 parseerror(parser, "internal error: failed to process condition");
2080 if (ifnot) *_ifnot = !*_ifnot;
2084 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2087 ast_expression *cond, *ontrue = nullptr, *onfalse = nullptr;
2090 lex_ctx_t ctx = parser_ctx(parser);
2092 (void)block; /* not touching */
2094 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2095 if (!parser_next(parser)) {
2096 parseerror(parser, "expected condition or 'not'");
2099 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2101 if (!parser_next(parser)) {
2102 parseerror(parser, "expected condition in parenthesis");
2106 if (parser->tok != '(') {
2107 parseerror(parser, "expected 'if' condition in parenthesis");
2110 /* parse into the expression */
2111 if (!parser_next(parser)) {
2112 parseerror(parser, "expected 'if' condition after opening paren");
2115 /* parse the condition */
2116 cond = parse_expression_leave(parser, false, true, false);
2120 if (parser->tok != ')') {
2121 parseerror(parser, "expected closing paren after 'if' condition");
2125 /* parse into the 'then' branch */
2126 if (!parser_next(parser)) {
2127 parseerror(parser, "expected statement for on-true branch of 'if'");
2131 if (!parse_statement_or_block(parser, &ontrue)) {
2136 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2137 /* check for an else */
2138 if (!strcmp(parser_tokval(parser), "else")) {
2139 /* parse into the 'else' branch */
2140 if (!parser_next(parser)) {
2141 parseerror(parser, "expected on-false branch after 'else'");
2146 if (!parse_statement_or_block(parser, &onfalse)) {
2153 cond = process_condition(parser, cond, &ifnot);
2155 if (ontrue) ast_delete(ontrue);
2156 if (onfalse) ast_delete(onfalse);
2161 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2163 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2164 *out = (ast_expression*)ifthen;
2168 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2169 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2172 char *label = nullptr;
2174 /* skip the 'while' and get the body */
2175 if (!parser_next(parser)) {
2176 if (OPTS_FLAG(LOOP_LABELS))
2177 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2179 parseerror(parser, "expected 'while' condition in parenthesis");
2183 if (parser->tok == ':') {
2184 if (!OPTS_FLAG(LOOP_LABELS))
2185 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2186 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2187 parseerror(parser, "expected loop label");
2190 label = util_strdup(parser_tokval(parser));
2191 if (!parser_next(parser)) {
2193 parseerror(parser, "expected 'while' condition in parenthesis");
2198 if (parser->tok != '(') {
2199 parseerror(parser, "expected 'while' condition in parenthesis");
2203 parser->breaks.push_back(label);
2204 parser->continues.push_back(label);
2206 rv = parse_while_go(parser, block, out);
2209 if (parser->breaks.back() != label || parser->continues.back() != label) {
2210 parseerror(parser, "internal error: label stack corrupted");
2216 parser->breaks.pop_back();
2217 parser->continues.pop_back();
2222 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2225 ast_expression *cond, *ontrue;
2229 lex_ctx_t ctx = parser_ctx(parser);
2231 (void)block; /* not touching */
2233 /* parse into the expression */
2234 if (!parser_next(parser)) {
2235 parseerror(parser, "expected 'while' condition after opening paren");
2238 /* parse the condition */
2239 cond = parse_expression_leave(parser, false, true, false);
2243 if (parser->tok != ')') {
2244 parseerror(parser, "expected closing paren after 'while' condition");
2248 /* parse into the 'then' branch */
2249 if (!parser_next(parser)) {
2250 parseerror(parser, "expected while-loop body");
2254 if (!parse_statement_or_block(parser, &ontrue)) {
2259 cond = process_condition(parser, cond, &ifnot);
2264 aloop = ast_loop_new(ctx, nullptr, cond, ifnot, nullptr, false, nullptr, ontrue);
2265 *out = (ast_expression*)aloop;
2269 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2270 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2273 char *label = nullptr;
2275 /* skip the 'do' and get the body */
2276 if (!parser_next(parser)) {
2277 if (OPTS_FLAG(LOOP_LABELS))
2278 parseerror(parser, "expected loop label or body");
2280 parseerror(parser, "expected loop body");
2284 if (parser->tok == ':') {
2285 if (!OPTS_FLAG(LOOP_LABELS))
2286 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2287 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2288 parseerror(parser, "expected loop label");
2291 label = util_strdup(parser_tokval(parser));
2292 if (!parser_next(parser)) {
2294 parseerror(parser, "expected loop body");
2299 parser->breaks.push_back(label);
2300 parser->continues.push_back(label);
2302 rv = parse_dowhile_go(parser, block, out);
2305 if (parser->breaks.back() != label || parser->continues.back() != label) {
2306 parseerror(parser, "internal error: label stack corrupted");
2309 * Test for nullptr otherwise ast_delete dereferences null pointer
2317 parser->breaks.pop_back();
2318 parser->continues.pop_back();
2323 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2326 ast_expression *cond, *ontrue;
2330 lex_ctx_t ctx = parser_ctx(parser);
2332 (void)block; /* not touching */
2334 if (!parse_statement_or_block(parser, &ontrue))
2337 /* expect the "while" */
2338 if (parser->tok != TOKEN_KEYWORD ||
2339 strcmp(parser_tokval(parser), "while"))
2341 parseerror(parser, "expected 'while' and condition");
2346 /* skip the 'while' and check for opening paren */
2347 if (!parser_next(parser) || parser->tok != '(') {
2348 parseerror(parser, "expected 'while' condition in parenthesis");
2352 /* parse into the expression */
2353 if (!parser_next(parser)) {
2354 parseerror(parser, "expected 'while' condition after opening paren");
2358 /* parse the condition */
2359 cond = parse_expression_leave(parser, false, true, false);
2363 if (parser->tok != ')') {
2364 parseerror(parser, "expected closing paren after 'while' condition");
2370 if (!parser_next(parser) || parser->tok != ';') {
2371 parseerror(parser, "expected semicolon after condition");
2377 if (!parser_next(parser)) {
2378 parseerror(parser, "parse error");
2384 cond = process_condition(parser, cond, &ifnot);
2389 aloop = ast_loop_new(ctx, nullptr, nullptr, false, cond, ifnot, nullptr, ontrue);
2390 *out = (ast_expression*)aloop;
2394 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2395 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2398 char *label = nullptr;
2400 /* skip the 'for' and check for opening paren */
2401 if (!parser_next(parser)) {
2402 if (OPTS_FLAG(LOOP_LABELS))
2403 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2405 parseerror(parser, "expected 'for' expressions in parenthesis");
2409 if (parser->tok == ':') {
2410 if (!OPTS_FLAG(LOOP_LABELS))
2411 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2412 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2413 parseerror(parser, "expected loop label");
2416 label = util_strdup(parser_tokval(parser));
2417 if (!parser_next(parser)) {
2419 parseerror(parser, "expected 'for' expressions in parenthesis");
2424 if (parser->tok != '(') {
2425 parseerror(parser, "expected 'for' expressions in parenthesis");
2429 parser->breaks.push_back(label);
2430 parser->continues.push_back(label);
2432 rv = parse_for_go(parser, block, out);
2435 if (parser->breaks.back() != label || parser->continues.back() != label) {
2436 parseerror(parser, "internal error: label stack corrupted");
2442 parser->breaks.pop_back();
2443 parser->continues.pop_back();
2447 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2450 ast_expression *initexpr, *cond, *increment, *ontrue;
2455 lex_ctx_t ctx = parser_ctx(parser);
2457 parser_enterblock(parser);
2461 increment = nullptr;
2464 /* parse into the expression */
2465 if (!parser_next(parser)) {
2466 parseerror(parser, "expected 'for' initializer after opening paren");
2471 if (parser->tok == TOKEN_IDENT)
2472 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2474 if (typevar || parser->tok == TOKEN_TYPENAME) {
2475 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, nullptr))
2478 else if (parser->tok != ';')
2480 initexpr = parse_expression_leave(parser, false, false, false);
2483 /* move on to condition */
2484 if (parser->tok != ';') {
2485 parseerror(parser, "expected semicolon after for-loop initializer");
2488 if (!parser_next(parser)) {
2489 parseerror(parser, "expected for-loop condition");
2493 else if (!parser_next(parser)) {
2494 parseerror(parser, "expected for-loop condition");
2498 /* parse the condition */
2499 if (parser->tok != ';') {
2500 cond = parse_expression_leave(parser, false, true, false);
2505 /* move on to incrementor */
2506 if (parser->tok != ';') {
2507 parseerror(parser, "expected semicolon after for-loop initializer");
2510 if (!parser_next(parser)) {
2511 parseerror(parser, "expected for-loop condition");
2515 /* parse the incrementor */
2516 if (parser->tok != ')') {
2517 lex_ctx_t condctx = parser_ctx(parser);
2518 increment = parse_expression_leave(parser, false, false, false);
2521 if (!increment->m_side_effects) {
2522 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2528 if (parser->tok != ')') {
2529 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2532 /* parse into the 'then' branch */
2533 if (!parser_next(parser)) {
2534 parseerror(parser, "expected for-loop body");
2537 if (!parse_statement_or_block(parser, &ontrue))
2541 cond = process_condition(parser, cond, &ifnot);
2545 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, nullptr, false, increment, ontrue);
2546 *out = (ast_expression*)aloop;
2548 if (!parser_leaveblock(parser)) {
2554 if (initexpr) ast_unref(initexpr);
2555 if (cond) ast_unref(cond);
2556 if (increment) ast_unref(increment);
2557 (void)!parser_leaveblock(parser);
2561 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2563 ast_expression *exp = nullptr;
2564 ast_expression *var = nullptr;
2565 ast_return *ret = nullptr;
2566 ast_value *retval = parser->function->m_return_value;
2567 ast_value *expected = parser->function->m_function_type;
2569 lex_ctx_t ctx = parser_ctx(parser);
2571 (void)block; /* not touching */
2573 if (!parser_next(parser)) {
2574 parseerror(parser, "expected return expression");
2578 /* return assignments */
2579 if (parser->tok == '=') {
2580 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2581 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2585 if (type_store_instr[expected->m_next->m_vtype] == VINSTR_END) {
2587 ast_type_to_string(expected->m_next, ty1, sizeof(ty1));
2588 parseerror(parser, "invalid return type: `%s'", ty1);
2592 if (!parser_next(parser)) {
2593 parseerror(parser, "expected return assignment expression");
2597 if (!(exp = parse_expression_leave(parser, false, false, false)))
2600 /* prepare the return value */
2602 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2603 ast_type_adopt(retval, expected->m_next);
2604 parser->function->m_return_value = retval;
2607 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2608 char ty1[1024], ty2[1024];
2609 ast_type_to_string(exp, ty1, sizeof(ty1));
2610 ast_type_to_string(retval, ty2, sizeof(ty2));
2611 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2614 /* store to 'return' local variable */
2615 var = (ast_expression*)ast_store_new(
2617 type_store_instr[expected->m_next->m_vtype],
2618 (ast_expression*)retval, exp);
2625 if (parser->tok != ';')
2626 parseerror(parser, "missing semicolon after return assignment");
2627 else if (!parser_next(parser))
2628 parseerror(parser, "parse error after return assignment");
2634 if (parser->tok != ';') {
2635 exp = parse_expression(parser, false, false);
2639 if (exp->m_vtype != TYPE_NIL &&
2640 exp->m_vtype != ((ast_expression*)expected)->m_next->m_vtype)
2642 parseerror(parser, "return with invalid expression");
2645 ret = ast_return_new(ctx, exp);
2651 if (!parser_next(parser))
2652 parseerror(parser, "parse error");
2654 if (!retval && expected->m_next->m_vtype != TYPE_VOID)
2656 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2658 ret = ast_return_new(ctx, (ast_expression*)retval);
2660 *out = (ast_expression*)ret;
2664 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2667 unsigned int levels = 0;
2668 lex_ctx_t ctx = parser_ctx(parser);
2669 auto &loops = (is_continue ? parser->continues : parser->breaks);
2671 (void)block; /* not touching */
2672 if (!parser_next(parser)) {
2673 parseerror(parser, "expected semicolon or loop label");
2677 if (loops.empty()) {
2679 parseerror(parser, "`continue` can only be used inside loops");
2681 parseerror(parser, "`break` can only be used inside loops or switches");
2684 if (parser->tok == TOKEN_IDENT) {
2685 if (!OPTS_FLAG(LOOP_LABELS))
2686 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2689 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2692 parseerror(parser, "no such loop to %s: `%s`",
2693 (is_continue ? "continue" : "break out of"),
2694 parser_tokval(parser));
2699 if (!parser_next(parser)) {
2700 parseerror(parser, "expected semicolon");
2705 if (parser->tok != ';') {
2706 parseerror(parser, "expected semicolon");
2710 if (!parser_next(parser))
2711 parseerror(parser, "parse error");
2713 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2717 /* returns true when it was a variable qualifier, false otherwise!
2718 * on error, cvq is set to CV_WRONG
2720 struct attribute_t {
2725 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2727 bool had_const = false;
2728 bool had_var = false;
2729 bool had_noref = false;
2730 bool had_attrib = false;
2731 bool had_static = false;
2734 static attribute_t attributes[] = {
2735 { "noreturn", AST_FLAG_NORETURN },
2736 { "inline", AST_FLAG_INLINE },
2737 { "eraseable", AST_FLAG_ERASEABLE },
2738 { "accumulate", AST_FLAG_ACCUMULATE },
2739 { "last", AST_FLAG_FINAL_DECL }
2746 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2748 /* parse an attribute */
2749 if (!parser_next(parser)) {
2750 parseerror(parser, "expected attribute after `[[`");
2755 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2756 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2757 flags |= attributes[i].flag;
2758 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2759 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2760 attributes[i].name);
2768 if (i != GMQCC_ARRAY_COUNT(attributes))
2772 if (!strcmp(parser_tokval(parser), "noref")) {
2774 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2775 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2780 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2781 flags |= AST_FLAG_ALIAS;
2784 if (!parser_next(parser)) {
2785 parseerror(parser, "parse error in attribute");
2789 if (parser->tok == '(') {
2790 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2791 parseerror(parser, "`alias` attribute missing parameter");
2795 *message = util_strdup(parser_tokval(parser));
2797 if (!parser_next(parser)) {
2798 parseerror(parser, "parse error in attribute");
2802 if (parser->tok != ')') {
2803 parseerror(parser, "`alias` attribute expected `)` after parameter");
2807 if (!parser_next(parser)) {
2808 parseerror(parser, "parse error in attribute");
2813 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2814 parseerror(parser, "`alias` attribute expected `]]`");
2818 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2819 flags |= AST_FLAG_DEPRECATED;
2822 if (!parser_next(parser)) {
2823 parseerror(parser, "parse error in attribute");
2827 if (parser->tok == '(') {
2828 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2829 parseerror(parser, "`deprecated` attribute missing parameter");
2833 *message = util_strdup(parser_tokval(parser));
2835 if (!parser_next(parser)) {
2836 parseerror(parser, "parse error in attribute");
2840 if(parser->tok != ')') {
2841 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2845 if (!parser_next(parser)) {
2846 parseerror(parser, "parse error in attribute");
2851 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2852 parseerror(parser, "`deprecated` attribute expected `]]`");
2855 if (*message) mem_d(*message);
2861 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2862 flags |= AST_FLAG_COVERAGE;
2863 if (!parser_next(parser)) {
2865 parseerror(parser, "parse error in coverage attribute");
2869 if (parser->tok == '(') {
2870 if (!parser_next(parser)) {
2872 parseerror(parser, "invalid parameter for coverage() attribute\n"
2873 "valid are: block");
2877 if (parser->tok != ')') {
2879 if (parser->tok != TOKEN_IDENT)
2880 goto bad_coverage_arg;
2881 if (!strcmp(parser_tokval(parser), "block"))
2882 flags |= AST_FLAG_BLOCK_COVERAGE;
2883 else if (!strcmp(parser_tokval(parser), "none"))
2884 flags &= ~(AST_FLAG_COVERAGE_MASK);
2886 goto bad_coverage_arg;
2887 if (!parser_next(parser))
2888 goto error_in_coverage;
2889 if (parser->tok == ',') {
2890 if (!parser_next(parser))
2891 goto error_in_coverage;
2893 } while (parser->tok != ')');
2895 if (parser->tok != ')' || !parser_next(parser))
2896 goto error_in_coverage;
2898 /* without parameter [[coverage]] equals [[coverage(block)]] */
2899 flags |= AST_FLAG_BLOCK_COVERAGE;
2904 /* Skip tokens until we hit a ]] */
2905 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2906 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2907 if (!parser_next(parser)) {
2908 parseerror(parser, "error inside attribute");
2915 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2917 else if (!strcmp(parser_tokval(parser), "const"))
2919 else if (!strcmp(parser_tokval(parser), "var"))
2921 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2923 else if (!strcmp(parser_tokval(parser), "noref"))
2925 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2932 if (!parser_next(parser))
2942 *is_static = had_static;
2946 parseerror(parser, "parse error after variable qualifier");
2951 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2952 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2955 char *label = nullptr;
2957 /* skip the 'while' and get the body */
2958 if (!parser_next(parser)) {
2959 if (OPTS_FLAG(LOOP_LABELS))
2960 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2962 parseerror(parser, "expected 'switch' operand in parenthesis");
2966 if (parser->tok == ':') {
2967 if (!OPTS_FLAG(LOOP_LABELS))
2968 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2969 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2970 parseerror(parser, "expected loop label");
2973 label = util_strdup(parser_tokval(parser));
2974 if (!parser_next(parser)) {
2976 parseerror(parser, "expected 'switch' operand in parenthesis");
2981 if (parser->tok != '(') {
2982 parseerror(parser, "expected 'switch' operand in parenthesis");
2986 parser->breaks.push_back(label);
2988 rv = parse_switch_go(parser, block, out);
2991 if (parser->breaks.back() != label) {
2992 parseerror(parser, "internal error: label stack corrupted");
2998 parser->breaks.pop_back();
3003 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3005 ast_expression *operand;
3008 ast_switch *switchnode;
3009 ast_switch_case swcase;
3012 bool noref, is_static;
3013 uint32_t qflags = 0;
3015 lex_ctx_t ctx = parser_ctx(parser);
3017 (void)block; /* not touching */
3020 /* parse into the expression */
3021 if (!parser_next(parser)) {
3022 parseerror(parser, "expected switch operand");
3025 /* parse the operand */
3026 operand = parse_expression_leave(parser, false, false, false);
3030 switchnode = ast_switch_new(ctx, operand);
3033 if (parser->tok != ')') {
3034 ast_delete(switchnode);
3035 parseerror(parser, "expected closing paren after 'switch' operand");
3039 /* parse over the opening paren */
3040 if (!parser_next(parser) || parser->tok != '{') {
3041 ast_delete(switchnode);
3042 parseerror(parser, "expected list of cases");
3046 if (!parser_next(parser)) {
3047 ast_delete(switchnode);
3048 parseerror(parser, "expected 'case' or 'default'");
3052 /* new block; allow some variables to be declared here */
3053 parser_enterblock(parser);
3056 if (parser->tok == TOKEN_IDENT)
3057 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3058 if (typevar || parser->tok == TOKEN_TYPENAME) {
3059 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, nullptr)) {
3060 ast_delete(switchnode);
3065 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, nullptr))
3067 if (cvq == CV_WRONG) {
3068 ast_delete(switchnode);
3071 if (!parse_variable(parser, block, true, cvq, nullptr, noref, is_static, qflags, nullptr)) {
3072 ast_delete(switchnode);
3081 while (parser->tok != '}') {
3082 ast_block *caseblock;
3084 if (!strcmp(parser_tokval(parser), "case")) {
3085 if (!parser_next(parser)) {
3086 ast_delete(switchnode);
3087 parseerror(parser, "expected expression for case");
3090 swcase.m_value = parse_expression_leave(parser, false, false, false);
3091 if (!swcase.m_value) {
3092 ast_delete(switchnode);
3093 parseerror(parser, "expected expression for case");
3096 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3097 if (!ast_istype(swcase.m_value, ast_value)) { /* || ((ast_value*)swcase.m_value)->m_cvq != CV_CONST) { */
3098 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3104 else if (!strcmp(parser_tokval(parser), "default")) {
3105 swcase.m_value = nullptr;
3106 if (!parser_next(parser)) {
3107 ast_delete(switchnode);
3108 parseerror(parser, "expected colon");
3113 ast_delete(switchnode);
3114 parseerror(parser, "expected 'case' or 'default'");
3118 /* Now the colon and body */
3119 if (parser->tok != ':') {
3120 if (swcase.m_value) ast_unref(swcase.m_value);
3121 ast_delete(switchnode);
3122 parseerror(parser, "expected colon");
3126 if (!parser_next(parser)) {
3127 if (swcase.m_value) ast_unref(swcase.m_value);
3128 ast_delete(switchnode);
3129 parseerror(parser, "expected statements or case");
3132 caseblock = ast_block_new(parser_ctx(parser));
3134 if (swcase.m_value) ast_unref(swcase.m_value);
3135 ast_delete(switchnode);
3138 swcase.m_code = (ast_expression*)caseblock;
3139 switchnode->m_cases.push_back(swcase);
3141 ast_expression *expr;
3142 if (parser->tok == '}')
3144 if (parser->tok == TOKEN_KEYWORD) {
3145 if (!strcmp(parser_tokval(parser), "case") ||
3146 !strcmp(parser_tokval(parser), "default"))
3151 if (!parse_statement(parser, caseblock, &expr, true)) {
3152 ast_delete(switchnode);
3157 if (!ast_block_add_expr(caseblock, expr)) {
3158 ast_delete(switchnode);
3164 parser_leaveblock(parser);
3167 if (parser->tok != '}') {
3168 ast_delete(switchnode);
3169 parseerror(parser, "expected closing paren of case list");
3172 if (!parser_next(parser)) {
3173 ast_delete(switchnode);
3174 parseerror(parser, "parse error after switch");
3177 *out = (ast_expression*)switchnode;
3181 /* parse computed goto sides */
3182 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3183 ast_expression *on_true;
3184 ast_expression *on_false;
3185 ast_expression *cond;
3190 if (ast_istype(*side, ast_ternary)) {
3191 ast_ternary *tern = (ast_ternary*)*side;
3192 on_true = parse_goto_computed(parser, &tern->m_on_true);
3193 on_false = parse_goto_computed(parser, &tern->m_on_false);
3195 if (!on_true || !on_false) {
3196 parseerror(parser, "expected label or expression in ternary");
3197 if (on_true) ast_unref(on_true);
3198 if (on_false) ast_unref(on_false);
3202 cond = tern->m_cond;
3203 tern->m_cond = nullptr;
3206 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3207 } else if (ast_istype(*side, ast_label)) {
3208 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->m_name);
3209 ast_goto_set_label(gt, ((ast_label*)*side));
3211 return (ast_expression*)gt;
3216 static bool parse_goto(parser_t *parser, ast_expression **out)
3218 ast_goto *gt = nullptr;
3219 ast_expression *lbl;
3221 if (!parser_next(parser))
3224 if (parser->tok != TOKEN_IDENT) {
3225 ast_expression *expression;
3227 /* could be an expression i.e computed goto :-) */
3228 if (parser->tok != '(') {
3229 parseerror(parser, "expected label name after `goto`");
3233 /* failed to parse expression for goto */
3234 if (!(expression = parse_expression(parser, false, true)) ||
3235 !(*out = parse_goto_computed(parser, &expression))) {
3236 parseerror(parser, "invalid goto expression");
3238 ast_unref(expression);
3245 /* not computed goto */
3246 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3247 lbl = parser_find_label(parser, gt->m_name);
3249 if (!ast_istype(lbl, ast_label)) {
3250 parseerror(parser, "internal error: label is not an ast_label");
3254 ast_goto_set_label(gt, (ast_label*)lbl);
3257 parser->gotos.push_back(gt);
3259 if (!parser_next(parser) || parser->tok != ';') {
3260 parseerror(parser, "semicolon expected after goto label");
3263 if (!parser_next(parser)) {
3264 parseerror(parser, "parse error after goto");
3268 *out = (ast_expression*)gt;
3272 static bool parse_skipwhite(parser_t *parser)
3275 if (!parser_next(parser))
3277 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3278 return parser->tok < TOKEN_ERROR;
3281 static bool parse_eol(parser_t *parser)
3283 if (!parse_skipwhite(parser))
3285 return parser->tok == TOKEN_EOL;
3288 static bool parse_pragma_do(parser_t *parser)
3290 if (!parser_next(parser) ||
3291 parser->tok != TOKEN_IDENT ||
3292 strcmp(parser_tokval(parser), "pragma"))
3294 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3297 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3298 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3302 if (!strcmp(parser_tokval(parser), "noref")) {
3303 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3304 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3307 parser->noref = !!parser_token(parser)->constval.i;
3308 if (!parse_eol(parser)) {
3309 parseerror(parser, "parse error after `noref` pragma");
3315 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3318 while (!parse_eol(parser)) {
3319 parser_next(parser);
3328 static bool parse_pragma(parser_t *parser)
3331 parser->lex->flags.preprocessing = true;
3332 parser->lex->flags.mergelines = true;
3333 rv = parse_pragma_do(parser);
3334 if (parser->tok != TOKEN_EOL) {
3335 parseerror(parser, "junk after pragma");
3338 parser->lex->flags.preprocessing = false;
3339 parser->lex->flags.mergelines = false;
3340 if (!parser_next(parser)) {
3341 parseerror(parser, "parse error after pragma");
3347 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3349 bool noref, is_static;
3351 uint32_t qflags = 0;
3352 ast_value *typevar = nullptr;
3353 char *vstring = nullptr;
3357 if (parser->tok == TOKEN_IDENT)
3358 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3360 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3362 /* local variable */
3364 parseerror(parser, "cannot declare a variable from here");
3367 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3368 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3371 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, nullptr))
3375 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3377 if (cvq == CV_WRONG)
3379 return parse_variable(parser, block, false, cvq, nullptr, noref, is_static, qflags, vstring);
3381 else if (parser->tok == TOKEN_KEYWORD)
3383 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3388 if (!parser_next(parser)) {
3389 parseerror(parser, "parse error after __builtin_debug_printtype");
3393 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3395 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3396 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->m_name, ty);
3397 if (!parser_next(parser)) {
3398 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3404 if (!parse_statement(parser, block, out, allow_cases))
3407 con_out("__builtin_debug_printtype: got no output node\n");
3410 ast_type_to_string(*out, ty, sizeof(ty));
3411 con_out("__builtin_debug_printtype: `%s`\n", ty);
3416 else if (!strcmp(parser_tokval(parser), "return"))
3418 return parse_return(parser, block, out);
3420 else if (!strcmp(parser_tokval(parser), "if"))
3422 return parse_if(parser, block, out);
3424 else if (!strcmp(parser_tokval(parser), "while"))
3426 return parse_while(parser, block, out);
3428 else if (!strcmp(parser_tokval(parser), "do"))
3430 return parse_dowhile(parser, block, out);
3432 else if (!strcmp(parser_tokval(parser), "for"))
3434 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3435 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3438 return parse_for(parser, block, out);
3440 else if (!strcmp(parser_tokval(parser), "break"))
3442 return parse_break_continue(parser, block, out, false);
3444 else if (!strcmp(parser_tokval(parser), "continue"))
3446 return parse_break_continue(parser, block, out, true);
3448 else if (!strcmp(parser_tokval(parser), "switch"))
3450 return parse_switch(parser, block, out);
3452 else if (!strcmp(parser_tokval(parser), "case") ||
3453 !strcmp(parser_tokval(parser), "default"))
3456 parseerror(parser, "unexpected 'case' label");
3461 else if (!strcmp(parser_tokval(parser), "goto"))
3463 return parse_goto(parser, out);
3465 else if (!strcmp(parser_tokval(parser), "typedef"))
3467 if (!parser_next(parser)) {
3468 parseerror(parser, "expected type definition after 'typedef'");
3471 return parse_typedef(parser);
3473 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3476 else if (parser->tok == '{')
3479 inner = parse_block(parser);
3482 *out = (ast_expression*)inner;
3485 else if (parser->tok == ':')
3489 if (!parser_next(parser)) {
3490 parseerror(parser, "expected label name");
3493 if (parser->tok != TOKEN_IDENT) {
3494 parseerror(parser, "label must be an identifier");
3497 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3499 if (!label->m_undefined) {
3500 parseerror(parser, "label `%s` already defined", label->m_name);
3503 label->m_undefined = false;
3506 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3507 parser->labels.push_back(label);
3509 *out = (ast_expression*)label;
3510 if (!parser_next(parser)) {
3511 parseerror(parser, "parse error after label");
3514 for (i = 0; i < parser->gotos.size(); ++i) {
3515 if (!strcmp(parser->gotos[i]->m_name, label->m_name)) {
3516 ast_goto_set_label(parser->gotos[i], label);
3517 parser->gotos.erase(parser->gotos.begin() + i);
3523 else if (parser->tok == ';')
3525 if (!parser_next(parser)) {
3526 parseerror(parser, "parse error after empty statement");
3533 lex_ctx_t ctx = parser_ctx(parser);
3534 ast_expression *exp = parse_expression(parser, false, false);
3538 if (!exp->m_side_effects) {
3539 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3546 static bool parse_enum(parser_t *parser)
3549 bool reverse = false;
3551 ast_value **values = nullptr;
3552 ast_value *var = nullptr;
3555 ast_expression *old;
3557 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3558 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3562 /* enumeration attributes (can add more later) */
3563 if (parser->tok == ':') {
3564 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3565 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3570 if (!strcmp(parser_tokval(parser), "flag")) {
3574 else if (!strcmp(parser_tokval(parser), "reverse")) {
3578 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3582 if (!parser_next(parser) || parser->tok != '{') {
3583 parseerror(parser, "expected `{` after enum attribute ");
3589 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3590 if (parser->tok == '}') {
3591 /* allow an empty enum */
3594 parseerror(parser, "expected identifier or `}`");
3598 old = parser_find_field(parser, parser_tokval(parser));
3600 old = parser_find_global(parser, parser_tokval(parser));
3602 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3603 parser_tokval(parser), old->m_context.file, old->m_context.line);
3607 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3608 vec_push(values, var);
3609 var->m_cvq = CV_CONST;
3610 var->m_hasvalue = true;
3612 /* for flagged enumerations increment in POTs of TWO */
3613 var->m_constval.vfloat = (flag) ? (num *= 2) : (num ++);
3614 parser_addglobal(parser, var->m_name, (ast_expression*)var);
3616 if (!parser_next(parser)) {
3617 parseerror(parser, "expected `=`, `}` or comma after identifier");
3621 if (parser->tok == ',')
3623 if (parser->tok == '}')
3625 if (parser->tok != '=') {
3626 parseerror(parser, "expected `=`, `}` or comma after identifier");
3630 if (!parser_next(parser)) {
3631 parseerror(parser, "expected expression after `=`");
3635 /* We got a value! */
3636 old = parse_expression_leave(parser, true, false, false);
3637 asvalue = (ast_value*)old;
3638 if (!ast_istype(old, ast_value) || asvalue->m_cvq != CV_CONST || !asvalue->m_hasvalue) {
3639 compile_error(var->m_context, "constant value or expression expected");
3642 num = (var->m_constval.vfloat = asvalue->m_constval.vfloat) + 1;
3644 if (parser->tok == '}')
3646 if (parser->tok != ',') {
3647 parseerror(parser, "expected `}` or comma after expression");
3652 /* patch them all (for reversed attribute) */
3655 for (i = 0; i < vec_size(values); i++)
3656 values[i]->m_constval.vfloat = vec_size(values) - i - 1;
3659 if (parser->tok != '}') {
3660 parseerror(parser, "internal error: breaking without `}`");
3664 if (!parser_next(parser) || parser->tok != ';') {
3665 parseerror(parser, "expected semicolon after enumeration");
3669 if (!parser_next(parser)) {
3670 parseerror(parser, "parse error after enumeration");
3682 static bool parse_block_into(parser_t *parser, ast_block *block)
3686 parser_enterblock(parser);
3688 if (!parser_next(parser)) { /* skip the '{' */
3689 parseerror(parser, "expected function body");
3693 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3695 ast_expression *expr = nullptr;
3696 if (parser->tok == '}')
3699 if (!parse_statement(parser, block, &expr, false)) {
3700 /* parseerror(parser, "parse error"); */
3706 if (!ast_block_add_expr(block, expr)) {
3713 if (parser->tok != '}') {
3716 (void)parser_next(parser);
3720 if (!parser_leaveblock(parser))
3722 return retval && !!block;
3725 static ast_block* parse_block(parser_t *parser)
3728 block = ast_block_new(parser_ctx(parser));
3731 if (!parse_block_into(parser, block)) {
3732 ast_block_delete(block);
3738 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3740 if (parser->tok == '{') {
3741 *out = (ast_expression*)parse_block(parser);
3744 return parse_statement(parser, nullptr, out, false);
3747 static bool create_vector_members(ast_value *var, ast_member **me)
3750 size_t len = strlen(var->m_name);
3752 for (i = 0; i < 3; ++i) {
3753 char *name = (char*)mem_a(len+3);
3754 memcpy(name, var->m_name, len);
3756 name[len+1] = 'x'+i;
3758 me[i] = ast_member_new(var->m_context, (ast_expression*)var, i, name);
3767 do { ast_member_delete(me[--i]); } while(i);
3771 static bool parse_function_body(parser_t *parser, ast_value *var)
3773 ast_block *block = nullptr;
3777 ast_expression *framenum = nullptr;
3778 ast_expression *nextthink = nullptr;
3779 /* None of the following have to be deleted */
3780 ast_expression *fld_think = nullptr, *fld_nextthink = nullptr, *fld_frame = nullptr;
3781 ast_expression *gbl_time = nullptr, *gbl_self = nullptr;
3782 bool has_frame_think;
3786 has_frame_think = false;
3787 old = parser->function;
3789 if (var->m_flags & AST_FLAG_ALIAS) {
3790 parseerror(parser, "function aliases cannot have bodies");
3794 if (parser->gotos.size() || parser->labels.size()) {
3795 parseerror(parser, "gotos/labels leaking");
3799 if (!OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC) {
3800 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3801 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3807 if (parser->tok == '[') {
3808 /* got a frame definition: [ framenum, nextthink ]
3809 * this translates to:
3810 * self.frame = framenum;
3811 * self.nextthink = time + 0.1;
3812 * self.think = nextthink;
3814 nextthink = nullptr;
3816 fld_think = parser_find_field(parser, "think");
3817 fld_nextthink = parser_find_field(parser, "nextthink");
3818 fld_frame = parser_find_field(parser, "frame");
3819 if (!fld_think || !fld_nextthink || !fld_frame) {
3820 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3821 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3824 gbl_time = parser_find_global(parser, "time");
3825 gbl_self = parser_find_global(parser, "self");
3826 if (!gbl_time || !gbl_self) {
3827 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3828 parseerror(parser, "please declare the following globals: `time`, `self`");
3832 if (!parser_next(parser))
3835 framenum = parse_expression_leave(parser, true, false, false);
3837 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3840 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->m_hasvalue) {
3841 ast_unref(framenum);
3842 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3846 if (parser->tok != ',') {
3847 ast_unref(framenum);
3848 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3849 parseerror(parser, "Got a %i\n", parser->tok);
3853 if (!parser_next(parser)) {
3854 ast_unref(framenum);
3858 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3860 /* qc allows the use of not-yet-declared functions here
3861 * - this automatically creates a prototype */
3862 ast_value *thinkfunc;
3863 ast_expression *functype = fld_think->m_next;
3865 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->m_vtype);
3866 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3867 ast_unref(framenum);
3868 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3871 ast_type_adopt(thinkfunc, functype);
3873 if (!parser_next(parser)) {
3874 ast_unref(framenum);
3875 ast_delete(thinkfunc);
3879 parser_addglobal(parser, thinkfunc->m_name, (ast_expression*)thinkfunc);
3881 nextthink = (ast_expression*)thinkfunc;
3884 nextthink = parse_expression_leave(parser, true, false, false);
3886 ast_unref(framenum);
3887 parseerror(parser, "expected a think-function in [frame,think] notation");
3892 if (!ast_istype(nextthink, ast_value)) {
3893 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3897 if (retval && parser->tok != ']') {
3898 parseerror(parser, "expected closing `]` for [frame,think] notation");
3902 if (retval && !parser_next(parser)) {
3906 if (retval && parser->tok != '{') {
3907 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3912 ast_unref(nextthink);
3913 ast_unref(framenum);
3917 has_frame_think = true;
3920 block = ast_block_new(parser_ctx(parser));
3922 parseerror(parser, "failed to allocate block");
3923 if (has_frame_think) {
3924 ast_unref(nextthink);
3925 ast_unref(framenum);
3930 if (has_frame_think) {
3931 if (!OPTS_FLAG(EMULATE_STATE)) {
3932 ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
3933 if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
3934 parseerror(parser, "failed to generate state op for [frame,think]");
3935 ast_unref(nextthink);
3936 ast_unref(framenum);
3941 /* emulate OP_STATE in code: */
3943 ast_expression *self_frame;
3944 ast_expression *self_nextthink;
3945 ast_expression *self_think;
3946 ast_expression *time_plus_1;
3947 ast_store *store_frame;
3948 ast_store *store_nextthink;
3949 ast_store *store_think;
3951 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3953 ctx = parser_ctx(parser);
3954 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3955 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3956 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3958 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3959 gbl_time, (ast_expression*)parser->m_fold.constgen_float(frame_delta, false));
3961 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3962 if (self_frame) ast_delete(self_frame);
3963 if (self_nextthink) ast_delete(self_nextthink);
3964 if (self_think) ast_delete(self_think);
3965 if (time_plus_1) ast_delete(time_plus_1);
3971 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3972 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3973 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3976 ast_delete(self_frame);
3979 if (!store_nextthink) {
3980 ast_delete(self_nextthink);
3984 ast_delete(self_think);
3988 if (store_frame) ast_delete(store_frame);
3989 if (store_nextthink) ast_delete(store_nextthink);
3990 if (store_think) ast_delete(store_think);
3993 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3994 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3995 !ast_block_add_expr(block, (ast_expression*)store_think))
4002 parseerror(parser, "failed to generate code for [frame,think]");
4003 ast_unref(nextthink);
4004 ast_unref(framenum);
4011 if (var->m_hasvalue) {
4012 if (!(var->m_flags & AST_FLAG_ACCUMULATE)) {
4013 parseerror(parser, "function `%s` declared with multiple bodies", var->m_name);
4014 ast_block_delete(block);
4017 func = var->m_constval.vfunc;
4020 parseerror(parser, "internal error: nullptr function: `%s`", var->m_name);
4021 ast_block_delete(block);
4025 func = ast_function_new(var->m_context, var->m_name, var);
4028 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
4029 ast_block_delete(block);
4032 parser->functions.push_back(func);
4035 parser_enterblock(parser);
4037 for (auto &it : var->m_type_params) {
4041 if (it->m_vtype != TYPE_VECTOR &&
4042 (it->m_vtype != TYPE_FIELD ||
4043 it->m_next->m_vtype != TYPE_VECTOR))
4048 if (!create_vector_members(it, me)) {
4049 ast_block_delete(block);
4053 for (e = 0; e < 3; ++e) {
4054 parser_addlocal(parser, me[e]->m_name, (ast_expression*)me[e]);
4055 ast_block_collect(block, (ast_expression*)me[e]);
4059 if (var->m_argcounter && !func->m_argc) {
4060 ast_value *argc = ast_value_new(var->m_context, var->m_argcounter, TYPE_FLOAT);
4061 parser_addlocal(parser, argc->m_name, (ast_expression*)argc);
4062 func->m_argc = argc;
4065 if (OPTS_FLAG(VARIADIC_ARGS) && var->m_flags & AST_FLAG_VARIADIC && !func->m_varargs) {
4067 ast_value *varargs = ast_value_new(var->m_context, "reserved:va_args", TYPE_ARRAY);
4068 varargs->m_flags |= AST_FLAG_IS_VARARG;
4069 varargs->m_next = (ast_expression*)ast_value_new(var->m_context, nullptr, TYPE_VECTOR);
4070 varargs->m_count = 0;
4071 util_snprintf(name, sizeof(name), "%s##va##SET", var->m_name);
4072 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4073 ast_delete(varargs);
4074 ast_block_delete(block);
4077 util_snprintf(name, sizeof(name), "%s##va##GET", var->m_name);
4078 if (!parser_create_array_getter_proto(parser, varargs, varargs->m_next, name)) {
4079 ast_delete(varargs);
4080 ast_block_delete(block);
4083 func->m_varargs = varargs;
4084 func->m_fixedparams = (ast_value*)parser->m_fold.constgen_float(var->m_type_params.size(), false);
4087 parser->function = func;
4088 if (!parse_block_into(parser, block)) {
4089 ast_block_delete(block);
4093 func->m_blocks.emplace_back(block);
4095 parser->function = old;
4096 if (!parser_leaveblock(parser))
4098 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4099 parseerror(parser, "internal error: local scopes left");
4103 if (parser->tok == ';')
4104 return parser_next(parser);
4105 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4106 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4110 (void)!parser_leaveblock(parser);
4111 parser->functions.pop_back();
4112 ast_function_delete(func);
4113 var->m_constval.vfunc = nullptr;
4116 parser->function = old;
4120 static ast_expression *array_accessor_split(
4125 ast_expression *left,
4126 ast_expression *right
4132 lex_ctx_t ctx = array->m_context;
4134 if (!left || !right) {
4135 if (left) ast_delete(left);
4136 if (right) ast_delete(right);
4140 cmp = ast_binary_new(ctx, INSTR_LT,
4141 (ast_expression*)index,
4142 (ast_expression*)parser->m_fold.constgen_float(middle, false));
4146 parseerror(parser, "internal error: failed to create comparison for array setter");
4150 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4152 ast_delete(cmp); /* will delete left and right */
4153 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4157 return (ast_expression*)ifthen;
4160 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4162 lex_ctx_t ctx = array->m_context;
4164 if (from+1 == afterend) {
4165 /* set this value */
4168 ast_array_index *subscript;
4170 int assignop = type_store_instr[value->m_vtype];
4172 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4173 assignop = INSTR_STORE_V;
4175 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4179 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4181 ast_delete(subscript);
4185 block = ast_block_new(ctx);
4191 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4196 ret = ast_return_new(ctx, nullptr);
4202 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4207 return (ast_expression*)block;
4209 ast_expression *left, *right;
4210 size_t diff = afterend - from;
4211 size_t middle = from + diff/2;
4212 left = array_setter_node(parser, array, index, value, from, middle);
4213 right = array_setter_node(parser, array, index, value, middle, afterend);
4214 return array_accessor_split(parser, array, index, middle, left, right);
4218 static ast_expression *array_field_setter_node(
4227 lex_ctx_t ctx = array->m_context;
4229 if (from+1 == afterend) {
4230 /* set this value */
4233 ast_entfield *entfield;
4234 ast_array_index *subscript;
4236 int assignop = type_storep_instr[value->m_vtype];
4238 if (value->m_vtype == TYPE_FIELD && value->m_next->m_vtype == TYPE_VECTOR)
4239 assignop = INSTR_STOREP_V;
4241 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4245 subscript->m_next = ast_type_copy(subscript->m_context, (ast_expression*)subscript);
4246 subscript->m_vtype = TYPE_FIELD;
4248 entfield = ast_entfield_new_force(ctx,
4249 (ast_expression*)entity,
4250 (ast_expression*)subscript,
4251 (ast_expression*)subscript);
4253 ast_delete(subscript);
4257 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4259 ast_delete(entfield);
4263 block = ast_block_new(ctx);
4269 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4274 ret = ast_return_new(ctx, nullptr);
4280 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4285 return (ast_expression*)block;
4287 ast_expression *left, *right;
4288 size_t diff = afterend - from;
4289 size_t middle = from + diff/2;
4290 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4291 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4292 return array_accessor_split(parser, array, index, middle, left, right);
4296 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4298 lex_ctx_t ctx = array->m_context;
4300 if (from+1 == afterend) {
4302 ast_array_index *subscript;
4304 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser->m_fold.constgen_float(from, false));
4308 ret = ast_return_new(ctx, (ast_expression*)subscript);
4310 ast_delete(subscript);
4314 return (ast_expression*)ret;
4316 ast_expression *left, *right;
4317 size_t diff = afterend - from;
4318 size_t middle = from + diff/2;
4319 left = array_getter_node(parser, array, index, from, middle);
4320 right = array_getter_node(parser, array, index, middle, afterend);
4321 return array_accessor_split(parser, array, index, middle, left, right);
4325 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4327 ast_function *func = nullptr;
4328 ast_value *fval = nullptr;
4329 ast_block *body = nullptr;
4331 fval = ast_value_new(array->m_context, funcname, TYPE_FUNCTION);
4333 parseerror(parser, "failed to create accessor function value");
4336 fval->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
4338 func = ast_function_new(array->m_context, funcname, fval);
4341 parseerror(parser, "failed to create accessor function node");
4345 body = ast_block_new(array->m_context);
4347 parseerror(parser, "failed to create block for array accessor");
4353 func->m_blocks.emplace_back(body);
4356 parser->accessors.push_back(fval);
4361 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4363 ast_value *index = nullptr;
4364 ast_value *value = nullptr;
4368 if (!ast_istype(array->m_next, ast_value)) {
4369 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4373 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4375 func = fval->m_constval.vfunc;
4376 fval->m_next = (ast_expression*)ast_value_new(array->m_context, "<void>", TYPE_VOID);
4378 index = ast_value_new(array->m_context, "index", TYPE_FLOAT);
4379 value = ast_value_copy((ast_value*)array->m_next);
4381 if (!index || !value) {
4382 parseerror(parser, "failed to create locals for array accessor");
4385 (void)!ast_value_set_name(value, "value"); /* not important */
4386 fval->m_type_params.push_back(index);
4387 fval->m_type_params.push_back(value);
4389 array->m_setter = fval;
4392 if (index) ast_delete(index);
4393 if (value) ast_delete(value);
4399 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4401 ast_expression *root = nullptr;
4402 root = array_setter_node(parser, array,
4403 array->m_setter->m_type_params[0],
4404 array->m_setter->m_type_params[1],
4407 parseerror(parser, "failed to build accessor search tree");
4410 if (!ast_block_add_expr(array->m_setter->m_constval.vfunc->m_blocks[0].get(), root)) {
4417 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4419 if (!parser_create_array_setter_proto(parser, array, funcname))
4421 return parser_create_array_setter_impl(parser, array);
4424 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4426 ast_expression *root = nullptr;
4427 ast_value *entity = nullptr;
4428 ast_value *index = nullptr;
4429 ast_value *value = nullptr;
4433 if (!ast_istype(array->m_next, ast_value)) {
4434 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4438 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4440 func = fval->m_constval.vfunc;
4441 fval->m_next = (ast_expression*)ast_value_new(array->m_context, "<void>", TYPE_VOID);
4443 entity = ast_value_new(array->m_context, "entity", TYPE_ENTITY);
4444 index = ast_value_new(array->m_context, "index", TYPE_FLOAT);
4445 value = ast_value_copy((ast_value*)array->m_next);
4446 if (!entity || !index || !value) {
4447 parseerror(parser, "failed to create locals for array accessor");
4450 (void)!ast_value_set_name(value, "value"); /* not important */
4451 fval->m_type_params.push_back(entity);
4452 fval->m_type_params.push_back(index);
4453 fval->m_type_params.push_back(value);
4455 root = array_field_setter_node(parser, array, entity, index, value, 0, array->m_count);
4457 parseerror(parser, "failed to build accessor search tree");
4461 array->m_setter = fval;
4462 return ast_block_add_expr(func->m_blocks[0].get(), root);
4464 if (entity) ast_delete(entity);
4465 if (index) ast_delete(index);
4466 if (value) ast_delete(value);
4467 if (root) ast_delete(root);
4473 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4475 ast_value *index = nullptr;
4479 /* NOTE: checking array->m_next rather than elemtype since
4480 * for fields elemtype is a temporary fieldtype.
4482 if (!ast_istype(array->m_next, ast_value)) {
4483 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4487 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4489 func = fval->m_constval.vfunc;
4490 fval->m_next = ast_type_copy(array->m_context, elemtype);
4492 index = ast_value_new(array->m_context, "index", TYPE_FLOAT);
4495 parseerror(parser, "failed to create locals for array accessor");
4498 fval->m_type_params.push_back(index);
4500 array->m_getter = fval;
4503 if (index) ast_delete(index);
4509 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4511 ast_expression *root = nullptr;
4513 root = array_getter_node(parser, array, array->m_getter->m_type_params[0], 0, array->m_count);
4515 parseerror(parser, "failed to build accessor search tree");
4518 if (!ast_block_add_expr(array->m_getter->m_constval.vfunc->m_blocks[0].get(), root)) {
4525 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4527 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4529 return parser_create_array_getter_impl(parser, array);
4532 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4534 lex_ctx_t ctx = parser_ctx(parser);
4535 std::vector<ast_value *> params;
4538 bool variadic = false;
4539 ast_value *varparam = nullptr;
4540 char *argcounter = nullptr;
4542 /* for the sake of less code we parse-in in this function */
4543 if (!parser_next(parser)) {
4545 parseerror(parser, "expected parameter list");
4549 /* parse variables until we hit a closing paren */
4550 while (parser->tok != ')') {
4551 bool is_varargs = false;
4554 /* there must be commas between them */
4555 if (parser->tok != ',') {
4556 parseerror(parser, "expected comma or end of parameter list");
4559 if (!parser_next(parser)) {
4560 parseerror(parser, "expected parameter");
4566 ast_value *param = parse_typename(parser, nullptr, nullptr, &is_varargs);
4567 if (!param && !is_varargs)
4570 /* '...' indicates a varargs function */
4572 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4573 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4576 if (parser->tok == TOKEN_IDENT) {
4577 argcounter = util_strdup(parser_tokval(parser));
4578 if (!parser_next(parser) || parser->tok != ')') {
4579 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4584 params.push_back(param);
4585 if (param->m_vtype >= TYPE_VARIANT) {
4586 char tname[1024]; /* typename is reserved in C++ */
4587 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4588 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4591 /* type-restricted varargs */
4592 if (parser->tok == TOKEN_DOTS) {
4594 varparam = params.back();
4596 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4597 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4600 if (parser->tok == TOKEN_IDENT) {
4601 argcounter = util_strdup(parser_tokval(parser));
4602 ast_value_set_name(param, argcounter);
4603 if (!parser_next(parser) || parser->tok != ')') {
4604 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4609 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->m_name[0] == '<') {
4610 parseerror(parser, "parameter name omitted");
4616 if (params.size() == 1 && params[0]->m_vtype == TYPE_VOID)
4620 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4621 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4624 if (!parser_next(parser)) {
4625 parseerror(parser, "parse error after typename");
4629 /* now turn 'var' into a function type */
4630 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4631 fval->m_next = (ast_expression*)var;
4633 fval->m_flags |= AST_FLAG_VARIADIC;
4636 var->m_type_params = move(params);
4637 var->m_varparam = (ast_expression*)varparam;
4638 var->m_argcounter = argcounter;
4646 ast_delete(varparam);
4648 for (auto &it : params)
4653 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4655 ast_expression *cexp;
4656 ast_value *cval, *tmp;
4659 ctx = parser_ctx(parser);
4661 if (!parser_next(parser)) {
4663 parseerror(parser, "expected array-size");
4667 if (parser->tok != ']') {
4668 cexp = parse_expression_leave(parser, true, false, false);
4670 if (!cexp || !ast_istype(cexp, ast_value)) {
4674 parseerror(parser, "expected array-size as constant positive integer");
4677 cval = (ast_value*)cexp;
4684 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4685 tmp->m_next = (ast_expression*)var;
4689 if (cval->m_vtype == TYPE_INTEGER)
4690 tmp->m_count = cval->m_constval.vint;
4691 else if (cval->m_vtype == TYPE_FLOAT)
4692 tmp->m_count = cval->m_constval.vfloat;
4696 parseerror(parser, "array-size must be a positive integer constant");
4703 var->m_flags |= AST_FLAG_ARRAY_INIT;
4706 if (parser->tok != ']') {
4708 parseerror(parser, "expected ']' after array-size");
4711 if (!parser_next(parser)) {
4713 parseerror(parser, "error after parsing array size");
4719 /* Parse a complete typename.
4720 * for single-variables (ie. function parameters or typedefs) storebase should be nullptr
4721 * but when parsing variables separated by comma
4722 * 'storebase' should point to where the base-type should be kept.
4723 * The base type makes up every bit of type information which comes *before* the
4726 * NOTE: The value must either be named, have a nullptr name, or a name starting
4727 * with '<'. In the first case, this will be the actual variable or type
4728 * name, in the other cases it is assumed that the name will appear
4729 * later, and an error is generated otherwise.
4731 * The following will be parsed in its entirety:
4733 * The 'basetype' in this case is 'void()'
4734 * and if there's a comma after it, say:
4736 * then the type-information 'void()' can be stored in 'storebase'
4738 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4740 ast_value *var, *tmp;
4743 const char *name = nullptr;
4744 bool isfield = false;
4745 bool wasarray = false;
4746 size_t morefields = 0;
4748 bool vararg = (parser->tok == TOKEN_DOTS);
4750 ctx = parser_ctx(parser);
4752 /* types may start with a dot */
4753 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4755 if (parser->tok == TOKEN_DOTS)
4757 /* if we parsed a dot we need a typename now */
4758 if (!parser_next(parser)) {
4759 parseerror(parser, "expected typename for field definition");
4763 /* Further dots are handled seperately because they won't be part of the
4767 if (parser->tok == '.')
4769 else if (parser->tok == TOKEN_DOTS)
4774 if (!parser_next(parser)) {
4775 parseerror(parser, "expected typename for field definition");
4780 if (parser->tok == TOKEN_IDENT)
4781 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4782 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4783 if (vararg && is_vararg) {
4787 parseerror(parser, "expected typename");
4791 /* generate the basic type value */
4792 if (cached_typedef) {
4793 var = ast_value_copy(cached_typedef);
4794 ast_value_set_name(var, "<type(from_def)>");
4796 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4798 for (; morefields; --morefields) {
4799 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4800 tmp->m_next = (ast_expression*)var;
4804 /* do not yet turn into a field - remember:
4805 * .void() foo; is a field too
4806 * .void()() foo; is a function
4810 if (!parser_next(parser)) {
4812 parseerror(parser, "parse error after typename");
4816 /* an opening paren now starts the parameter-list of a function
4817 * this is where original-QC has parameter lists.
4818 * We allow a single parameter list here.
4819 * Much like fteqcc we don't allow `float()() x`
4821 if (parser->tok == '(') {
4822 var = parse_parameter_list(parser, var);
4827 /* store the base if requested */
4829 *storebase = ast_value_copy(var);
4831 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4832 tmp->m_next = (ast_expression*)*storebase;
4837 /* there may be a name now */
4838 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4839 if (!strcmp(parser_tokval(parser), "break"))
4840 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4841 else if (parser->tok == TOKEN_KEYWORD)
4844 name = util_strdup(parser_tokval(parser));
4847 if (!parser_next(parser)) {
4850 parseerror(parser, "error after variable or field declaration");
4856 /* now this may be an array */
4857 if (parser->tok == '[') {
4859 var = parse_arraysize(parser, var);
4861 if (name) mem_d(name);
4866 /* This is the point where we can turn it into a field */
4868 /* turn it into a field if desired */
4869 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4870 tmp->m_next = (ast_expression*)var;
4874 /* now there may be function parens again */
4875 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4876 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4877 if (parser->tok == '(' && wasarray)
4878 parseerror(parser, "arrays as part of a return type is not supported");
4879 while (parser->tok == '(') {
4880 var = parse_parameter_list(parser, var);
4882 if (name) mem_d(name);
4887 /* finally name it */
4889 if (!ast_value_set_name(var, name)) {
4892 parseerror(parser, "internal error: failed to set name");
4895 /* free the name, ast_value_set_name duplicates */
4902 static bool parse_typedef(parser_t *parser)
4904 ast_value *typevar, *oldtype;
4905 ast_expression *old;
4907 typevar = parse_typename(parser, nullptr, nullptr, nullptr);
4912 /* while parsing types, the ast_value's get named '<something>' */
4913 if (!typevar->m_name || typevar->m_name[0] == '<') {
4914 parseerror(parser, "missing name in typedef");
4915 ast_delete(typevar);
4919 if ( (old = parser_find_var(parser, typevar->m_name)) ) {
4920 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4921 " -> `%s` has been declared here: %s:%i",
4922 typevar->m_name, old->m_context.file, old->m_context.line);
4923 ast_delete(typevar);
4927 if ( (oldtype = parser_find_typedef(parser, typevar->m_name, vec_last(parser->_blocktypedefs))) ) {
4928 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4929 typevar->m_name, oldtype->m_context.file, oldtype->m_context.line);
4930 ast_delete(typevar);
4934 vec_push(parser->_typedefs, typevar);
4935 util_htset(vec_last(parser->typedefs), typevar->m_name, typevar);
4937 if (parser->tok != ';') {
4938 parseerror(parser, "expected semicolon after typedef");
4941 if (!parser_next(parser)) {
4942 parseerror(parser, "parse error after typedef");
4949 static const char *cvq_to_str(int cvq) {
4951 case CV_NONE: return "none";
4952 case CV_VAR: return "`var`";
4953 case CV_CONST: return "`const`";
4954 default: return "<INVALID>";
4958 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4961 if (proto->m_cvq != var->m_cvq) {
4962 if (!(proto->m_cvq == CV_CONST && var->m_cvq == CV_NONE &&
4963 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4964 parser->tok == '='))
4966 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4967 "`%s` declared with different qualifiers: %s\n"
4968 " -> previous declaration here: %s:%i uses %s",
4969 var->m_name, cvq_to_str(var->m_cvq),
4970 proto->m_context.file, proto->m_context.line,
4971 cvq_to_str(proto->m_cvq));
4974 av = (var ->m_flags & AST_FLAG_NORETURN);
4975 ao = (proto->m_flags & AST_FLAG_NORETURN);
4977 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4978 "`%s` declared with different attributes%s\n"
4979 " -> previous declaration here: %s:%i",
4980 var->m_name, (av ? ": noreturn" : ""),
4981 proto->m_context.file, proto->m_context.line,
4982 (ao ? ": noreturn" : ""));
4987 static bool create_array_accessors(parser_t *parser, ast_value *var)
4990 util_snprintf(name, sizeof(name), "%s##SET", var->m_name);
4991 if (!parser_create_array_setter(parser, var, name))
4993 util_snprintf(name, sizeof(name), "%s##GET", var->m_name);
4994 if (!parser_create_array_getter(parser, var, var->m_next, name))
4999 static bool parse_array(parser_t *parser, ast_value *array)
5002 if (array->m_initlist.size()) {
5003 parseerror(parser, "array already initialized elsewhere");
5006 if (!parser_next(parser)) {
5007 parseerror(parser, "parse error in array initializer");
5011 while (parser->tok != '}') {
5012 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5015 if (!ast_istype(v, ast_value) || !v->m_hasvalue || v->m_cvq != CV_CONST) {
5017 parseerror(parser, "initializing element must be a compile time constant");
5020 array->m_initlist.push_back(v->m_constval);
5021 if (v->m_vtype == TYPE_STRING) {
5022 array->m_initlist[i].vstring = util_strdupe(array->m_initlist[i].vstring);
5026 if (parser->tok == '}')
5028 if (parser->tok != ',' || !parser_next(parser)) {
5029 parseerror(parser, "expected comma or '}' in element list");
5033 if (!parser_next(parser) || parser->tok != ';') {
5034 parseerror(parser, "expected semicolon after initializer, got %s");
5038 if (!parser_next(parser)) {
5039 parseerror(parser, "parse error after initializer");
5044 if (array->m_flags & AST_FLAG_ARRAY_INIT) {
5045 if (array->m_count != (size_t)-1) {
5046 parseerror(parser, "array `%s' has already been initialized with %u elements",
5047 array->m_name, (unsigned)array->m_count);
5049 array->m_count = array->m_initlist.size();
5050 if (!create_array_accessors(parser, array))
5056 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)
5060 ast_expression *old;
5064 ast_value *basetype = nullptr;
5066 bool isparam = false;
5067 bool isvector = false;
5068 bool cleanvar = true;
5069 bool wasarray = false;
5071 ast_member *me[3] = { nullptr, nullptr, nullptr };
5072 ast_member *last_me[3] = { nullptr, nullptr, nullptr };
5074 if (!localblock && is_static)
5075 parseerror(parser, "`static` qualifier is not supported in global scope");
5077 /* get the first complete variable */
5078 var = parse_typename(parser, &basetype, cached_typedef, nullptr);
5081 ast_delete(basetype);
5085 /* while parsing types, the ast_value's get named '<something>' */
5086 if (!var->m_name || var->m_name[0] == '<') {
5087 parseerror(parser, "declaration does not declare anything");
5089 ast_delete(basetype);
5097 /* Part 0: finish the type */
5098 if (parser->tok == '(') {
5099 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5100 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5101 var = parse_parameter_list(parser, var);
5107 /* we only allow 1-dimensional arrays */
5108 if (parser->tok == '[') {
5110 var = parse_arraysize(parser, var);
5116 if (parser->tok == '(' && wasarray) {
5117 parseerror(parser, "arrays as part of a return type is not supported");
5118 /* we'll still parse the type completely for now */
5120 /* for functions returning functions */
5121 while (parser->tok == '(') {
5122 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5123 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5124 var = parse_parameter_list(parser, var);
5131 var->m_cvq = qualifier;
5132 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5133 var->m_flags &= ~(AST_FLAG_COVERAGE_MASK);
5134 var->m_flags |= qflags;
5137 * store the vstring back to var for alias and
5138 * deprecation messages.
5140 if (var->m_flags & AST_FLAG_DEPRECATED ||
5141 var->m_flags & AST_FLAG_ALIAS)
5142 var->m_desc = vstring;
5144 if (parser_find_global(parser, var->m_name) && var->m_flags & AST_FLAG_ALIAS) {
5145 parseerror(parser, "function aliases cannot be forward declared");
5152 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5153 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5154 * is then filled with the previous definition and the parameter-names replaced.
5156 if (!strcmp(var->m_name, "nil")) {
5157 if (OPTS_FLAG(UNTYPED_NIL)) {
5158 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5159 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5161 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5164 /* Deal with end_sys_ vars */
5166 if (!strcmp(var->m_name, "end_sys_globals")) {
5168 parser->crc_globals = parser->globals.size();
5171 else if (!strcmp(var->m_name, "end_sys_fields")) {
5173 parser->crc_fields = parser->fields.size();
5176 if (was_end && var->m_vtype == TYPE_FIELD) {
5177 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5178 "global '%s' hint should not be a field",
5179 parser_tokval(parser)))
5186 if (!nofields && var->m_vtype == TYPE_FIELD)
5188 /* deal with field declarations */
5189 old = parser_find_field(parser, var->m_name);
5191 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5192 var->m_name, old->m_context.file, (int)old->m_context.line))
5201 parseerror(parser, "field `%s` already declared here: %s:%i",
5202 var->m_name, old->m_context.file, old->m_context.line);
5207 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5208 (old = parser_find_global(parser, var->m_name)))
5210 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5211 parseerror(parser, "field `%s` already declared here: %s:%i",
5212 var->m_name, old->m_context.file, old->m_context.line);
5219 /* deal with other globals */
5220 old = parser_find_global(parser, var->m_name);
5221 if (old && var->m_vtype == TYPE_FUNCTION && old->m_vtype == TYPE_FUNCTION)
5223 /* This is a function which had a prototype */
5224 if (!ast_istype(old, ast_value)) {
5225 parseerror(parser, "internal error: prototype is not an ast_value");
5229 proto = (ast_value*)old;
5230 proto->m_desc = var->m_desc;
5231 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5232 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5234 proto->m_context.file, proto->m_context.line);
5238 /* we need the new parameter-names */
5239 for (i = 0; i < proto->m_type_params.size(); ++i)
5240 ast_value_set_name(proto->m_type_params[i], var->m_type_params[i]->m_name);
5241 if (!parser_check_qualifiers(parser, var, proto)) {
5244 mem_d(proto->m_desc);
5248 proto->m_flags |= var->m_flags;
5256 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5257 "global `%s` already declared here: %s:%i",
5258 var->m_name, old->m_context.file, old->m_context.line))
5263 if (old->m_flags & AST_FLAG_FINAL_DECL) {
5264 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5265 var->m_name, old->m_context.file, old->m_context.line);
5269 proto = (ast_value*)old;
5270 if (!ast_istype(old, ast_value)) {
5271 parseerror(parser, "internal error: not an ast_value");
5276 if (!parser_check_qualifiers(parser, var, proto)) {
5281 proto->m_flags |= var->m_flags;
5282 /* copy the context for finals,
5283 * so the error can show where it was actually made 'final'
5285 if (proto->m_flags & AST_FLAG_FINAL_DECL)
5286 old->m_context = var->m_context;
5290 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5291 (old = parser_find_field(parser, var->m_name)))
5293 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5294 parseerror(parser, "global `%s` already declared here: %s:%i",
5295 var->m_name, old->m_context.file, old->m_context.line);
5302 else /* it's not a global */
5304 old = parser_find_local(parser, var->m_name, vec_size(parser->variables)-1, &isparam);
5305 if (old && !isparam) {
5306 parseerror(parser, "local `%s` already declared here: %s:%i",
5307 var->m_name, old->m_context.file, (int)old->m_context.line);
5311 /* doing this here as the above is just for a single scope */
5312 old = parser_find_local(parser, var->m_name, 0, &isparam);
5313 if (old && isparam) {
5314 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5315 "local `%s` is shadowing a parameter", var->m_name))
5317 parseerror(parser, "local `%s` already declared here: %s:%i",
5318 var->m_name, old->m_context.file, (int)old->m_context.line);
5322 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5324 if (ast_istype(old, ast_value))
5325 var = proto = (ast_value*)old;
5334 /* in a noref section we simply bump the usecount */
5335 if (noref || parser->noref)
5339 * Create the global/local, and deal with vector types.
5342 if (var->m_vtype == TYPE_VECTOR)
5344 else if (var->m_vtype == TYPE_FIELD &&
5345 var->m_next->m_vtype == TYPE_VECTOR)
5349 if (!create_vector_members(var, me)) {
5356 /* deal with global variables, fields, functions */
5357 if (!nofields && var->m_vtype == TYPE_FIELD && parser->tok != '=') {
5358 var->m_isfield = true;
5359 parser->fields.push_back((ast_expression*)var);
5360 util_htset(parser->htfields, var->m_name, var);
5362 for (i = 0; i < 3; ++i) {
5363 parser->fields.push_back((ast_expression*)me[i]);
5364 util_htset(parser->htfields, me[i]->m_name, me[i]);
5369 if (!(var->m_flags & AST_FLAG_ALIAS)) {
5370 parser_addglobal(parser, var->m_name, (ast_expression*)var);
5372 for (i = 0; i < 3; ++i) {
5373 parser_addglobal(parser, me[i]->m_name, (ast_expression*)me[i]);
5377 ast_expression *find = parser_find_global(parser, var->m_desc);
5380 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->m_desc, var->m_name);
5384 if (!ast_compare_type((ast_expression*)var, find)) {
5388 ast_type_to_string(find, ty1, sizeof(ty1));
5389 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5391 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5392 ty1, ty2, var->m_name
5397 util_htset(parser->aliases, var->m_name, find);
5399 /* generate aliases for vector components */
5403 util_asprintf(&buffer[0], "%s_x", var->m_desc);
5404 util_asprintf(&buffer[1], "%s_y", var->m_desc);
5405 util_asprintf(&buffer[2], "%s_z", var->m_desc);
5407 util_htset(parser->aliases, me[0]->m_name, parser_find_global(parser, buffer[0]));
5408 util_htset(parser->aliases, me[1]->m_name, parser_find_global(parser, buffer[1]));
5409 util_htset(parser->aliases, me[2]->m_name, parser_find_global(parser, buffer[2]));
5419 /* a static adds itself to be generated like any other global
5420 * but is added to the local namespace instead
5422 char *defname = nullptr;
5423 size_t prefix_len, ln;
5426 ln = strlen(parser->function->m_name);
5427 vec_append(defname, ln, parser->function->m_name);
5429 vec_append(defname, 2, "::");
5430 /* remember the length up to here */
5431 prefix_len = vec_size(defname);
5433 /* Add it to the local scope */
5434 util_htset(vec_last(parser->variables), var->m_name, (void*)var);
5436 /* now rename the global */
5437 ln = strlen(var->m_name);
5438 vec_append(defname, ln, var->m_name);
5439 /* if a variable of that name already existed, add the
5441 * The counter is incremented either way.
5443 sn_size = parser->function->m_static_names.size();
5444 for (sn = 0; sn != sn_size; ++sn) {
5445 if (strcmp(parser->function->m_static_names[sn], var->m_name) == 0)
5448 if (sn != sn_size) {
5449 char *num = nullptr;
5450 int len = util_asprintf(&num, "#%u", parser->function->m_static_count);
5451 vec_append(defname, len, num);
5455 parser->function->m_static_names.push_back(util_strdup(var->m_name));
5456 parser->function->m_static_count++;
5457 ast_value_set_name(var, defname);
5459 /* push it to the to-be-generated globals */
5460 parser->globals.push_back((ast_expression*)var);
5462 /* same game for the vector members */
5464 for (i = 0; i < 3; ++i) {
5465 util_htset(vec_last(parser->variables), me[i]->m_name, (void*)(me[i]));
5467 vec_shrinkto(defname, prefix_len);
5468 ln = strlen(me[i]->m_name);
5469 vec_append(defname, ln, me[i]->m_name);
5470 ast_member_set_name(me[i], defname);
5472 parser->globals.push_back((ast_expression*)me[i]);
5477 localblock->m_locals.push_back(var);
5478 parser_addlocal(parser, var->m_name, (ast_expression*)var);
5480 for (i = 0; i < 3; ++i) {
5481 parser_addlocal(parser, me[i]->m_name, (ast_expression*)me[i]);
5482 ast_block_collect(localblock, (ast_expression*)me[i]);
5488 memcpy(last_me, me, sizeof(me));
5489 me[0] = me[1] = me[2] = nullptr;
5494 if (var->m_vtype == TYPE_ARRAY) {
5495 if (var->m_count != (size_t)-1) {
5496 if (!create_array_accessors(parser, var))
5500 else if (!localblock && !nofields &&
5501 var->m_vtype == TYPE_FIELD &&
5502 var->m_next->m_vtype == TYPE_ARRAY)
5505 ast_expression *telem;
5507 ast_value *array = (ast_value*)var->m_next;
5509 if (!ast_istype(var->m_next, ast_value)) {
5510 parseerror(parser, "internal error: field element type must be an ast_value");
5514 util_snprintf(name, sizeof(name), "%s##SETF", var->m_name);
5515 if (!parser_create_array_field_setter(parser, array, name))
5518 telem = ast_type_copy(var->m_context, array->m_next);
5519 tfield = ast_value_new(var->m_context, "<.type>", TYPE_FIELD);
5520 tfield->m_next = telem;
5521 util_snprintf(name, sizeof(name), "%s##GETFP", var->m_name);
5522 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5530 if (parser->tok == ';') {
5531 ast_delete(basetype);
5532 if (!parser_next(parser)) {
5533 parseerror(parser, "error after variable declaration");
5539 if (parser->tok == ',')
5543 if (!var || (!localblock && !nofields && basetype->m_vtype == TYPE_FIELD)) {
5546 parseerror(parser, "missing comma or semicolon while parsing variables");
5550 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5551 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5552 "initializing expression turns variable `%s` into a constant in this standard",
5559 if (parser->tok != '{' || var->m_vtype != TYPE_FUNCTION) {
5560 if (parser->tok != '=') {
5561 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5565 if (!parser_next(parser)) {
5566 parseerror(parser, "error parsing initializer");
5570 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5571 parseerror(parser, "expected '=' before function body in this standard");
5574 if (parser->tok == '#') {
5575 ast_function *func = nullptr;
5576 ast_value *number = nullptr;
5582 parseerror(parser, "cannot declare builtins within functions");
5585 if (var->m_vtype != TYPE_FUNCTION) {
5586 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->m_name);
5589 if (!parser_next(parser)) {
5590 parseerror(parser, "expected builtin number");
5594 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5595 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5597 parseerror(parser, "builtin number expected");
5600 if (!ast_istype(number, ast_value) || !number->m_hasvalue || number->m_cvq != CV_CONST)
5603 parseerror(parser, "builtin number must be a compile time constant");
5606 if (number->m_vtype == TYPE_INTEGER)
5607 builtin_num = number->m_constval.vint;
5608 else if (number->m_vtype == TYPE_FLOAT)
5609 builtin_num = number->m_constval.vfloat;
5612 parseerror(parser, "builtin number must be an integer constant");
5617 fractional = modff(builtin_num, &integral);
5618 if (builtin_num < 0 || fractional != 0) {
5619 parseerror(parser, "builtin number must be an integer greater than zero");
5623 /* we only want the integral part anyways */
5624 builtin_num = integral;
5625 } else if (parser->tok == TOKEN_INTCONST) {
5626 builtin_num = parser_token(parser)->constval.i;
5628 parseerror(parser, "builtin number must be a compile time constant");
5632 if (var->m_hasvalue) {
5633 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5634 "builtin `%s` has already been defined\n"
5635 " -> previous declaration here: %s:%i",
5636 var->m_name, var->m_context.file, (int)var->m_context.line);
5640 func = ast_function_new(var->m_context, var->m_name, var);
5642 parseerror(parser, "failed to allocate function for `%s`", var->m_name);
5645 parser->functions.push_back(func);
5647 func->m_builtin = -builtin_num-1;
5650 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5651 ? (parser->tok != ',' && parser->tok != ';')
5652 : (!parser_next(parser)))
5654 parseerror(parser, "expected comma or semicolon");
5656 ast_function_delete(func);
5657 var->m_constval.vfunc = nullptr;
5661 else if (var->m_vtype == TYPE_ARRAY && parser->tok == '{')
5664 /* Note that fteqcc and most others don't even *have*
5665 * local arrays, so this is not a high priority.
5667 parseerror(parser, "TODO: initializers for local arrays");
5671 var->m_hasvalue = true;
5672 if (!parse_array(parser, var))
5675 else if (var->m_vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5678 parseerror(parser, "cannot declare functions within functions");
5683 proto->m_context = parser_ctx(parser);
5685 if (!parse_function_body(parser, var))
5687 ast_delete(basetype);
5688 for (auto &it : parser->gotos)
5689 parseerror(parser, "undefined label: `%s`", it->m_name);
5690 parser->gotos.clear();
5691 parser->labels.clear();
5694 ast_expression *cexp;
5696 bool folded_const = false;
5698 cexp = parse_expression_leave(parser, true, false, false);
5701 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : nullptr;
5703 /* deal with foldable constants: */
5705 var->m_cvq == CV_CONST && cval && cval->m_hasvalue && cval->m_cvq == CV_CONST && !cval->m_isfield)
5707 /* remove it from the current locals */
5709 for (i = 0; i < 3; ++i) {
5710 vec_pop(parser->_locals);
5711 localblock->m_collect.pop_back();
5714 /* do sanity checking, this function really needs refactoring */
5715 if (vec_last(parser->_locals) != (ast_expression*)var)
5716 parseerror(parser, "internal error: unexpected change in local variable handling");
5718 vec_pop(parser->_locals);
5719 if (localblock->m_locals.back() != var)
5720 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5722 localblock->m_locals.pop_back();
5723 /* push it to the to-be-generated globals */
5724 parser->globals.push_back((ast_expression*)var);
5726 for (i = 0; i < 3; ++i)
5727 parser->globals.push_back((ast_expression*)last_me[i]);
5728 folded_const = true;
5731 if (folded_const || !localblock || is_static) {
5732 if (cval != parser->nil &&
5733 (!cval || ((!cval->m_hasvalue || cval->m_cvq != CV_CONST) && !cval->m_isfield))
5736 parseerror(parser, "initializer is non constant");
5741 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5742 qualifier != CV_VAR)
5744 var->m_cvq = CV_CONST;
5746 if (cval == parser->nil)
5747 var->m_flags |= AST_FLAG_INITIALIZED;
5750 var->m_hasvalue = true;
5751 if (cval->m_vtype == TYPE_STRING)
5752 var->m_constval.vstring = parser_strdup(cval->m_constval.vstring);
5753 else if (cval->m_vtype == TYPE_FIELD)
5754 var->m_constval.vfield = cval;
5756 memcpy(&var->m_constval, &cval->m_constval, sizeof(var->m_constval));
5764 var->m_cvq = CV_NONE;
5765 sy.out.push_back(syexp(var->m_context, (ast_expression*)var));
5766 sy.out.push_back(syexp(cexp->m_context, (ast_expression*)cexp));
5767 sy.ops.push_back(syop(var->m_context, parser->assign_op));
5768 if (!parser_sy_apply_operator(parser, &sy))
5771 if (sy.out.size() != 1 && sy.ops.size() != 0)
5772 parseerror(parser, "internal error: leaked operands");
5773 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5778 /* a constant initialized to an inexact value should be marked inexact:
5779 * const float x = <inexact>; should propagate the inexact flag
5781 if (var->m_cvq == CV_CONST && var->m_vtype == TYPE_FLOAT) {
5782 if (cval && cval->m_hasvalue && cval->m_cvq == CV_CONST)
5783 var->m_inexact = cval->m_inexact;
5788 if (parser->tok == ',') {
5789 if (!parser_next(parser)) {
5790 parseerror(parser, "expected another variable");
5794 if (parser->tok != TOKEN_IDENT) {
5795 parseerror(parser, "expected another variable");
5798 var = ast_value_copy(basetype);
5800 ast_value_set_name(var, parser_tokval(parser));
5801 if (!parser_next(parser)) {
5802 parseerror(parser, "error parsing variable declaration");
5808 if (parser->tok != ';') {
5809 parseerror(parser, "missing semicolon after variables");
5813 if (!parser_next(parser)) {
5814 parseerror(parser, "parse error after variable declaration");
5818 ast_delete(basetype);
5822 if (cleanvar && var)
5824 ast_delete(basetype);
5828 ast_delete(basetype);
5829 if (cleanvar && var)
5831 if (me[0]) ast_member_delete(me[0]);
5832 if (me[1]) ast_member_delete(me[1]);
5833 if (me[2]) ast_member_delete(me[2]);
5837 static bool parser_global_statement(parser_t *parser)
5841 bool is_static = false;
5842 uint32_t qflags = 0;
5843 ast_value *istype = nullptr;
5844 char *vstring = nullptr;
5846 if (parser->tok == TOKEN_IDENT)
5847 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5849 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5851 return parse_variable(parser, nullptr, false, CV_NONE, istype, false, false, 0, nullptr);
5853 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5855 if (cvq == CV_WRONG)
5857 return parse_variable(parser, nullptr, false, cvq, nullptr, noref, is_static, qflags, vstring);
5859 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5861 return parse_enum(parser);
5863 else if (parser->tok == TOKEN_KEYWORD)
5865 if (!strcmp(parser_tokval(parser), "typedef")) {
5866 if (!parser_next(parser)) {
5867 parseerror(parser, "expected type definition after 'typedef'");
5870 return parse_typedef(parser);
5872 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5875 else if (parser->tok == '#')
5877 return parse_pragma(parser);
5879 else if (parser->tok == '$')
5881 if (!parser_next(parser)) {
5882 parseerror(parser, "parse error");
5888 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5894 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5896 return util_crc16(old, str, strlen(str));
5899 static void progdefs_crc_file(const char *str)
5901 /* write to progdefs.h here */
5905 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5907 old = progdefs_crc_sum(old, str);
5908 progdefs_crc_file(str);
5912 static void generate_checksum(parser_t *parser, ir_builder *ir)
5914 uint16_t crc = 0xFFFF;
5918 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5919 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5921 progdefs_crc_file("\tint\tpad;\n");
5922 progdefs_crc_file("\tint\tofs_return[3];\n");
5923 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5924 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5925 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5926 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5927 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5928 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5929 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5930 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5932 for (i = 0; i < parser->crc_globals; ++i) {
5933 if (!ast_istype(parser->globals[i], ast_value))
5935 value = (ast_value*)(parser->globals[i]);
5936 switch (value->m_vtype) {
5937 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5938 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5939 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5940 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5942 crc = progdefs_crc_both(crc, "\tint\t");
5945 crc = progdefs_crc_both(crc, value->m_name);
5946 crc = progdefs_crc_both(crc, ";\n");
5948 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5949 for (i = 0; i < parser->crc_fields; ++i) {
5950 if (!ast_istype(parser->fields[i], ast_value))
5952 value = (ast_value*)(parser->fields[i]);
5953 switch (value->m_next->m_vtype) {
5954 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5955 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5956 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5957 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5959 crc = progdefs_crc_both(crc, "\tint\t");
5962 crc = progdefs_crc_both(crc, value->m_name);
5963 crc = progdefs_crc_both(crc, ";\n");
5965 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5966 ir->m_code->crc = crc;
5969 parser_t *parser_create()
5972 lex_ctx_t empty_ctx;
5975 parser = (parser_t*)mem_a(sizeof(parser_t));
5979 memset(parser, 0, sizeof(*parser));
5982 new (parser) parser_t();
5984 for (i = 0; i < operator_count; ++i) {
5985 if (operators[i].id == opid1('=')) {
5986 parser->assign_op = operators+i;
5990 if (!parser->assign_op) {
5991 con_err("internal error: initializing parser: failed to find assign operator\n");
5996 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5997 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5998 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5999 vec_push(parser->_blocktypedefs, 0);
6001 parser->aliases = util_htnew(PARSER_HT_SIZE);
6003 empty_ctx.file = "<internal>";
6005 empty_ctx.column = 0;
6006 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6007 parser->nil->m_cvq = CV_CONST;
6008 if (OPTS_FLAG(UNTYPED_NIL))
6009 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6011 parser->max_param_count = 1;
6013 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6014 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6015 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6017 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6018 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6019 parser->reserved_version->m_cvq = CV_CONST;
6020 parser->reserved_version->m_hasvalue = true;
6021 parser->reserved_version->m_flags |= AST_FLAG_INCLUDE_DEF;
6022 parser->reserved_version->m_constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6024 parser->reserved_version = nullptr;
6027 parser->m_fold = fold(parser);
6028 parser->m_intrin = intrin(parser);
6032 static bool parser_compile(parser_t *parser)
6034 /* initial lexer/parser state */
6035 parser->lex->flags.noops = true;
6037 if (parser_next(parser))
6039 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6041 if (!parser_global_statement(parser)) {
6042 if (parser->tok == TOKEN_EOF)
6043 parseerror(parser, "unexpected end of file");
6044 else if (compile_errors)
6045 parseerror(parser, "there have been errors, bailing out");
6046 lex_close(parser->lex);
6047 parser->lex = nullptr;
6052 parseerror(parser, "parse error");
6053 lex_close(parser->lex);
6054 parser->lex = nullptr;
6058 lex_close(parser->lex);
6059 parser->lex = nullptr;
6061 return !compile_errors;
6064 bool parser_compile_file(parser_t *parser, const char *filename)
6066 parser->lex = lex_open(filename);
6068 con_err("failed to open file \"%s\"\n", filename);
6071 return parser_compile(parser);
6074 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6076 parser->lex = lex_open_string(str, len, name);
6078 con_err("failed to create lexer for string \"%s\"\n", name);
6081 return parser_compile(parser);
6084 static void parser_remove_ast(parser_t *parser)
6087 if (parser->ast_cleaned)
6089 parser->ast_cleaned = true;
6090 for (auto &it : parser->accessors) {
6091 ast_delete(it->m_constval.vfunc);
6092 it->m_constval.vfunc = nullptr;
6095 for (auto &it : parser->functions) ast_delete(it);
6096 for (auto &it : parser->globals) ast_delete(it);
6097 for (auto &it : parser->fields) ast_delete(it);
6099 for (i = 0; i < vec_size(parser->variables); ++i)
6100 util_htdel(parser->variables[i]);
6101 vec_free(parser->variables);
6102 vec_free(parser->_blocklocals);
6103 vec_free(parser->_locals);
6105 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6106 ast_delete(parser->_typedefs[i]);
6107 vec_free(parser->_typedefs);
6108 for (i = 0; i < vec_size(parser->typedefs); ++i)
6109 util_htdel(parser->typedefs[i]);
6110 vec_free(parser->typedefs);
6111 vec_free(parser->_blocktypedefs);
6113 vec_free(parser->_block_ctx);
6115 ast_value_delete(parser->nil);
6117 ast_value_delete(parser->const_vec[0]);
6118 ast_value_delete(parser->const_vec[1]);
6119 ast_value_delete(parser->const_vec[2]);
6121 if (parser->reserved_version)
6122 ast_value_delete(parser->reserved_version);
6124 util_htdel(parser->aliases);
6127 void parser_cleanup(parser_t *parser)
6129 parser_remove_ast(parser);
6130 parser->~parser_t();
6134 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6135 ast_expression *expr;
6139 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6143 for (auto &it : parser->functions) {
6144 if (!strcmp(it->m_name, "coverage")) {
6150 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6151 con_out("coverage support requested but no coverage() builtin declared\n");
6158 cov = func->m_function_type;
6159 expr = (ast_expression*)cov;
6161 if (expr->m_vtype != TYPE_FUNCTION || expr->m_type_params.size()) {
6163 ast_type_to_string(expr, ty, sizeof(ty));
6164 con_out("invalid type for coverage(): %s\n", ty);
6169 ir->m_coverage_func = func->m_ir_func->m_value;
6173 bool parser_finish(parser_t *parser, const char *output)
6178 if (compile_errors) {
6179 con_out("*** there were compile errors\n");
6183 ir = new ir_builder("gmqcc_out");
6185 con_out("failed to allocate builder\n");
6189 for (auto &it : parser->fields) {
6191 if (!ast_istype(it, ast_value))
6193 ast_value *field = (ast_value*)it;
6194 hasvalue = field->m_hasvalue;
6195 field->m_hasvalue = false;
6196 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6197 con_out("failed to generate field %s\n", field->m_name);
6203 ast_expression *subtype;
6204 field->m_hasvalue = true;
6205 subtype = field->m_next;
6206 ifld = ir_builder_create_field(ir, field->m_name, subtype->m_vtype);
6207 if (subtype->m_vtype == TYPE_FIELD)
6208 ifld->m_fieldtype = subtype->m_next->m_vtype;
6209 else if (subtype->m_vtype == TYPE_FUNCTION)
6210 ifld->m_outtype = subtype->m_next->m_vtype;
6211 (void)!ir_value_set_field(field->m_ir_v, ifld);
6214 for (auto &it : parser->globals) {
6216 if (!ast_istype(it, ast_value))
6218 asvalue = (ast_value*)it;
6219 if (!asvalue->m_uses && !asvalue->m_hasvalue && asvalue->m_vtype != TYPE_FUNCTION) {
6220 retval = retval && !compile_warning(asvalue->m_context, WARN_UNUSED_VARIABLE,
6221 "unused global: `%s`", asvalue->m_name);
6223 if (!ast_global_codegen(asvalue, ir, false)) {
6224 con_out("failed to generate global %s\n", asvalue->m_name);
6229 /* Build function vararg accessor ast tree now before generating
6230 * immediates, because the accessors may add new immediates
6232 for (auto &f : parser->functions) {
6234 if (parser->max_param_count > f->m_function_type->m_type_params.size()) {
6235 f->m_varargs->m_count = parser->max_param_count - f->m_function_type->m_type_params.size();
6236 if (!parser_create_array_setter_impl(parser, f->m_varargs)) {
6237 con_out("failed to generate vararg setter for %s\n", f->m_name);
6241 if (!parser_create_array_getter_impl(parser, f->m_varargs)) {
6242 con_out("failed to generate vararg getter for %s\n", f->m_name);
6247 ast_delete(f->m_varargs);
6248 f->m_varargs = nullptr;
6252 /* Now we can generate immediates */
6253 if (!parser->m_fold.generate(ir))
6256 /* before generating any functions we need to set the coverage_func */
6257 if (!parser_set_coverage_func(parser, ir))
6259 for (auto &it : parser->globals) {
6260 if (!ast_istype(it, ast_value))
6262 ast_value *asvalue = (ast_value*)it;
6263 if (!(asvalue->m_flags & AST_FLAG_INITIALIZED))
6265 if (asvalue->m_cvq == CV_CONST && !asvalue->m_hasvalue)
6266 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_CONSTANT,
6267 "uninitialized constant: `%s`",
6269 else if ((asvalue->m_cvq == CV_NONE || asvalue->m_cvq == CV_CONST) && !asvalue->m_hasvalue)
6270 (void)!compile_warning(asvalue->m_context, WARN_UNINITIALIZED_GLOBAL,
6271 "uninitialized global: `%s`",
6274 if (!ast_generate_accessors(asvalue, ir)) {
6279 for (auto &it : parser->fields) {
6280 ast_value *asvalue = (ast_value*)it->m_next;
6281 if (!ast_istype((ast_expression*)asvalue, ast_value))
6283 if (asvalue->m_vtype != TYPE_ARRAY)
6285 if (!ast_generate_accessors(asvalue, ir)) {
6290 if (parser->reserved_version &&
6291 !ast_global_codegen(parser->reserved_version, ir, false))
6293 con_out("failed to generate reserved::version");
6297 for (auto &f : parser->functions) {
6298 if (!ast_function_codegen(f, ir)) {
6299 con_out("failed to generate function %s\n", f->m_name);
6305 generate_checksum(parser, ir);
6307 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6308 ir_builder_dump(ir, con_out);
6309 for (auto &it : parser->functions) {
6310 if (!ir_function_finalize(it->m_ir_func)) {
6311 con_out("failed to finalize function %s\n", it->m_name);
6316 parser_remove_ast(parser);
6318 if (compile_Werrors) {
6319 con_out("*** there were warnings treated as errors\n");
6320 compile_show_werrors();
6325 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6326 ir_builder_dump(ir, con_out);
6328 if (!ir_builder_generate(ir, output)) {
6329 con_out("*** failed to generate output file\n");