6 #define PARSER_HT_LOCALS 2
7 #define PARSER_HT_SIZE 512
8 #define TYPEDEF_HT_SIZE 512
10 static void parser_enterblock(parser_t *parser);
11 static bool parser_leaveblock(parser_t *parser);
12 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
13 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
14 static bool parse_typedef(parser_t *parser);
15 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);
16 static ast_block* parse_block(parser_t *parser);
17 static bool parse_block_into(parser_t *parser, ast_block *block);
18 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
19 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
20 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
21 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
22 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
23 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
24 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg);
26 static void parseerror(parser_t *parser, const char *fmt, ...)
30 vcompile_error(parser->lex->tok.ctx, fmt, ap);
34 /* returns true if it counts as an error */
35 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
40 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
45 /**********************************************************************
49 static bool parser_next(parser_t *parser)
51 /* lex_do kills the previous token */
52 parser->tok = lex_do(parser->lex);
53 if (parser->tok == TOKEN_EOF)
55 if (parser->tok >= TOKEN_ERROR) {
56 parseerror(parser, "lex error");
62 #define parser_tokval(p) ((p)->lex->tok.value)
63 #define parser_token(p) (&((p)->lex->tok))
65 char *parser_strdup(const char *str)
68 /* actually dup empty strings */
69 char *out = (char*)mem_a(1);
73 return util_strdup(str);
76 static ast_expression* parser_find_field(parser_t *parser, const char *name)
78 return ( ast_expression*)util_htget(parser->htfields, name);
81 static ast_expression* parser_find_label(parser_t *parser, const char *name)
84 for(i = 0; i < vec_size(parser->labels); i++)
85 if (!strcmp(parser->labels[i]->name, name))
86 return (ast_expression*)parser->labels[i];
90 ast_expression* parser_find_global(parser_t *parser, const char *name)
92 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
95 return (ast_expression*)util_htget(parser->htglobals, name);
98 static ast_expression* parser_find_param(parser_t *parser, const char *name)
102 if (!parser->function)
104 fun = parser->function->vtype;
105 for (i = 0; i < vec_size(fun->expression.params); ++i) {
106 if (!strcmp(fun->expression.params[i]->name, name))
107 return (ast_expression*)(fun->expression.params[i]);
112 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
117 hash = util_hthash(parser->htglobals, name);
120 for (i = vec_size(parser->variables); i > upto;) {
122 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
126 return parser_find_param(parser, name);
129 static ast_expression* parser_find_var(parser_t *parser, const char *name)
133 v = parser_find_local(parser, name, 0, &dummy);
134 if (!v) v = parser_find_global(parser, name);
138 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
142 hash = util_hthash(parser->typedefs[0], name);
144 for (i = vec_size(parser->typedefs); i > upto;) {
146 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 */
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 = ast_ctx(*out);
235 if (!ast_istype(*out, ast_array_index))
237 index = (ast_array_index*)*out;
239 if (!ast_istype(index->array, ast_entfield))
241 entfield = (ast_entfield*)index->array;
243 if (!ast_istype(entfield->field, ast_value))
245 field = (ast_value*)entfield->field;
248 entity = entfield->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->array = NULL;
257 oldindex->index = NULL;
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->cvq == CV_CONST) {
268 if (val->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->name);
279 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
286 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
290 ast_expression *out = NULL;
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 (!vec_size(sy->ops)) {
301 parseerror(parser, "internal error: missing operator");
305 if (vec_last(sy->ops).isparen) {
306 parseerror(parser, "unmatched parenthesis");
310 op = &operators[vec_last(sy->ops).etype - 1];
311 ctx = vec_last(sy->ops).ctx;
313 if (vec_size(sy->out) < 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);
321 vec_shrinkby(sy->ops, 1);
323 /* op(:?) has no input and no output */
327 vec_shrinkby(sy->out, op->operands);
328 for (i = 0; i < op->operands; ++i) {
329 exprs[i] = sy->out[vec_size(sy->out)+i].out;
330 blocks[i] = sy->out[vec_size(sy->out)+i].block;
332 if (exprs[i]->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(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
339 compile_error(ast_ctx(exprs[i]), "not an expression");
340 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
344 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
345 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
349 #define NotSameType(T) \
350 (exprs[0]->vtype != exprs[1]->vtype || \
351 exprs[0]->vtype != T)
356 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
360 if (exprs[0]->vtype == TYPE_VECTOR &&
361 exprs[1]->vtype == TYPE_NOEXPR)
363 if (exprs[1] == (ast_expression*)parser->const_vec[0])
364 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
365 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
366 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
367 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
368 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
370 compile_error(ctx, "access to invalid vector component");
374 else if (exprs[0]->vtype == TYPE_ENTITY) {
375 if (exprs[1]->vtype != TYPE_FIELD) {
376 compile_error(ast_ctx(exprs[1]), "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]->vtype == TYPE_VECTOR) {
382 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
386 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
392 if (exprs[0]->vtype != TYPE_ARRAY &&
393 !(exprs[0]->vtype == TYPE_FIELD &&
394 exprs[0]->next->vtype == TYPE_ARRAY))
396 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
397 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
400 if (exprs[1]->vtype != TYPE_FLOAT) {
401 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
402 compile_error(ast_ctx(exprs[1]), "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 (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
411 vec_push(sy->out, syexp(ctx, exprs[0]));
412 vec_push(sy->out, syexp(ctx, exprs[1]));
413 vec_last(sy->argc)++;
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 vec_push(sy->out, syblock(ctx, blocks[0]));
436 if ((out = fold_op(parser->fold, op, exprs)))
439 if (exprs[0]->vtype != TYPE_FLOAT &&
440 exprs[0]->vtype != TYPE_VECTOR) {
441 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
442 type_name[exprs[0]->vtype]);
445 if (exprs[0]->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 = fold_op(parser->fold, op, exprs))) {
453 switch (exprs[0]->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]->vtype]);
482 if (exprs[0]->vtype != exprs[1]->vtype ||
483 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
485 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
486 type_name[exprs[0]->vtype],
487 type_name[exprs[1]->vtype]);
490 if (!(out = fold_op(parser->fold, op, exprs))) {
491 switch (exprs[0]->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]->vtype],
501 type_name[exprs[1]->vtype]);
507 if (exprs[0]->vtype != exprs[1]->vtype ||
508 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
510 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
511 type_name[exprs[1]->vtype],
512 type_name[exprs[0]->vtype]);
515 if (!(out = fold_op(parser->fold, op, exprs))) {
516 switch (exprs[0]->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]->vtype],
526 type_name[exprs[0]->vtype]);
532 if (exprs[0]->vtype != exprs[1]->vtype &&
533 !(exprs[0]->vtype == TYPE_VECTOR &&
534 exprs[1]->vtype == TYPE_FLOAT) &&
535 !(exprs[1]->vtype == TYPE_VECTOR &&
536 exprs[0]->vtype == TYPE_FLOAT)
539 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
540 type_name[exprs[1]->vtype],
541 type_name[exprs[0]->vtype]);
544 if (!(out = fold_op(parser->fold, op, exprs))) {
545 switch (exprs[0]->vtype) {
547 if (exprs[1]->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]->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]->vtype],
561 type_name[exprs[0]->vtype]);
568 if (exprs[1]->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 = fold_op(parser->fold, op, exprs))) {
575 if (exprs[0]->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]->vtype],
590 type_name[exprs[1]->vtype]);
592 } else if (!(out = fold_op(parser->fold, op, exprs))) {
593 /* generate a call to __builtin_mod */
594 ast_expression *mod = intrin_func(parser->intrin, "mod");
595 ast_call *call = NULL;
596 if (!mod) return false; /* can return null for missing floor */
598 call = ast_call_new(parser_ctx(parser), mod);
599 vec_push(call->params, exprs[0]);
600 vec_push(call->params, exprs[1]);
602 out = (ast_expression*)call;
607 compile_error(ctx, "%= is unimplemented");
613 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
614 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
615 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->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]->vtype],
619 type_name[exprs[1]->vtype]);
623 if (!(out = fold_op(parser->fold, 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]->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]->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]->vtype],
659 type_name[exprs[1]->vtype]);
663 if (!(out = fold_op(parser->fold, op, exprs))) {
664 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
665 ast_call *call = ast_call_new(parser_ctx(parser), shift);
666 vec_push(call->params, exprs[0]);
667 vec_push(call->params, 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]->vtype],
677 type_name[exprs[1]->vtype]);
681 if(!(out = fold_op(parser->fold, op, exprs))) {
682 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
683 ast_call *call = ast_call_new(parser_ctx(parser), shift);
684 vec_push(call->params, exprs[0]);
685 vec_push(call->params, 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 = fold_op(parser->fold, 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]->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 = NULL;
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]->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 = NULL;
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 (vec_last(sy->paren) != PAREN_TERNARY2) {
737 compile_error(ctx, "mismatched parenthesis/ternary");
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 = fold_op(parser->fold, 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 = fold_op(parser->fold, op, exprs))) {
761 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
762 vec_push(gencall->params, exprs[0]);
763 vec_push(gencall->params, 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 = fold_op(parser->fold, 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 = fold_op(parser->fold, 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->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->fold->imm_float[2],
811 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
813 (ast_expression*)parser->fold->imm_float[0],
816 (ast_expression*)parser->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]->vtype],
836 type_name[exprs[1]->vtype]);
839 if (!(out = fold_op(parser->fold, op, exprs)))
840 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
842 case opid2('!', '='):
843 if (exprs[0]->vtype != exprs[1]->vtype) {
844 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
845 type_name[exprs[0]->vtype],
846 type_name[exprs[1]->vtype]);
849 if (!(out = fold_op(parser->fold, op, exprs)))
850 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
852 case opid2('=', '='):
853 if (exprs[0]->vtype != exprs[1]->vtype) {
854 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
855 type_name[exprs[0]->vtype],
856 type_name[exprs[1]->vtype]);
859 if (!(out = fold_op(parser->fold, op, exprs)))
860 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
864 if (ast_istype(exprs[0], ast_entfield)) {
865 ast_expression *field = ((ast_entfield*)exprs[0])->field;
866 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
867 exprs[0]->vtype == TYPE_FIELD &&
868 exprs[0]->next->vtype == TYPE_VECTOR)
870 assignop = type_storep_instr[TYPE_VECTOR];
873 assignop = type_storep_instr[exprs[0]->vtype];
874 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
876 ast_type_to_string(field->next, ty1, sizeof(ty1));
877 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
878 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
879 field->next->vtype == TYPE_FUNCTION &&
880 exprs[1]->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]->vtype == TYPE_FIELD &&
893 exprs[0]->next->vtype == TYPE_VECTOR)
895 assignop = type_store_instr[TYPE_VECTOR];
898 assignop = type_store_instr[exprs[0]->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]->vtype == TYPE_FUNCTION &&
912 exprs[1]->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])->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]->vtype != TYPE_FLOAT) {
931 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
932 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
935 if (op->id == opid3('+','+','P'))
939 (void)check_write_to(ast_ctx(exprs[0]), 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->fold->imm_float[1]);
945 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
947 (ast_expression*)parser->fold->imm_float[1]);
950 case opid3('S','+','+'):
951 case opid3('S','-','-'):
953 if (exprs[0]->vtype != TYPE_FLOAT) {
954 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
955 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
958 if (op->id == opid3('S','+','+')) {
965 (void)check_write_to(ast_ctx(exprs[0]), 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->fold->imm_float[1]);
971 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
973 (ast_expression*)parser->fold->imm_float[1]);
977 out = fold_binary(ctx, subop,
979 (ast_expression*)parser->fold->imm_float[1]);
984 if (exprs[0]->vtype != exprs[1]->vtype ||
985 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->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]->vtype];
997 assignop = type_store_instr[exprs[0]->vtype];
998 switch (exprs[0]->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]->vtype],
1012 type_name[exprs[1]->vtype]);
1016 case opid2('*','='):
1017 case opid2('/','='):
1018 if (exprs[1]->vtype != TYPE_FLOAT ||
1019 !(exprs[0]->vtype == TYPE_FLOAT ||
1020 exprs[0]->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]->vtype];
1032 assignop = type_store_instr[exprs[0]->vtype];
1033 switch (exprs[0]->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->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]->vtype],
1058 type_name[exprs[1]->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]->vtype];
1076 assignop = type_store_instr[exprs[0]->vtype];
1077 if (exprs[0]->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]->vtype];
1101 assignop = type_store_instr[exprs[0]->vtype];
1102 if (exprs[0]->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]->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->keep_dest = true;
1114 out = (ast_expression*)asbinstore;
1117 case opid3('l', 'e', 'n'):
1118 if (exprs[0]->vtype != TYPE_STRING && exprs[0]->vtype != TYPE_ARRAY) {
1119 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1120 compile_error(ast_ctx(exprs[0]), "invalid type for length operator: %s", ty1);
1123 /* strings must be const, arrays are statically sized */
1124 if (exprs[0]->vtype == TYPE_STRING &&
1125 !(((ast_value*)exprs[0])->hasvalue && ((ast_value*)exprs[0])->cvq == CV_CONST))
1127 compile_error(ast_ctx(exprs[0]), "operand of length operator not a valid constant expression");
1130 out = fold_op(parser->fold, op, exprs);
1133 case opid2('~', 'P'):
1134 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1139 if (!(out = fold_op(parser->fold, op, exprs))) {
1140 if (exprs[0]->vtype == TYPE_FLOAT) {
1141 out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1143 out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1150 compile_error(ctx, "failed to apply operator %s", op->op);
1154 vec_push(sy->out, 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 = NULL;
1166 size_t paramcount, i;
1169 fid = vec_last(sy->ops).off;
1170 vec_shrinkby(sy->ops, 1);
1172 /* out[fid] is the function
1173 * everything above is parameters...
1175 if (!vec_size(sy->argc)) {
1176 parseerror(parser, "internal error: no argument counter available");
1180 paramcount = vec_last(sy->argc);
1183 if (vec_size(sy->out) < fid) {
1184 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1185 (unsigned long)vec_size(sy->out),
1187 (unsigned long)paramcount);
1192 * TODO handle this at the intrinsic level with an ast_intrinsic
1195 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1197 if (fid+2 != vec_size(sy->out) ||
1198 vec_last(sy->out).block)
1200 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1203 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1204 ast_unref(vec_last(sy->out).out);
1205 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1206 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1207 vec_shrinkby(sy->out, 1);
1212 * Now we need to determine if the function that is being called is
1213 * an intrinsic so we can evaluate if the arguments to it are constant
1214 * and than fruitfully fold them.
1216 #define fold_can_1(X) \
1217 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1218 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1220 if (fid + 1 < vec_size(sy->out))
1223 for (i = 0; i < paramcount; ++i) {
1224 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1231 * All is well which ends well, if we make it into here we can ignore the
1232 * intrinsic call and just evaluate it i.e constant fold it.
1234 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1235 ast_expression **exprs = NULL;
1236 ast_expression *foldval = NULL;
1238 for (i = 0; i < paramcount; i++)
1239 vec_push(exprs, sy->out[fid+1 + i].out);
1241 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1247 * Blub: what sorts of unreffing and resizing of
1248 * sy->out should I be doing here?
1250 sy->out[fid] = syexp(foldval->node.context, foldval);
1251 vec_shrinkby(sy->out, paramcount);
1258 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1263 if (fid+1 + paramcount != vec_size(sy->out)) {
1264 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1265 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1269 for (i = 0; i < paramcount; ++i)
1270 vec_push(call->params, sy->out[fid+1 + i].out);
1271 vec_shrinkby(sy->out, paramcount);
1272 (void)!ast_call_check_types(call, parser->function->vtype->expression.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->flags & AST_FLAG_VARIADIC) &&
1279 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1281 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount, false);
1285 /* overwrite fid, the function, with a call */
1286 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1288 if (fun->vtype != TYPE_FUNCTION) {
1289 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1294 parseerror(parser, "could not determine function return type");
1297 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1299 if (fun->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 ast_ctx(fun).file, ast_ctx(fun).line);
1307 return !parsewarning(parser, WARN_DEPRECATED,
1308 "call to `%s` (which is marked deprecated)\n"
1309 "-> `%s` declared here: %s:%i",
1310 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1312 return !parsewarning(parser, WARN_DEPRECATED,
1313 "call to `%s` (deprecated: %s)\n"
1314 "-> `%s` declared here: %s:%i",
1315 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1319 if (vec_size(fun->params) != paramcount &&
1320 !((fun->flags & AST_FLAG_VARIADIC) &&
1321 vec_size(fun->params) < paramcount))
1323 const char *fewmany = (vec_size(fun->params) > 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->name, (int)vec_size(fun->params), (int)paramcount,
1329 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).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)vec_size(fun->params), (int)paramcount,
1335 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1342 static bool parser_close_paren(parser_t *parser, shunt *sy)
1344 if (!vec_size(sy->ops)) {
1345 parseerror(parser, "unmatched closing paren");
1349 while (vec_size(sy->ops)) {
1350 if (vec_last(sy->ops).isparen) {
1351 if (vec_last(sy->paren) == PAREN_FUNC) {
1353 if (!parser_close_call(parser, sy))
1357 if (vec_last(sy->paren) == PAREN_EXPR) {
1359 if (!vec_size(sy->out)) {
1360 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1361 vec_shrinkby(sy->ops, 1);
1364 vec_shrinkby(sy->ops, 1);
1367 if (vec_last(sy->paren) == PAREN_INDEX) {
1369 /* pop off the parenthesis */
1370 vec_shrinkby(sy->ops, 1);
1371 /* then apply the index operator */
1372 if (!parser_sy_apply_operator(parser, sy))
1376 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1377 vec_last(sy->paren) = PAREN_TERNARY2;
1378 /* pop off the parenthesis */
1379 vec_shrinkby(sy->ops, 1);
1382 compile_error(vec_last(sy->ops).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->vtype;
1409 lex_ctx_t ctx = parser_ctx(parser);
1411 if (!parser->function->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, NULL, NULL, NULL);
1452 if (parser->tok != ')') {
1454 ast_delete(typevar);
1455 parseerror(parser, "expected closing paren");
1459 if (funtype->expression.varparam &&
1460 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1464 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1465 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1466 compile_error(ast_ctx(typevar),
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->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*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1514 vec_push(sy->out, 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 vec_push(sy->out, syexp(parser_ctx(parser), va));
1535 else if (parser->tok == TOKEN_FLOATCONST) {
1536 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f), false);
1539 vec_push(sy->out, syexp(parser_ctx(parser), val));
1542 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1543 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i), false);
1546 vec_push(sy->out, syexp(parser_ctx(parser), val));
1549 else if (parser->tok == TOKEN_STRINGCONST) {
1550 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1553 vec_push(sy->out, syexp(parser_ctx(parser), val));
1556 else if (parser->tok == TOKEN_VECTORCONST) {
1557 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1560 vec_push(sy->out, syexp(parser_ctx(parser), val));
1563 else if (parser->tok == TOKEN_IDENT)
1565 const char *ctoken = parser_tokval(parser);
1566 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1567 ast_expression *var;
1568 /* a_vector.{x,y,z} */
1569 if (!vec_size(sy->ops) ||
1570 !vec_last(sy->ops).etype ||
1571 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1573 /* When adding more intrinsics, fix the above condition */
1576 if (prev && prev->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 vec_push(parser->labels, lbl);
1592 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1593 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->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 = intrin_func(parser->intrin, 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 = intrin_func(parser->intrin, 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)->uses++;
1641 else if (ast_istype(var, ast_member)) {
1642 ast_member *mem = (ast_member*)var;
1643 if (ast_istype(mem->owner, ast_value))
1644 ((ast_value*)(mem->owner))->uses++;
1647 vec_push(sy->out, 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 = NULL;
1659 bool wantop = false;
1660 /* only warn once about an assignment in a truth value because the current code
1661 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1663 bool warn_parenthesis = true;
1665 /* count the parens because an if starts with one, so the
1666 * end of a condition is an unmatched closing paren
1670 memset(&sy, 0, sizeof(sy));
1672 parser->lex->flags.noops = false;
1674 parser_reclassify_token(parser);
1678 if (parser->tok == TOKEN_TYPENAME) {
1679 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1683 if (parser->tok == TOKEN_OPERATOR)
1685 /* classify the operator */
1686 const oper_info *op;
1687 const oper_info *olast = NULL;
1689 for (o = 0; o < operator_count; ++o) {
1690 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1691 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1692 !strcmp(parser_tokval(parser), operators[o].op))
1697 if (o == operator_count) {
1698 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1701 /* found an operator */
1704 /* when declaring variables, a comma starts a new variable */
1705 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1706 /* fixup the token */
1711 /* a colon without a pervious question mark cannot be a ternary */
1712 if (!ternaries && op->id == opid2(':','?')) {
1717 if (op->id == opid1(',')) {
1718 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1719 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1723 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1724 olast = &operators[vec_last(sy.ops).etype-1];
1726 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1727 while (olast && op->prec < olast->prec)
1729 if (!parser_sy_apply_operator(parser, &sy))
1731 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1732 olast = &operators[vec_last(sy.ops).etype-1];
1737 #define IsAssignOp(x) (\
1738 (x) == opid1('=') || \
1739 (x) == opid2('+','=') || \
1740 (x) == opid2('-','=') || \
1741 (x) == opid2('*','=') || \
1742 (x) == opid2('/','=') || \
1743 (x) == opid2('%','=') || \
1744 (x) == opid2('&','=') || \
1745 (x) == opid2('|','=') || \
1746 (x) == opid3('&','~','=') \
1748 if (warn_parenthesis) {
1749 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1750 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1751 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1754 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1755 warn_parenthesis = false;
1758 if (olast && olast->id != op->id) {
1759 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1760 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1762 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1763 warn_parenthesis = false;
1765 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1766 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1768 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1769 warn_parenthesis = false;
1775 (op->prec < olast->prec) ||
1776 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1778 if (!parser_sy_apply_operator(parser, &sy))
1780 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1781 olast = &operators[vec_last(sy.ops).etype-1];
1786 if (op->id == opid1('(')) {
1788 size_t sycount = vec_size(sy.out);
1789 /* we expected an operator, this is the function-call operator */
1790 vec_push(sy.paren, PAREN_FUNC);
1791 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1792 vec_push(sy.argc, 0);
1794 vec_push(sy.paren, PAREN_EXPR);
1795 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1798 } else if (op->id == opid1('[')) {
1800 parseerror(parser, "unexpected array subscript");
1803 vec_push(sy.paren, PAREN_INDEX);
1804 /* push both the operator and the paren, this makes life easier */
1805 vec_push(sy.ops, syop(parser_ctx(parser), op));
1806 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1808 } else if (op->id == opid2('?',':')) {
1809 vec_push(sy.ops, syop(parser_ctx(parser), op));
1810 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1813 vec_push(sy.paren, PAREN_TERNARY1);
1814 } else if (op->id == opid2(':','?')) {
1815 if (!vec_size(sy.paren)) {
1816 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1819 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1820 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1823 if (!parser_close_paren(parser, &sy))
1825 vec_push(sy.ops, syop(parser_ctx(parser), op));
1829 vec_push(sy.ops, syop(parser_ctx(parser), op));
1830 wantop = !!(op->flags & OP_SUFFIX);
1833 else if (parser->tok == ')') {
1834 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1835 if (!parser_sy_apply_operator(parser, &sy))
1838 if (!vec_size(sy.paren))
1841 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1842 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1845 if (!parser_close_paren(parser, &sy))
1848 /* must be a function call without parameters */
1849 if (vec_last(sy.paren) != PAREN_FUNC) {
1850 parseerror(parser, "closing paren in invalid position");
1853 if (!parser_close_paren(parser, &sy))
1858 else if (parser->tok == '(') {
1859 parseerror(parser, "internal error: '(' should be classified as operator");
1862 else if (parser->tok == '[') {
1863 parseerror(parser, "internal error: '[' should be classified as operator");
1866 else if (parser->tok == ']') {
1867 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1868 if (!parser_sy_apply_operator(parser, &sy))
1871 if (!vec_size(sy.paren))
1873 if (vec_last(sy.paren) != PAREN_INDEX) {
1874 parseerror(parser, "mismatched parentheses, unexpected ']'");
1877 if (!parser_close_paren(parser, &sy))
1882 if (!parse_sya_operand(parser, &sy, with_labels))
1887 /* in this case we might want to allow constant string concatenation */
1888 bool concatenated = false;
1889 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1890 ast_expression *lexpr = vec_last(sy.out).out;
1891 if (ast_istype(lexpr, ast_value)) {
1892 ast_value *last = (ast_value*)lexpr;
1893 if (last->isimm == true && last->cvq == CV_CONST &&
1894 last->hasvalue && last->expression.vtype == TYPE_STRING)
1896 char *newstr = NULL;
1897 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1898 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1900 concatenated = true;
1904 if (!concatenated) {
1905 parseerror(parser, "expected operator or end of statement");
1910 if (!parser_next(parser)) {
1913 if (parser->tok == ';' ||
1914 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1915 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1921 while (vec_size(sy.ops)) {
1922 if (!parser_sy_apply_operator(parser, &sy))
1926 parser->lex->flags.noops = true;
1927 if (vec_size(sy.out) != 1) {
1928 parseerror(parser, "expression expected");
1931 expr = sy.out[0].out;
1934 if (vec_size(sy.paren)) {
1935 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1943 parser->lex->flags.noops = true;
1944 for (i = 0; i < vec_size(sy.out); ++i) {
1946 ast_unref(sy.out[i].out);
1955 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1957 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1960 if (parser->tok != ';') {
1961 parseerror(parser, "semicolon expected after expression");
1965 if (!parser_next(parser)) {
1972 static void parser_enterblock(parser_t *parser)
1974 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1975 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1976 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1977 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1978 vec_push(parser->_block_ctx, parser_ctx(parser));
1981 static bool parser_leaveblock(parser_t *parser)
1984 size_t locals, typedefs;
1986 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1987 parseerror(parser, "internal error: parser_leaveblock with no block");
1991 util_htdel(vec_last(parser->variables));
1993 vec_pop(parser->variables);
1994 if (!vec_size(parser->_blocklocals)) {
1995 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1999 locals = vec_last(parser->_blocklocals);
2000 vec_pop(parser->_blocklocals);
2001 while (vec_size(parser->_locals) != locals) {
2002 ast_expression *e = vec_last(parser->_locals);
2003 ast_value *v = (ast_value*)e;
2004 vec_pop(parser->_locals);
2005 if (ast_istype(e, ast_value) && !v->uses) {
2006 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2011 typedefs = vec_last(parser->_blocktypedefs);
2012 while (vec_size(parser->_typedefs) != typedefs) {
2013 ast_delete(vec_last(parser->_typedefs));
2014 vec_pop(parser->_typedefs);
2016 util_htdel(vec_last(parser->typedefs));
2017 vec_pop(parser->typedefs);
2019 vec_pop(parser->_block_ctx);
2024 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2026 vec_push(parser->_locals, e);
2027 util_htset(vec_last(parser->variables), name, (void*)e);
2030 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2032 vec_push(parser->globals, e);
2033 util_htset(parser->htglobals, name, e);
2036 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2040 ast_expression *prev;
2042 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2044 ast_type_to_string(cond, ty, sizeof(ty));
2045 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2048 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2051 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2054 parseerror(parser, "internal error: failed to process condition");
2059 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2061 /* vector types need to be cast to true booleans */
2062 ast_binary *bin = (ast_binary*)cond;
2063 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2065 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2067 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2070 parseerror(parser, "internal error: failed to process condition");
2077 unary = (ast_unary*)cond;
2078 /* ast_istype dereferences cond, should test here for safety */
2079 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2081 cond = unary->operand;
2082 unary->operand = NULL;
2085 unary = (ast_unary*)cond;
2089 parseerror(parser, "internal error: failed to process condition");
2091 if (ifnot) *_ifnot = !*_ifnot;
2095 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2098 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2101 lex_ctx_t ctx = parser_ctx(parser);
2103 (void)block; /* not touching */
2105 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2106 if (!parser_next(parser)) {
2107 parseerror(parser, "expected condition or 'not'");
2110 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2112 if (!parser_next(parser)) {
2113 parseerror(parser, "expected condition in parenthesis");
2117 if (parser->tok != '(') {
2118 parseerror(parser, "expected 'if' condition in parenthesis");
2121 /* parse into the expression */
2122 if (!parser_next(parser)) {
2123 parseerror(parser, "expected 'if' condition after opening paren");
2126 /* parse the condition */
2127 cond = parse_expression_leave(parser, false, true, false);
2131 if (parser->tok != ')') {
2132 parseerror(parser, "expected closing paren after 'if' condition");
2136 /* parse into the 'then' branch */
2137 if (!parser_next(parser)) {
2138 parseerror(parser, "expected statement for on-true branch of 'if'");
2142 if (!parse_statement_or_block(parser, &ontrue)) {
2147 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2148 /* check for an else */
2149 if (!strcmp(parser_tokval(parser), "else")) {
2150 /* parse into the 'else' branch */
2151 if (!parser_next(parser)) {
2152 parseerror(parser, "expected on-false branch after 'else'");
2157 if (!parse_statement_or_block(parser, &onfalse)) {
2164 cond = process_condition(parser, cond, &ifnot);
2166 if (ontrue) ast_delete(ontrue);
2167 if (onfalse) ast_delete(onfalse);
2172 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2174 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2175 *out = (ast_expression*)ifthen;
2179 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2180 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2185 /* skip the 'while' and get the body */
2186 if (!parser_next(parser)) {
2187 if (OPTS_FLAG(LOOP_LABELS))
2188 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2190 parseerror(parser, "expected 'while' condition in parenthesis");
2194 if (parser->tok == ':') {
2195 if (!OPTS_FLAG(LOOP_LABELS))
2196 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2197 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2198 parseerror(parser, "expected loop label");
2201 label = util_strdup(parser_tokval(parser));
2202 if (!parser_next(parser)) {
2204 parseerror(parser, "expected 'while' condition in parenthesis");
2209 if (parser->tok != '(') {
2210 parseerror(parser, "expected 'while' condition in parenthesis");
2214 vec_push(parser->breaks, label);
2215 vec_push(parser->continues, label);
2217 rv = parse_while_go(parser, block, out);
2220 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2221 parseerror(parser, "internal error: label stack corrupted");
2227 vec_pop(parser->breaks);
2228 vec_pop(parser->continues);
2233 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2236 ast_expression *cond, *ontrue;
2240 lex_ctx_t ctx = parser_ctx(parser);
2242 (void)block; /* not touching */
2244 /* parse into the expression */
2245 if (!parser_next(parser)) {
2246 parseerror(parser, "expected 'while' condition after opening paren");
2249 /* parse the condition */
2250 cond = parse_expression_leave(parser, false, true, false);
2254 if (parser->tok != ')') {
2255 parseerror(parser, "expected closing paren after 'while' condition");
2259 /* parse into the 'then' branch */
2260 if (!parser_next(parser)) {
2261 parseerror(parser, "expected while-loop body");
2265 if (!parse_statement_or_block(parser, &ontrue)) {
2270 cond = process_condition(parser, cond, &ifnot);
2275 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2276 *out = (ast_expression*)aloop;
2280 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2281 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2286 /* skip the 'do' and get the body */
2287 if (!parser_next(parser)) {
2288 if (OPTS_FLAG(LOOP_LABELS))
2289 parseerror(parser, "expected loop label or body");
2291 parseerror(parser, "expected loop body");
2295 if (parser->tok == ':') {
2296 if (!OPTS_FLAG(LOOP_LABELS))
2297 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2298 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2299 parseerror(parser, "expected loop label");
2302 label = util_strdup(parser_tokval(parser));
2303 if (!parser_next(parser)) {
2305 parseerror(parser, "expected loop body");
2310 vec_push(parser->breaks, label);
2311 vec_push(parser->continues, label);
2313 rv = parse_dowhile_go(parser, block, out);
2316 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2317 parseerror(parser, "internal error: label stack corrupted");
2320 * Test for NULL otherwise ast_delete dereferences null pointer
2328 vec_pop(parser->breaks);
2329 vec_pop(parser->continues);
2334 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2337 ast_expression *cond, *ontrue;
2341 lex_ctx_t ctx = parser_ctx(parser);
2343 (void)block; /* not touching */
2345 if (!parse_statement_or_block(parser, &ontrue))
2348 /* expect the "while" */
2349 if (parser->tok != TOKEN_KEYWORD ||
2350 strcmp(parser_tokval(parser), "while"))
2352 parseerror(parser, "expected 'while' and condition");
2357 /* skip the 'while' and check for opening paren */
2358 if (!parser_next(parser) || parser->tok != '(') {
2359 parseerror(parser, "expected 'while' condition in parenthesis");
2363 /* parse into the expression */
2364 if (!parser_next(parser)) {
2365 parseerror(parser, "expected 'while' condition after opening paren");
2369 /* parse the condition */
2370 cond = parse_expression_leave(parser, false, true, false);
2374 if (parser->tok != ')') {
2375 parseerror(parser, "expected closing paren after 'while' condition");
2381 if (!parser_next(parser) || parser->tok != ';') {
2382 parseerror(parser, "expected semicolon after condition");
2388 if (!parser_next(parser)) {
2389 parseerror(parser, "parse error");
2395 cond = process_condition(parser, cond, &ifnot);
2400 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2401 *out = (ast_expression*)aloop;
2405 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2406 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2411 /* skip the 'for' and check for opening paren */
2412 if (!parser_next(parser)) {
2413 if (OPTS_FLAG(LOOP_LABELS))
2414 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2416 parseerror(parser, "expected 'for' expressions in parenthesis");
2420 if (parser->tok == ':') {
2421 if (!OPTS_FLAG(LOOP_LABELS))
2422 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2423 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2424 parseerror(parser, "expected loop label");
2427 label = util_strdup(parser_tokval(parser));
2428 if (!parser_next(parser)) {
2430 parseerror(parser, "expected 'for' expressions in parenthesis");
2435 if (parser->tok != '(') {
2436 parseerror(parser, "expected 'for' expressions in parenthesis");
2440 vec_push(parser->breaks, label);
2441 vec_push(parser->continues, label);
2443 rv = parse_for_go(parser, block, out);
2446 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2447 parseerror(parser, "internal error: label stack corrupted");
2453 vec_pop(parser->breaks);
2454 vec_pop(parser->continues);
2458 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2461 ast_expression *initexpr, *cond, *increment, *ontrue;
2466 lex_ctx_t ctx = parser_ctx(parser);
2468 parser_enterblock(parser);
2475 /* parse into the expression */
2476 if (!parser_next(parser)) {
2477 parseerror(parser, "expected 'for' initializer after opening paren");
2482 if (parser->tok == TOKEN_IDENT)
2483 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2485 if (typevar || parser->tok == TOKEN_TYPENAME) {
2486 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2489 else if (parser->tok != ';')
2491 initexpr = parse_expression_leave(parser, false, false, false);
2495 /* move on to condition */
2496 if (parser->tok != ';') {
2497 parseerror(parser, "expected semicolon after for-loop initializer");
2501 if (!parser_next(parser)) {
2502 parseerror(parser, "expected for-loop condition");
2507 /* parse the condition */
2508 if (parser->tok != ';') {
2509 cond = parse_expression_leave(parser, false, true, false);
2514 /* move on to incrementor */
2515 if (parser->tok != ';') {
2516 parseerror(parser, "expected semicolon after for-loop initializer");
2519 if (!parser_next(parser)) {
2520 parseerror(parser, "expected for-loop condition");
2524 /* parse the incrementor */
2525 if (parser->tok != ')') {
2526 lex_ctx_t condctx = parser_ctx(parser);
2527 increment = parse_expression_leave(parser, false, false, false);
2530 if (!ast_side_effects(increment)) {
2531 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2537 if (parser->tok != ')') {
2538 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2541 /* parse into the 'then' branch */
2542 if (!parser_next(parser)) {
2543 parseerror(parser, "expected for-loop body");
2546 if (!parse_statement_or_block(parser, &ontrue))
2550 cond = process_condition(parser, cond, &ifnot);
2554 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2555 *out = (ast_expression*)aloop;
2557 if (!parser_leaveblock(parser)) {
2563 if (initexpr) ast_unref(initexpr);
2564 if (cond) ast_unref(cond);
2565 if (increment) ast_unref(increment);
2566 (void)!parser_leaveblock(parser);
2570 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2572 ast_expression *exp = NULL;
2573 ast_expression *var = NULL;
2574 ast_return *ret = NULL;
2575 ast_value *retval = parser->function->return_value;
2576 ast_value *expected = parser->function->vtype;
2578 lex_ctx_t ctx = parser_ctx(parser);
2580 (void)block; /* not touching */
2582 if (!parser_next(parser)) {
2583 parseerror(parser, "expected return expression");
2587 /* return assignments */
2588 if (parser->tok == '=') {
2589 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2590 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2594 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2596 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2597 parseerror(parser, "invalid return type: `%s'", ty1);
2601 if (!parser_next(parser)) {
2602 parseerror(parser, "expected return assignment expression");
2606 if (!(exp = parse_expression_leave(parser, false, false, false)))
2609 /* prepare the return value */
2611 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2612 ast_type_adopt(retval, expected->expression.next);
2613 parser->function->return_value = retval;
2616 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2617 char ty1[1024], ty2[1024];
2618 ast_type_to_string(exp, ty1, sizeof(ty1));
2619 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2620 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2623 /* store to 'return' local variable */
2624 var = (ast_expression*)ast_store_new(
2626 type_store_instr[expected->expression.next->vtype],
2627 (ast_expression*)retval, exp);
2634 if (parser->tok != ';')
2635 parseerror(parser, "missing semicolon after return assignment");
2636 else if (!parser_next(parser))
2637 parseerror(parser, "parse error after return assignment");
2643 if (parser->tok != ';') {
2644 exp = parse_expression(parser, false, false);
2648 if (exp->vtype != TYPE_NIL &&
2649 exp->vtype != ((ast_expression*)expected)->next->vtype)
2651 parseerror(parser, "return with invalid expression");
2654 ret = ast_return_new(ctx, exp);
2660 if (!parser_next(parser))
2661 parseerror(parser, "parse error");
2663 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2665 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2667 ret = ast_return_new(ctx, (ast_expression*)retval);
2669 *out = (ast_expression*)ret;
2673 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2676 unsigned int levels = 0;
2677 lex_ctx_t ctx = parser_ctx(parser);
2678 const char **loops = (is_continue ? parser->continues : parser->breaks);
2680 (void)block; /* not touching */
2681 if (!parser_next(parser)) {
2682 parseerror(parser, "expected semicolon or loop label");
2686 if (!vec_size(loops)) {
2688 parseerror(parser, "`continue` can only be used inside loops");
2690 parseerror(parser, "`break` can only be used inside loops or switches");
2693 if (parser->tok == TOKEN_IDENT) {
2694 if (!OPTS_FLAG(LOOP_LABELS))
2695 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2696 i = vec_size(loops);
2698 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2701 parseerror(parser, "no such loop to %s: `%s`",
2702 (is_continue ? "continue" : "break out of"),
2703 parser_tokval(parser));
2708 if (!parser_next(parser)) {
2709 parseerror(parser, "expected semicolon");
2714 if (parser->tok != ';') {
2715 parseerror(parser, "expected semicolon");
2719 if (!parser_next(parser))
2720 parseerror(parser, "parse error");
2722 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2726 /* returns true when it was a variable qualifier, false otherwise!
2727 * on error, cvq is set to CV_WRONG
2734 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2736 bool had_const = false;
2737 bool had_var = false;
2738 bool had_noref = false;
2739 bool had_attrib = false;
2740 bool had_static = false;
2743 static attribute_t attributes[] = {
2744 { "noreturn", AST_FLAG_NORETURN },
2745 { "inline", AST_FLAG_INLINE },
2746 { "eraseable", AST_FLAG_ERASEABLE },
2747 { "accumulate", AST_FLAG_ACCUMULATE },
2748 { "last", AST_FLAG_FINAL_DECL }
2755 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2757 /* parse an attribute */
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "expected attribute after `[[`");
2764 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2765 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2766 flags |= attributes[i].flag;
2767 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2768 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2769 attributes[i].name);
2777 if (i != GMQCC_ARRAY_COUNT(attributes))
2781 if (!strcmp(parser_tokval(parser), "noref")) {
2783 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2784 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2789 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2790 flags |= AST_FLAG_ALIAS;
2793 if (!parser_next(parser)) {
2794 parseerror(parser, "parse error in attribute");
2798 if (parser->tok == '(') {
2799 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2800 parseerror(parser, "`alias` attribute missing parameter");
2804 *message = util_strdup(parser_tokval(parser));
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "parse error in attribute");
2811 if (parser->tok != ')') {
2812 parseerror(parser, "`alias` attribute expected `)` after parameter");
2816 if (!parser_next(parser)) {
2817 parseerror(parser, "parse error in attribute");
2822 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2823 parseerror(parser, "`alias` attribute expected `]]`");
2827 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2828 flags |= AST_FLAG_DEPRECATED;
2831 if (!parser_next(parser)) {
2832 parseerror(parser, "parse error in attribute");
2836 if (parser->tok == '(') {
2837 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2838 parseerror(parser, "`deprecated` attribute missing parameter");
2842 *message = util_strdup(parser_tokval(parser));
2844 if (!parser_next(parser)) {
2845 parseerror(parser, "parse error in attribute");
2849 if(parser->tok != ')') {
2850 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2854 if (!parser_next(parser)) {
2855 parseerror(parser, "parse error in attribute");
2860 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2861 parseerror(parser, "`deprecated` attribute expected `]]`");
2864 if (*message) mem_d(*message);
2870 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2871 flags |= AST_FLAG_COVERAGE;
2872 if (!parser_next(parser)) {
2874 parseerror(parser, "parse error in coverage attribute");
2878 if (parser->tok == '(') {
2879 if (!parser_next(parser)) {
2881 parseerror(parser, "invalid parameter for coverage() attribute\n"
2882 "valid are: block");
2886 if (parser->tok != ')') {
2888 if (parser->tok != TOKEN_IDENT)
2889 goto bad_coverage_arg;
2890 if (!strcmp(parser_tokval(parser), "block"))
2891 flags |= AST_FLAG_BLOCK_COVERAGE;
2892 else if (!strcmp(parser_tokval(parser), "none"))
2893 flags &= ~(AST_FLAG_COVERAGE_MASK);
2895 goto bad_coverage_arg;
2896 if (!parser_next(parser))
2897 goto error_in_coverage;
2898 if (parser->tok == ',') {
2899 if (!parser_next(parser))
2900 goto error_in_coverage;
2902 } while (parser->tok != ')');
2904 if (parser->tok != ')' || !parser_next(parser))
2905 goto error_in_coverage;
2907 /* without parameter [[coverage]] equals [[coverage(block)]] */
2908 flags |= AST_FLAG_BLOCK_COVERAGE;
2913 /* Skip tokens until we hit a ]] */
2914 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2915 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2916 if (!parser_next(parser)) {
2917 parseerror(parser, "error inside attribute");
2924 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2926 else if (!strcmp(parser_tokval(parser), "const"))
2928 else if (!strcmp(parser_tokval(parser), "var"))
2930 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2932 else if (!strcmp(parser_tokval(parser), "noref"))
2934 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2941 if (!parser_next(parser))
2951 *is_static = had_static;
2955 parseerror(parser, "parse error after variable qualifier");
2960 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2961 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2966 /* skip the 'while' and get the body */
2967 if (!parser_next(parser)) {
2968 if (OPTS_FLAG(LOOP_LABELS))
2969 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2971 parseerror(parser, "expected 'switch' operand in parenthesis");
2975 if (parser->tok == ':') {
2976 if (!OPTS_FLAG(LOOP_LABELS))
2977 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2978 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2979 parseerror(parser, "expected loop label");
2982 label = util_strdup(parser_tokval(parser));
2983 if (!parser_next(parser)) {
2985 parseerror(parser, "expected 'switch' operand in parenthesis");
2990 if (parser->tok != '(') {
2991 parseerror(parser, "expected 'switch' operand in parenthesis");
2995 vec_push(parser->breaks, label);
2997 rv = parse_switch_go(parser, block, out);
3000 if (vec_last(parser->breaks) != label) {
3001 parseerror(parser, "internal error: label stack corrupted");
3007 vec_pop(parser->breaks);
3012 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3014 ast_expression *operand;
3017 ast_switch *switchnode;
3018 ast_switch_case swcase;
3021 bool noref, is_static;
3022 uint32_t qflags = 0;
3024 lex_ctx_t ctx = parser_ctx(parser);
3026 (void)block; /* not touching */
3029 /* parse into the expression */
3030 if (!parser_next(parser)) {
3031 parseerror(parser, "expected switch operand");
3034 /* parse the operand */
3035 operand = parse_expression_leave(parser, false, false, false);
3039 switchnode = ast_switch_new(ctx, operand);
3042 if (parser->tok != ')') {
3043 ast_delete(switchnode);
3044 parseerror(parser, "expected closing paren after 'switch' operand");
3048 /* parse over the opening paren */
3049 if (!parser_next(parser) || parser->tok != '{') {
3050 ast_delete(switchnode);
3051 parseerror(parser, "expected list of cases");
3055 if (!parser_next(parser)) {
3056 ast_delete(switchnode);
3057 parseerror(parser, "expected 'case' or 'default'");
3061 /* new block; allow some variables to be declared here */
3062 parser_enterblock(parser);
3065 if (parser->tok == TOKEN_IDENT)
3066 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3067 if (typevar || parser->tok == TOKEN_TYPENAME) {
3068 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, NULL)) {
3069 ast_delete(switchnode);
3074 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3076 if (cvq == CV_WRONG) {
3077 ast_delete(switchnode);
3080 if (!parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, NULL)) {
3081 ast_delete(switchnode);
3090 while (parser->tok != '}') {
3091 ast_block *caseblock;
3093 if (!strcmp(parser_tokval(parser), "case")) {
3094 if (!parser_next(parser)) {
3095 ast_delete(switchnode);
3096 parseerror(parser, "expected expression for case");
3099 swcase.value = parse_expression_leave(parser, false, false, false);
3100 if (!swcase.value) {
3101 ast_delete(switchnode);
3102 parseerror(parser, "expected expression for case");
3105 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3106 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3107 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3113 else if (!strcmp(parser_tokval(parser), "default")) {
3114 swcase.value = NULL;
3115 if (!parser_next(parser)) {
3116 ast_delete(switchnode);
3117 parseerror(parser, "expected colon");
3122 ast_delete(switchnode);
3123 parseerror(parser, "expected 'case' or 'default'");
3127 /* Now the colon and body */
3128 if (parser->tok != ':') {
3129 if (swcase.value) ast_unref(swcase.value);
3130 ast_delete(switchnode);
3131 parseerror(parser, "expected colon");
3135 if (!parser_next(parser)) {
3136 if (swcase.value) ast_unref(swcase.value);
3137 ast_delete(switchnode);
3138 parseerror(parser, "expected statements or case");
3141 caseblock = ast_block_new(parser_ctx(parser));
3143 if (swcase.value) ast_unref(swcase.value);
3144 ast_delete(switchnode);
3147 swcase.code = (ast_expression*)caseblock;
3148 vec_push(switchnode->cases, swcase);
3150 ast_expression *expr;
3151 if (parser->tok == '}')
3153 if (parser->tok == TOKEN_KEYWORD) {
3154 if (!strcmp(parser_tokval(parser), "case") ||
3155 !strcmp(parser_tokval(parser), "default"))
3160 if (!parse_statement(parser, caseblock, &expr, true)) {
3161 ast_delete(switchnode);
3166 if (!ast_block_add_expr(caseblock, expr)) {
3167 ast_delete(switchnode);
3173 parser_leaveblock(parser);
3176 if (parser->tok != '}') {
3177 ast_delete(switchnode);
3178 parseerror(parser, "expected closing paren of case list");
3181 if (!parser_next(parser)) {
3182 ast_delete(switchnode);
3183 parseerror(parser, "parse error after switch");
3186 *out = (ast_expression*)switchnode;
3190 /* parse computed goto sides */
3191 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3192 ast_expression *on_true;
3193 ast_expression *on_false;
3194 ast_expression *cond;
3199 if (ast_istype(*side, ast_ternary)) {
3200 ast_ternary *tern = (ast_ternary*)*side;
3201 on_true = parse_goto_computed(parser, &tern->on_true);
3202 on_false = parse_goto_computed(parser, &tern->on_false);
3204 if (!on_true || !on_false) {
3205 parseerror(parser, "expected label or expression in ternary");
3206 if (on_true) ast_unref(on_true);
3207 if (on_false) ast_unref(on_false);
3215 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3216 } else if (ast_istype(*side, ast_label)) {
3217 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3218 ast_goto_set_label(gt, ((ast_label*)*side));
3220 return (ast_expression*)gt;
3225 static bool parse_goto(parser_t *parser, ast_expression **out)
3227 ast_goto *gt = NULL;
3228 ast_expression *lbl;
3230 if (!parser_next(parser))
3233 if (parser->tok != TOKEN_IDENT) {
3234 ast_expression *expression;
3236 /* could be an expression i.e computed goto :-) */
3237 if (parser->tok != '(') {
3238 parseerror(parser, "expected label name after `goto`");
3242 /* failed to parse expression for goto */
3243 if (!(expression = parse_expression(parser, false, true)) ||
3244 !(*out = parse_goto_computed(parser, &expression))) {
3245 parseerror(parser, "invalid goto expression");
3247 ast_unref(expression);
3254 /* not computed goto */
3255 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3256 lbl = parser_find_label(parser, gt->name);
3258 if (!ast_istype(lbl, ast_label)) {
3259 parseerror(parser, "internal error: label is not an ast_label");
3263 ast_goto_set_label(gt, (ast_label*)lbl);
3266 vec_push(parser->gotos, gt);
3268 if (!parser_next(parser) || parser->tok != ';') {
3269 parseerror(parser, "semicolon expected after goto label");
3272 if (!parser_next(parser)) {
3273 parseerror(parser, "parse error after goto");
3277 *out = (ast_expression*)gt;
3281 static bool parse_skipwhite(parser_t *parser)
3284 if (!parser_next(parser))
3286 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3287 return parser->tok < TOKEN_ERROR;
3290 static bool parse_eol(parser_t *parser)
3292 if (!parse_skipwhite(parser))
3294 return parser->tok == TOKEN_EOL;
3297 static bool parse_pragma_do(parser_t *parser)
3299 if (!parser_next(parser) ||
3300 parser->tok != TOKEN_IDENT ||
3301 strcmp(parser_tokval(parser), "pragma"))
3303 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3306 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3307 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3311 if (!strcmp(parser_tokval(parser), "noref")) {
3312 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3313 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3316 parser->noref = !!parser_token(parser)->constval.i;
3317 if (!parse_eol(parser)) {
3318 parseerror(parser, "parse error after `noref` pragma");
3324 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3327 while (!parse_eol(parser)) {
3328 parser_next(parser);
3337 static bool parse_pragma(parser_t *parser)
3340 parser->lex->flags.preprocessing = true;
3341 parser->lex->flags.mergelines = true;
3342 rv = parse_pragma_do(parser);
3343 if (parser->tok != TOKEN_EOL) {
3344 parseerror(parser, "junk after pragma");
3347 parser->lex->flags.preprocessing = false;
3348 parser->lex->flags.mergelines = false;
3349 if (!parser_next(parser)) {
3350 parseerror(parser, "parse error after pragma");
3356 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3358 bool noref, is_static;
3360 uint32_t qflags = 0;
3361 ast_value *typevar = NULL;
3362 char *vstring = NULL;
3366 if (parser->tok == TOKEN_IDENT)
3367 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3369 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3371 /* local variable */
3373 parseerror(parser, "cannot declare a variable from here");
3376 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3377 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3380 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3384 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3386 if (cvq == CV_WRONG)
3388 return parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, vstring);
3390 else if (parser->tok == TOKEN_KEYWORD)
3392 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3397 if (!parser_next(parser)) {
3398 parseerror(parser, "parse error after __builtin_debug_printtype");
3402 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3404 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3405 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3406 if (!parser_next(parser)) {
3407 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3413 if (!parse_statement(parser, block, out, allow_cases))
3416 con_out("__builtin_debug_printtype: got no output node\n");
3419 ast_type_to_string(*out, ty, sizeof(ty));
3420 con_out("__builtin_debug_printtype: `%s`\n", ty);
3425 else if (!strcmp(parser_tokval(parser), "return"))
3427 return parse_return(parser, block, out);
3429 else if (!strcmp(parser_tokval(parser), "if"))
3431 return parse_if(parser, block, out);
3433 else if (!strcmp(parser_tokval(parser), "while"))
3435 return parse_while(parser, block, out);
3437 else if (!strcmp(parser_tokval(parser), "do"))
3439 return parse_dowhile(parser, block, out);
3441 else if (!strcmp(parser_tokval(parser), "for"))
3443 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3444 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3447 return parse_for(parser, block, out);
3449 else if (!strcmp(parser_tokval(parser), "break"))
3451 return parse_break_continue(parser, block, out, false);
3453 else if (!strcmp(parser_tokval(parser), "continue"))
3455 return parse_break_continue(parser, block, out, true);
3457 else if (!strcmp(parser_tokval(parser), "switch"))
3459 return parse_switch(parser, block, out);
3461 else if (!strcmp(parser_tokval(parser), "case") ||
3462 !strcmp(parser_tokval(parser), "default"))
3465 parseerror(parser, "unexpected 'case' label");
3470 else if (!strcmp(parser_tokval(parser), "goto"))
3472 return parse_goto(parser, out);
3474 else if (!strcmp(parser_tokval(parser), "typedef"))
3476 if (!parser_next(parser)) {
3477 parseerror(parser, "expected type definition after 'typedef'");
3480 return parse_typedef(parser);
3482 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3485 else if (parser->tok == '{')
3488 inner = parse_block(parser);
3491 *out = (ast_expression*)inner;
3494 else if (parser->tok == ':')
3498 if (!parser_next(parser)) {
3499 parseerror(parser, "expected label name");
3502 if (parser->tok != TOKEN_IDENT) {
3503 parseerror(parser, "label must be an identifier");
3506 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3508 if (!label->undefined) {
3509 parseerror(parser, "label `%s` already defined", label->name);
3512 label->undefined = false;
3515 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3516 vec_push(parser->labels, label);
3518 *out = (ast_expression*)label;
3519 if (!parser_next(parser)) {
3520 parseerror(parser, "parse error after label");
3523 for (i = 0; i < vec_size(parser->gotos); ++i) {
3524 if (!strcmp(parser->gotos[i]->name, label->name)) {
3525 ast_goto_set_label(parser->gotos[i], label);
3526 vec_remove(parser->gotos, i, 1);
3532 else if (parser->tok == ';')
3534 if (!parser_next(parser)) {
3535 parseerror(parser, "parse error after empty statement");
3542 lex_ctx_t ctx = parser_ctx(parser);
3543 ast_expression *exp = parse_expression(parser, false, false);
3547 if (!ast_side_effects(exp)) {
3548 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3555 static bool parse_enum(parser_t *parser)
3558 bool reverse = false;
3560 ast_value **values = NULL;
3561 ast_value *var = NULL;
3564 ast_expression *old;
3566 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3567 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3571 /* enumeration attributes (can add more later) */
3572 if (parser->tok == ':') {
3573 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3574 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3579 if (!strcmp(parser_tokval(parser), "flag")) {
3583 else if (!strcmp(parser_tokval(parser), "reverse")) {
3587 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3591 if (!parser_next(parser) || parser->tok != '{') {
3592 parseerror(parser, "expected `{` after enum attribute ");
3598 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3599 if (parser->tok == '}') {
3600 /* allow an empty enum */
3603 parseerror(parser, "expected identifier or `}`");
3607 old = parser_find_field(parser, parser_tokval(parser));
3609 old = parser_find_global(parser, parser_tokval(parser));
3611 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3612 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3616 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3617 vec_push(values, var);
3618 var->cvq = CV_CONST;
3619 var->hasvalue = true;
3621 /* for flagged enumerations increment in POTs of TWO */
3622 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3623 parser_addglobal(parser, var->name, (ast_expression*)var);
3625 if (!parser_next(parser)) {
3626 parseerror(parser, "expected `=`, `}` or comma after identifier");
3630 if (parser->tok == ',')
3632 if (parser->tok == '}')
3634 if (parser->tok != '=') {
3635 parseerror(parser, "expected `=`, `}` or comma after identifier");
3639 if (!parser_next(parser)) {
3640 parseerror(parser, "expected expression after `=`");
3644 /* We got a value! */
3645 old = parse_expression_leave(parser, true, false, false);
3646 asvalue = (ast_value*)old;
3647 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3648 compile_error(ast_ctx(var), "constant value or expression expected");
3651 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3653 if (parser->tok == '}')
3655 if (parser->tok != ',') {
3656 parseerror(parser, "expected `}` or comma after expression");
3661 /* patch them all (for reversed attribute) */
3664 for (i = 0; i < vec_size(values); i++)
3665 values[i]->constval.vfloat = vec_size(values) - i - 1;
3668 if (parser->tok != '}') {
3669 parseerror(parser, "internal error: breaking without `}`");
3673 if (!parser_next(parser) || parser->tok != ';') {
3674 parseerror(parser, "expected semicolon after enumeration");
3678 if (!parser_next(parser)) {
3679 parseerror(parser, "parse error after enumeration");
3691 static bool parse_block_into(parser_t *parser, ast_block *block)
3695 parser_enterblock(parser);
3697 if (!parser_next(parser)) { /* skip the '{' */
3698 parseerror(parser, "expected function body");
3702 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3704 ast_expression *expr = NULL;
3705 if (parser->tok == '}')
3708 if (!parse_statement(parser, block, &expr, false)) {
3709 /* parseerror(parser, "parse error"); */
3715 if (!ast_block_add_expr(block, expr)) {
3722 if (parser->tok != '}') {
3725 (void)parser_next(parser);
3729 if (!parser_leaveblock(parser))
3731 return retval && !!block;
3734 static ast_block* parse_block(parser_t *parser)
3737 block = ast_block_new(parser_ctx(parser));
3740 if (!parse_block_into(parser, block)) {
3741 ast_block_delete(block);
3747 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3749 if (parser->tok == '{') {
3750 *out = (ast_expression*)parse_block(parser);
3753 return parse_statement(parser, NULL, out, false);
3756 static bool create_vector_members(ast_value *var, ast_member **me)
3759 size_t len = strlen(var->name);
3761 for (i = 0; i < 3; ++i) {
3762 char *name = (char*)mem_a(len+3);
3763 memcpy(name, var->name, len);
3765 name[len+1] = 'x'+i;
3767 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3776 do { ast_member_delete(me[--i]); } while(i);
3780 static bool parse_function_body(parser_t *parser, ast_value *var)
3782 ast_block *block = NULL;
3787 ast_expression *framenum = NULL;
3788 ast_expression *nextthink = NULL;
3789 /* None of the following have to be deleted */
3790 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3791 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3792 bool has_frame_think;
3796 has_frame_think = false;
3797 old = parser->function;
3799 if (var->expression.flags & AST_FLAG_ALIAS) {
3800 parseerror(parser, "function aliases cannot have bodies");
3804 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3805 parseerror(parser, "gotos/labels leaking");
3809 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3810 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3811 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3817 if (parser->tok == '[') {
3818 /* got a frame definition: [ framenum, nextthink ]
3819 * this translates to:
3820 * self.frame = framenum;
3821 * self.nextthink = time + 0.1;
3822 * self.think = nextthink;
3826 fld_think = parser_find_field(parser, "think");
3827 fld_nextthink = parser_find_field(parser, "nextthink");
3828 fld_frame = parser_find_field(parser, "frame");
3829 if (!fld_think || !fld_nextthink || !fld_frame) {
3830 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3831 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3834 gbl_time = parser_find_global(parser, "time");
3835 gbl_self = parser_find_global(parser, "self");
3836 if (!gbl_time || !gbl_self) {
3837 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3838 parseerror(parser, "please declare the following globals: `time`, `self`");
3842 if (!parser_next(parser))
3845 framenum = parse_expression_leave(parser, true, false, false);
3847 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3850 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3851 ast_unref(framenum);
3852 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3856 if (parser->tok != ',') {
3857 ast_unref(framenum);
3858 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3859 parseerror(parser, "Got a %i\n", parser->tok);
3863 if (!parser_next(parser)) {
3864 ast_unref(framenum);
3868 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3870 /* qc allows the use of not-yet-declared functions here
3871 * - this automatically creates a prototype */
3872 ast_value *thinkfunc;
3873 ast_expression *functype = fld_think->next;
3875 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3876 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3877 ast_unref(framenum);
3878 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3881 ast_type_adopt(thinkfunc, functype);
3883 if (!parser_next(parser)) {
3884 ast_unref(framenum);
3885 ast_delete(thinkfunc);
3889 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3891 nextthink = (ast_expression*)thinkfunc;
3894 nextthink = parse_expression_leave(parser, true, false, false);
3896 ast_unref(framenum);
3897 parseerror(parser, "expected a think-function in [frame,think] notation");
3902 if (!ast_istype(nextthink, ast_value)) {
3903 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3907 if (retval && parser->tok != ']') {
3908 parseerror(parser, "expected closing `]` for [frame,think] notation");
3912 if (retval && !parser_next(parser)) {
3916 if (retval && parser->tok != '{') {
3917 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3922 ast_unref(nextthink);
3923 ast_unref(framenum);
3927 has_frame_think = true;
3930 block = ast_block_new(parser_ctx(parser));
3932 parseerror(parser, "failed to allocate block");
3933 if (has_frame_think) {
3934 ast_unref(nextthink);
3935 ast_unref(framenum);
3940 if (has_frame_think) {
3941 if (!OPTS_FLAG(EMULATE_STATE)) {
3942 ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
3943 if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
3944 parseerror(parser, "failed to generate state op for [frame,think]");
3945 ast_unref(nextthink);
3946 ast_unref(framenum);
3951 /* emulate OP_STATE in code: */
3953 ast_expression *self_frame;
3954 ast_expression *self_nextthink;
3955 ast_expression *self_think;
3956 ast_expression *time_plus_1;
3957 ast_store *store_frame;
3958 ast_store *store_nextthink;
3959 ast_store *store_think;
3961 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3963 ctx = parser_ctx(parser);
3964 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3965 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3966 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3968 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3969 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, frame_delta, false));
3971 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3972 if (self_frame) ast_delete(self_frame);
3973 if (self_nextthink) ast_delete(self_nextthink);
3974 if (self_think) ast_delete(self_think);
3975 if (time_plus_1) ast_delete(time_plus_1);
3981 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3982 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3983 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3986 ast_delete(self_frame);
3989 if (!store_nextthink) {
3990 ast_delete(self_nextthink);
3994 ast_delete(self_think);
3998 if (store_frame) ast_delete(store_frame);
3999 if (store_nextthink) ast_delete(store_nextthink);
4000 if (store_think) ast_delete(store_think);
4003 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4004 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4005 !ast_block_add_expr(block, (ast_expression*)store_think))
4012 parseerror(parser, "failed to generate code for [frame,think]");
4013 ast_unref(nextthink);
4014 ast_unref(framenum);
4021 if (var->hasvalue) {
4022 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4023 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4024 ast_block_delete(block);
4027 func = var->constval.vfunc;
4030 parseerror(parser, "internal error: NULL function: `%s`", var->name);
4031 ast_block_delete(block);
4035 func = ast_function_new(ast_ctx(var), var->name, var);
4038 parseerror(parser, "failed to allocate function for `%s`", var->name);
4039 ast_block_delete(block);
4042 vec_push(parser->functions, func);
4045 parser_enterblock(parser);
4047 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4049 ast_value *param = var->expression.params[parami];
4052 if (param->expression.vtype != TYPE_VECTOR &&
4053 (param->expression.vtype != TYPE_FIELD ||
4054 param->expression.next->vtype != TYPE_VECTOR))
4059 if (!create_vector_members(param, me)) {
4060 ast_block_delete(block);
4064 for (e = 0; e < 3; ++e) {
4065 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4066 ast_block_collect(block, (ast_expression*)me[e]);
4070 if (var->argcounter && !func->argc) {
4071 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4072 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4076 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4078 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4079 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4080 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4081 varargs->expression.count = 0;
4082 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4083 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4084 ast_delete(varargs);
4085 ast_block_delete(block);
4088 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4089 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4090 ast_delete(varargs);
4091 ast_block_delete(block);
4094 func->varargs = varargs;
4095 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params), false);
4098 parser->function = func;
4099 if (!parse_block_into(parser, block)) {
4100 ast_block_delete(block);
4104 vec_push(func->blocks, block);
4106 parser->function = old;
4107 if (!parser_leaveblock(parser))
4109 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4110 parseerror(parser, "internal error: local scopes left");
4114 if (parser->tok == ';')
4115 return parser_next(parser);
4116 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4117 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4121 (void)!parser_leaveblock(parser);
4122 vec_pop(parser->functions);
4123 ast_function_delete(func);
4124 var->constval.vfunc = NULL;
4127 parser->function = old;
4131 static ast_expression *array_accessor_split(
4136 ast_expression *left,
4137 ast_expression *right
4143 lex_ctx_t ctx = ast_ctx(array);
4145 if (!left || !right) {
4146 if (left) ast_delete(left);
4147 if (right) ast_delete(right);
4151 cmp = ast_binary_new(ctx, INSTR_LT,
4152 (ast_expression*)index,
4153 (ast_expression*)fold_constgen_float(parser->fold, middle, false));
4157 parseerror(parser, "internal error: failed to create comparison for array setter");
4161 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4163 ast_delete(cmp); /* will delete left and right */
4164 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4168 return (ast_expression*)ifthen;
4171 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4173 lex_ctx_t ctx = ast_ctx(array);
4175 if (from+1 == afterend) {
4176 /* set this value */
4179 ast_array_index *subscript;
4181 int assignop = type_store_instr[value->expression.vtype];
4183 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4184 assignop = INSTR_STORE_V;
4186 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4190 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4192 ast_delete(subscript);
4196 block = ast_block_new(ctx);
4202 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4207 ret = ast_return_new(ctx, NULL);
4213 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4218 return (ast_expression*)block;
4220 ast_expression *left, *right;
4221 size_t diff = afterend - from;
4222 size_t middle = from + diff/2;
4223 left = array_setter_node(parser, array, index, value, from, middle);
4224 right = array_setter_node(parser, array, index, value, middle, afterend);
4225 return array_accessor_split(parser, array, index, middle, left, right);
4229 static ast_expression *array_field_setter_node(
4238 lex_ctx_t ctx = ast_ctx(array);
4240 if (from+1 == afterend) {
4241 /* set this value */
4244 ast_entfield *entfield;
4245 ast_array_index *subscript;
4247 int assignop = type_storep_instr[value->expression.vtype];
4249 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4250 assignop = INSTR_STOREP_V;
4252 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4256 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4257 subscript->expression.vtype = TYPE_FIELD;
4259 entfield = ast_entfield_new_force(ctx,
4260 (ast_expression*)entity,
4261 (ast_expression*)subscript,
4262 (ast_expression*)subscript);
4264 ast_delete(subscript);
4268 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4270 ast_delete(entfield);
4274 block = ast_block_new(ctx);
4280 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4285 ret = ast_return_new(ctx, NULL);
4291 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4296 return (ast_expression*)block;
4298 ast_expression *left, *right;
4299 size_t diff = afterend - from;
4300 size_t middle = from + diff/2;
4301 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4302 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4303 return array_accessor_split(parser, array, index, middle, left, right);
4307 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4309 lex_ctx_t ctx = ast_ctx(array);
4311 if (from+1 == afterend) {
4313 ast_array_index *subscript;
4315 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4319 ret = ast_return_new(ctx, (ast_expression*)subscript);
4321 ast_delete(subscript);
4325 return (ast_expression*)ret;
4327 ast_expression *left, *right;
4328 size_t diff = afterend - from;
4329 size_t middle = from + diff/2;
4330 left = array_getter_node(parser, array, index, from, middle);
4331 right = array_getter_node(parser, array, index, middle, afterend);
4332 return array_accessor_split(parser, array, index, middle, left, right);
4336 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4338 ast_function *func = NULL;
4339 ast_value *fval = NULL;
4340 ast_block *body = NULL;
4342 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4344 parseerror(parser, "failed to create accessor function value");
4347 fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4349 func = ast_function_new(ast_ctx(array), funcname, fval);
4352 parseerror(parser, "failed to create accessor function node");
4356 body = ast_block_new(ast_ctx(array));
4358 parseerror(parser, "failed to create block for array accessor");
4364 vec_push(func->blocks, body);
4367 vec_push(parser->accessors, fval);
4372 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4374 ast_value *index = NULL;
4375 ast_value *value = NULL;
4379 if (!ast_istype(array->expression.next, ast_value)) {
4380 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4384 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4386 func = fval->constval.vfunc;
4387 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4389 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4390 value = ast_value_copy((ast_value*)array->expression.next);
4392 if (!index || !value) {
4393 parseerror(parser, "failed to create locals for array accessor");
4396 (void)!ast_value_set_name(value, "value"); /* not important */
4397 vec_push(fval->expression.params, index);
4398 vec_push(fval->expression.params, value);
4400 array->setter = fval;
4403 if (index) ast_delete(index);
4404 if (value) ast_delete(value);
4410 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4412 ast_expression *root = NULL;
4413 root = array_setter_node(parser, array,
4414 array->setter->expression.params[0],
4415 array->setter->expression.params[1],
4416 0, array->expression.count);
4418 parseerror(parser, "failed to build accessor search tree");
4421 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4428 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4430 if (!parser_create_array_setter_proto(parser, array, funcname))
4432 return parser_create_array_setter_impl(parser, array);
4435 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4437 ast_expression *root = NULL;
4438 ast_value *entity = NULL;
4439 ast_value *index = NULL;
4440 ast_value *value = NULL;
4444 if (!ast_istype(array->expression.next, ast_value)) {
4445 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4449 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4451 func = fval->constval.vfunc;
4452 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4454 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4455 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4456 value = ast_value_copy((ast_value*)array->expression.next);
4457 if (!entity || !index || !value) {
4458 parseerror(parser, "failed to create locals for array accessor");
4461 (void)!ast_value_set_name(value, "value"); /* not important */
4462 vec_push(fval->expression.params, entity);
4463 vec_push(fval->expression.params, index);
4464 vec_push(fval->expression.params, value);
4466 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4468 parseerror(parser, "failed to build accessor search tree");
4472 array->setter = fval;
4473 return ast_block_add_expr(func->blocks[0], root);
4475 if (entity) ast_delete(entity);
4476 if (index) ast_delete(index);
4477 if (value) ast_delete(value);
4478 if (root) ast_delete(root);
4484 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4486 ast_value *index = NULL;
4490 /* NOTE: checking array->expression.next rather than elemtype since
4491 * for fields elemtype is a temporary fieldtype.
4493 if (!ast_istype(array->expression.next, ast_value)) {
4494 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4498 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4500 func = fval->constval.vfunc;
4501 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4503 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4506 parseerror(parser, "failed to create locals for array accessor");
4509 vec_push(fval->expression.params, index);
4511 array->getter = fval;
4514 if (index) ast_delete(index);
4520 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4522 ast_expression *root = NULL;
4524 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4526 parseerror(parser, "failed to build accessor search tree");
4529 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4536 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4538 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4540 return parser_create_array_getter_impl(parser, array);
4543 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4551 bool variadic = false;
4552 ast_value *varparam = NULL;
4553 char *argcounter = NULL;
4555 ctx = parser_ctx(parser);
4557 /* for the sake of less code we parse-in in this function */
4558 if (!parser_next(parser)) {
4560 parseerror(parser, "expected parameter list");
4566 /* parse variables until we hit a closing paren */
4567 while (parser->tok != ')') {
4568 bool is_varargs = false;
4571 /* there must be commas between them */
4572 if (parser->tok != ',') {
4573 parseerror(parser, "expected comma or end of parameter list");
4576 if (!parser_next(parser)) {
4577 parseerror(parser, "expected parameter");
4583 param = parse_typename(parser, NULL, NULL, &is_varargs);
4584 if (!param && !is_varargs)
4587 /* '...' indicates a varargs function */
4589 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4590 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4593 if (parser->tok == TOKEN_IDENT) {
4594 argcounter = util_strdup(parser_tokval(parser));
4595 if (!parser_next(parser) || parser->tok != ')') {
4596 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4601 vec_push(params, param);
4602 if (param->expression.vtype >= TYPE_VARIANT) {
4603 char tname[1024]; /* typename is reserved in C++ */
4604 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4605 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4608 /* type-restricted varargs */
4609 if (parser->tok == TOKEN_DOTS) {
4611 varparam = vec_last(params);
4613 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4614 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4617 if (parser->tok == TOKEN_IDENT) {
4618 argcounter = util_strdup(parser_tokval(parser));
4619 ast_value_set_name(param, argcounter);
4620 if (!parser_next(parser) || parser->tok != ')') {
4621 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4626 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->name[0] == '<') {
4627 parseerror(parser, "parameter name omitted");
4633 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4637 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4638 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4641 if (!parser_next(parser)) {
4642 parseerror(parser, "parse error after typename");
4646 /* now turn 'var' into a function type */
4647 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4648 fval->expression.next = (ast_expression*)var;
4650 fval->expression.flags |= AST_FLAG_VARIADIC;
4653 var->expression.params = params;
4654 var->expression.varparam = (ast_expression*)varparam;
4655 var->argcounter = argcounter;
4664 ast_delete(varparam);
4666 for (i = 0; i < vec_size(params); ++i)
4667 ast_delete(params[i]);
4672 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4674 ast_expression *cexp;
4675 ast_value *cval, *tmp;
4678 ctx = parser_ctx(parser);
4680 if (!parser_next(parser)) {
4682 parseerror(parser, "expected array-size");
4686 if (parser->tok != ']') {
4687 cexp = parse_expression_leave(parser, true, false, false);
4689 if (!cexp || !ast_istype(cexp, ast_value)) {
4693 parseerror(parser, "expected array-size as constant positive integer");
4696 cval = (ast_value*)cexp;
4703 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4704 tmp->expression.next = (ast_expression*)var;
4708 if (cval->expression.vtype == TYPE_INTEGER)
4709 tmp->expression.count = cval->constval.vint;
4710 else if (cval->expression.vtype == TYPE_FLOAT)
4711 tmp->expression.count = cval->constval.vfloat;
4715 parseerror(parser, "array-size must be a positive integer constant");
4721 var->expression.count = -1;
4722 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4725 if (parser->tok != ']') {
4727 parseerror(parser, "expected ']' after array-size");
4730 if (!parser_next(parser)) {
4732 parseerror(parser, "error after parsing array size");
4738 /* Parse a complete typename.
4739 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4740 * but when parsing variables separated by comma
4741 * 'storebase' should point to where the base-type should be kept.
4742 * The base type makes up every bit of type information which comes *before* the
4745 * NOTE: The value must either be named, have a NULL name, or a name starting
4746 * with '<'. In the first case, this will be the actual variable or type
4747 * name, in the other cases it is assumed that the name will appear
4748 * later, and an error is generated otherwise.
4750 * The following will be parsed in its entirety:
4752 * The 'basetype' in this case is 'void()'
4753 * and if there's a comma after it, say:
4755 * then the type-information 'void()' can be stored in 'storebase'
4757 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4759 ast_value *var, *tmp;
4762 const char *name = NULL;
4763 bool isfield = false;
4764 bool wasarray = false;
4765 size_t morefields = 0;
4767 bool vararg = (parser->tok == TOKEN_DOTS);
4769 ctx = parser_ctx(parser);
4771 /* types may start with a dot */
4772 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4774 if (parser->tok == TOKEN_DOTS)
4776 /* if we parsed a dot we need a typename now */
4777 if (!parser_next(parser)) {
4778 parseerror(parser, "expected typename for field definition");
4782 /* Further dots are handled seperately because they won't be part of the
4786 if (parser->tok == '.')
4788 else if (parser->tok == TOKEN_DOTS)
4793 if (!parser_next(parser)) {
4794 parseerror(parser, "expected typename for field definition");
4799 if (parser->tok == TOKEN_IDENT)
4800 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4801 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4802 if (vararg && is_vararg) {
4806 parseerror(parser, "expected typename");
4810 /* generate the basic type value */
4811 if (cached_typedef) {
4812 var = ast_value_copy(cached_typedef);
4813 ast_value_set_name(var, "<type(from_def)>");
4815 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4817 for (; morefields; --morefields) {
4818 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4819 tmp->expression.next = (ast_expression*)var;
4823 /* do not yet turn into a field - remember:
4824 * .void() foo; is a field too
4825 * .void()() foo; is a function
4829 if (!parser_next(parser)) {
4831 parseerror(parser, "parse error after typename");
4835 /* an opening paren now starts the parameter-list of a function
4836 * this is where original-QC has parameter lists.
4837 * We allow a single parameter list here.
4838 * Much like fteqcc we don't allow `float()() x`
4840 if (parser->tok == '(') {
4841 var = parse_parameter_list(parser, var);
4846 /* store the base if requested */
4848 *storebase = ast_value_copy(var);
4850 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4851 tmp->expression.next = (ast_expression*)*storebase;
4856 /* there may be a name now */
4857 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4858 if (!strcmp(parser_tokval(parser), "break"))
4859 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4860 else if (parser->tok == TOKEN_KEYWORD)
4863 name = util_strdup(parser_tokval(parser));
4866 if (!parser_next(parser)) {
4869 parseerror(parser, "error after variable or field declaration");
4875 /* now this may be an array */
4876 if (parser->tok == '[') {
4878 var = parse_arraysize(parser, var);
4880 if (name) mem_d(name);
4885 /* This is the point where we can turn it into a field */
4887 /* turn it into a field if desired */
4888 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4889 tmp->expression.next = (ast_expression*)var;
4893 /* now there may be function parens again */
4894 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4895 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4896 if (parser->tok == '(' && wasarray)
4897 parseerror(parser, "arrays as part of a return type is not supported");
4898 while (parser->tok == '(') {
4899 var = parse_parameter_list(parser, var);
4901 if (name) mem_d(name);
4906 /* finally name it */
4908 if (!ast_value_set_name(var, name)) {
4911 parseerror(parser, "internal error: failed to set name");
4914 /* free the name, ast_value_set_name duplicates */
4921 static bool parse_typedef(parser_t *parser)
4923 ast_value *typevar, *oldtype;
4924 ast_expression *old;
4926 typevar = parse_typename(parser, NULL, NULL, NULL);
4931 /* while parsing types, the ast_value's get named '<something>' */
4932 if (!typevar->name || typevar->name[0] == '<') {
4933 parseerror(parser, "missing name in typedef");
4934 ast_delete(typevar);
4938 if ( (old = parser_find_var(parser, typevar->name)) ) {
4939 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4940 " -> `%s` has been declared here: %s:%i",
4941 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4942 ast_delete(typevar);
4946 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4947 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4948 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4949 ast_delete(typevar);
4953 vec_push(parser->_typedefs, typevar);
4954 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4956 if (parser->tok != ';') {
4957 parseerror(parser, "expected semicolon after typedef");
4960 if (!parser_next(parser)) {
4961 parseerror(parser, "parse error after typedef");
4968 static const char *cvq_to_str(int cvq) {
4970 case CV_NONE: return "none";
4971 case CV_VAR: return "`var`";
4972 case CV_CONST: return "`const`";
4973 default: return "<INVALID>";
4977 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4980 if (proto->cvq != var->cvq) {
4981 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4982 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4983 parser->tok == '='))
4985 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4986 "`%s` declared with different qualifiers: %s\n"
4987 " -> previous declaration here: %s:%i uses %s",
4988 var->name, cvq_to_str(var->cvq),
4989 ast_ctx(proto).file, ast_ctx(proto).line,
4990 cvq_to_str(proto->cvq));
4993 av = (var ->expression.flags & AST_FLAG_NORETURN);
4994 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4996 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4997 "`%s` declared with different attributes%s\n"
4998 " -> previous declaration here: %s:%i",
4999 var->name, (av ? ": noreturn" : ""),
5000 ast_ctx(proto).file, ast_ctx(proto).line,
5001 (ao ? ": noreturn" : ""));
5006 static bool create_array_accessors(parser_t *parser, ast_value *var)
5009 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5010 if (!parser_create_array_setter(parser, var, name))
5012 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5013 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5018 static bool parse_array(parser_t *parser, ast_value *array)
5021 if (array->initlist) {
5022 parseerror(parser, "array already initialized elsewhere");
5025 if (!parser_next(parser)) {
5026 parseerror(parser, "parse error in array initializer");
5030 while (parser->tok != '}') {
5031 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5034 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5036 parseerror(parser, "initializing element must be a compile time constant");
5039 vec_push(array->initlist, v->constval);
5040 if (v->expression.vtype == TYPE_STRING) {
5041 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5045 if (parser->tok == '}')
5047 if (parser->tok != ',' || !parser_next(parser)) {
5048 parseerror(parser, "expected comma or '}' in element list");
5052 if (!parser_next(parser) || parser->tok != ';') {
5053 parseerror(parser, "expected semicolon after initializer, got %s");
5057 if (!parser_next(parser)) {
5058 parseerror(parser, "parse error after initializer");
5063 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5064 if (array->expression.count != (size_t)-1) {
5065 parseerror(parser, "array `%s' has already been initialized with %u elements",
5066 array->name, (unsigned)array->expression.count);
5068 array->expression.count = vec_size(array->initlist);
5069 if (!create_array_accessors(parser, array))
5075 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)
5079 ast_expression *old;
5083 ast_value *basetype = NULL;
5085 bool isparam = false;
5086 bool isvector = false;
5087 bool cleanvar = true;
5088 bool wasarray = false;
5090 ast_member *me[3] = { NULL, NULL, NULL };
5091 ast_member *last_me[3] = { NULL, NULL, NULL };
5093 if (!localblock && is_static)
5094 parseerror(parser, "`static` qualifier is not supported in global scope");
5096 /* get the first complete variable */
5097 var = parse_typename(parser, &basetype, cached_typedef, NULL);
5100 ast_delete(basetype);
5104 /* while parsing types, the ast_value's get named '<something>' */
5105 if (!var->name || var->name[0] == '<') {
5106 parseerror(parser, "declaration does not declare anything");
5108 ast_delete(basetype);
5116 /* Part 0: finish the type */
5117 if (parser->tok == '(') {
5118 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5119 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5120 var = parse_parameter_list(parser, var);
5126 /* we only allow 1-dimensional arrays */
5127 if (parser->tok == '[') {
5129 var = parse_arraysize(parser, var);
5135 if (parser->tok == '(' && wasarray) {
5136 parseerror(parser, "arrays as part of a return type is not supported");
5137 /* we'll still parse the type completely for now */
5139 /* for functions returning functions */
5140 while (parser->tok == '(') {
5141 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5142 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5143 var = parse_parameter_list(parser, var);
5150 var->cvq = qualifier;
5151 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5152 var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5153 var->expression.flags |= qflags;
5156 * store the vstring back to var for alias and
5157 * deprecation messages.
5159 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5160 var->expression.flags & AST_FLAG_ALIAS)
5161 var->desc = vstring;
5163 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5164 parseerror(parser, "function aliases cannot be forward declared");
5171 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5172 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5173 * is then filled with the previous definition and the parameter-names replaced.
5175 if (!strcmp(var->name, "nil")) {
5176 if (OPTS_FLAG(UNTYPED_NIL)) {
5177 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5178 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5180 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5183 /* Deal with end_sys_ vars */
5185 if (!strcmp(var->name, "end_sys_globals")) {
5187 parser->crc_globals = vec_size(parser->globals);
5190 else if (!strcmp(var->name, "end_sys_fields")) {
5192 parser->crc_fields = vec_size(parser->fields);
5195 if (was_end && var->expression.vtype == TYPE_FIELD) {
5196 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5197 "global '%s' hint should not be a field",
5198 parser_tokval(parser)))
5205 if (!nofields && var->expression.vtype == TYPE_FIELD)
5207 /* deal with field declarations */
5208 old = parser_find_field(parser, var->name);
5210 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5211 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5220 parseerror(parser, "field `%s` already declared here: %s:%i",
5221 var->name, ast_ctx(old).file, ast_ctx(old).line);
5226 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5227 (old = parser_find_global(parser, var->name)))
5229 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5230 parseerror(parser, "field `%s` already declared here: %s:%i",
5231 var->name, ast_ctx(old).file, ast_ctx(old).line);
5238 /* deal with other globals */
5239 old = parser_find_global(parser, var->name);
5240 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5242 /* This is a function which had a prototype */
5243 if (!ast_istype(old, ast_value)) {
5244 parseerror(parser, "internal error: prototype is not an ast_value");
5248 proto = (ast_value*)old;
5249 proto->desc = var->desc;
5250 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5251 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5253 ast_ctx(proto).file, ast_ctx(proto).line);
5257 /* we need the new parameter-names */
5258 for (i = 0; i < vec_size(proto->expression.params); ++i)
5259 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5260 if (!parser_check_qualifiers(parser, var, proto)) {
5267 proto->expression.flags |= var->expression.flags;
5275 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5276 "global `%s` already declared here: %s:%i",
5277 var->name, ast_ctx(old).file, ast_ctx(old).line))
5282 if (old->flags & AST_FLAG_FINAL_DECL) {
5283 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5284 var->name, ast_ctx(old).file, ast_ctx(old).line);
5288 proto = (ast_value*)old;
5289 if (!ast_istype(old, ast_value)) {
5290 parseerror(parser, "internal error: not an ast_value");
5295 if (!parser_check_qualifiers(parser, var, proto)) {
5300 proto->expression.flags |= var->expression.flags;
5301 /* copy the context for finals,
5302 * so the error can show where it was actually made 'final'
5304 if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5305 ast_ctx(old) = ast_ctx(var);
5309 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5310 (old = parser_find_field(parser, var->name)))
5312 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5313 parseerror(parser, "global `%s` already declared here: %s:%i",
5314 var->name, ast_ctx(old).file, ast_ctx(old).line);
5321 else /* it's not a global */
5323 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5324 if (old && !isparam) {
5325 parseerror(parser, "local `%s` already declared here: %s:%i",
5326 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5330 /* doing this here as the above is just for a single scope */
5331 old = parser_find_local(parser, var->name, 0, &isparam);
5332 if (old && isparam) {
5333 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5334 "local `%s` is shadowing a parameter", var->name))
5336 parseerror(parser, "local `%s` already declared here: %s:%i",
5337 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5341 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5343 if (ast_istype(old, ast_value))
5344 var = proto = (ast_value*)old;
5353 /* in a noref section we simply bump the usecount */
5354 if (noref || parser->noref)
5358 * Create the global/local, and deal with vector types.
5361 if (var->expression.vtype == TYPE_VECTOR)
5363 else if (var->expression.vtype == TYPE_FIELD &&
5364 var->expression.next->vtype == TYPE_VECTOR)
5368 if (!create_vector_members(var, me)) {
5375 /* deal with global variables, fields, functions */
5376 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5377 var->isfield = true;
5378 vec_push(parser->fields, (ast_expression*)var);
5379 util_htset(parser->htfields, var->name, var);
5381 for (i = 0; i < 3; ++i) {
5382 vec_push(parser->fields, (ast_expression*)me[i]);
5383 util_htset(parser->htfields, me[i]->name, me[i]);
5388 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5389 parser_addglobal(parser, var->name, (ast_expression*)var);
5391 for (i = 0; i < 3; ++i) {
5392 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5396 ast_expression *find = parser_find_global(parser, var->desc);
5399 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5403 if (!ast_compare_type((ast_expression*)var, find)) {
5407 ast_type_to_string(find, ty1, sizeof(ty1));
5408 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5410 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5416 util_htset(parser->aliases, var->name, find);
5418 /* generate aliases for vector components */
5422 util_asprintf(&buffer[0], "%s_x", var->desc);
5423 util_asprintf(&buffer[1], "%s_y", var->desc);
5424 util_asprintf(&buffer[2], "%s_z", var->desc);
5426 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5427 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5428 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5438 /* a static adds itself to be generated like any other global
5439 * but is added to the local namespace instead
5441 char *defname = NULL;
5442 size_t prefix_len, ln;
5445 ln = strlen(parser->function->name);
5446 vec_append(defname, ln, parser->function->name);
5448 vec_append(defname, 2, "::");
5449 /* remember the length up to here */
5450 prefix_len = vec_size(defname);
5452 /* Add it to the local scope */
5453 util_htset(vec_last(parser->variables), var->name, (void*)var);
5455 /* now rename the global */
5456 ln = strlen(var->name);
5457 vec_append(defname, ln, var->name);
5458 /* if a variable of that name already existed, add the
5460 * The counter is incremented either way.
5462 sn_size = vec_size(parser->function->static_names);
5463 for (sn = 0; sn != sn_size; ++sn) {
5464 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5467 if (sn != sn_size) {
5469 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5470 vec_append(defname, len, num);
5474 vec_push(parser->function->static_names, util_strdup(var->name));
5475 parser->function->static_count++;
5476 ast_value_set_name(var, defname);
5478 /* push it to the to-be-generated globals */
5479 vec_push(parser->globals, (ast_expression*)var);
5481 /* same game for the vector members */
5483 for (i = 0; i < 3; ++i) {
5484 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5486 vec_shrinkto(defname, prefix_len);
5487 ln = strlen(me[i]->name);
5488 vec_append(defname, ln, me[i]->name);
5489 ast_member_set_name(me[i], defname);
5491 vec_push(parser->globals, (ast_expression*)me[i]);
5496 vec_push(localblock->locals, var);
5497 parser_addlocal(parser, var->name, (ast_expression*)var);
5499 for (i = 0; i < 3; ++i) {
5500 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5501 ast_block_collect(localblock, (ast_expression*)me[i]);
5507 memcpy(last_me, me, sizeof(me));
5508 me[0] = me[1] = me[2] = NULL;
5513 if (var->expression.vtype == TYPE_ARRAY) {
5514 if (var->expression.count != (size_t)-1) {
5515 if (!create_array_accessors(parser, var))
5519 else if (!localblock && !nofields &&
5520 var->expression.vtype == TYPE_FIELD &&
5521 var->expression.next->vtype == TYPE_ARRAY)
5524 ast_expression *telem;
5526 ast_value *array = (ast_value*)var->expression.next;
5528 if (!ast_istype(var->expression.next, ast_value)) {
5529 parseerror(parser, "internal error: field element type must be an ast_value");
5533 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5534 if (!parser_create_array_field_setter(parser, array, name))
5537 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5538 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5539 tfield->expression.next = telem;
5540 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5541 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5549 if (parser->tok == ';') {
5550 ast_delete(basetype);
5551 if (!parser_next(parser)) {
5552 parseerror(parser, "error after variable declaration");
5558 if (parser->tok == ',')
5562 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5565 parseerror(parser, "missing comma or semicolon while parsing variables");
5569 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5570 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5571 "initializing expression turns variable `%s` into a constant in this standard",
5578 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5579 if (parser->tok != '=') {
5580 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5584 if (!parser_next(parser)) {
5585 parseerror(parser, "error parsing initializer");
5589 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5590 parseerror(parser, "expected '=' before function body in this standard");
5593 if (parser->tok == '#') {
5594 ast_function *func = NULL;
5595 ast_value *number = NULL;
5601 parseerror(parser, "cannot declare builtins within functions");
5604 if (var->expression.vtype != TYPE_FUNCTION) {
5605 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5608 if (!parser_next(parser)) {
5609 parseerror(parser, "expected builtin number");
5613 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5614 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5616 parseerror(parser, "builtin number expected");
5619 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5622 parseerror(parser, "builtin number must be a compile time constant");
5625 if (number->expression.vtype == TYPE_INTEGER)
5626 builtin_num = number->constval.vint;
5627 else if (number->expression.vtype == TYPE_FLOAT)
5628 builtin_num = number->constval.vfloat;
5631 parseerror(parser, "builtin number must be an integer constant");
5636 fractional = modff(builtin_num, &integral);
5637 if (builtin_num < 0 || fractional != 0) {
5638 parseerror(parser, "builtin number must be an integer greater than zero");
5642 /* we only want the integral part anyways */
5643 builtin_num = integral;
5644 } else if (parser->tok == TOKEN_INTCONST) {
5645 builtin_num = parser_token(parser)->constval.i;
5647 parseerror(parser, "builtin number must be a compile time constant");
5651 if (var->hasvalue) {
5652 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5653 "builtin `%s` has already been defined\n"
5654 " -> previous declaration here: %s:%i",
5655 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5659 func = ast_function_new(ast_ctx(var), var->name, var);
5661 parseerror(parser, "failed to allocate function for `%s`", var->name);
5664 vec_push(parser->functions, func);
5666 func->builtin = -builtin_num-1;
5669 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5670 ? (parser->tok != ',' && parser->tok != ';')
5671 : (!parser_next(parser)))
5673 parseerror(parser, "expected comma or semicolon");
5675 ast_function_delete(func);
5676 var->constval.vfunc = NULL;
5680 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5683 /* Note that fteqcc and most others don't even *have*
5684 * local arrays, so this is not a high priority.
5686 parseerror(parser, "TODO: initializers for local arrays");
5690 var->hasvalue = true;
5691 if (!parse_array(parser, var))
5694 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5697 parseerror(parser, "cannot declare functions within functions");
5702 ast_ctx(proto) = parser_ctx(parser);
5704 if (!parse_function_body(parser, var))
5706 ast_delete(basetype);
5707 for (i = 0; i < vec_size(parser->gotos); ++i)
5708 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5709 vec_free(parser->gotos);
5710 vec_free(parser->labels);
5713 ast_expression *cexp;
5715 bool folded_const = false;
5717 cexp = parse_expression_leave(parser, true, false, false);
5720 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : NULL;
5722 /* deal with foldable constants: */
5724 var->cvq == CV_CONST && cval && cval->hasvalue && cval->cvq == CV_CONST && !cval->isfield)
5726 /* remove it from the current locals */
5728 for (i = 0; i < 3; ++i) {
5729 vec_pop(parser->_locals);
5730 vec_pop(localblock->collect);
5733 /* do sanity checking, this function really needs refactoring */
5734 if (vec_last(parser->_locals) != (ast_expression*)var)
5735 parseerror(parser, "internal error: unexpected change in local variable handling");
5737 vec_pop(parser->_locals);
5738 if (vec_last(localblock->locals) != var)
5739 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5741 vec_pop(localblock->locals);
5742 /* push it to the to-be-generated globals */
5743 vec_push(parser->globals, (ast_expression*)var);
5745 for (i = 0; i < 3; ++i)
5746 vec_push(parser->globals, (ast_expression*)last_me[i]);
5747 folded_const = true;
5750 if (folded_const || !localblock || is_static) {
5751 if (cval != parser->nil &&
5752 (!cval || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5755 parseerror(parser, "initializer is non constant");
5760 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5761 qualifier != CV_VAR)
5763 var->cvq = CV_CONST;
5765 if (cval == parser->nil)
5766 var->expression.flags |= AST_FLAG_INITIALIZED;
5769 var->hasvalue = true;
5770 if (cval->expression.vtype == TYPE_STRING)
5771 var->constval.vstring = parser_strdup(cval->constval.vstring);
5772 else if (cval->expression.vtype == TYPE_FIELD)
5773 var->constval.vfield = cval;
5775 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5781 shunt sy = { NULL, NULL, NULL, NULL };
5784 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5785 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5786 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5787 if (!parser_sy_apply_operator(parser, &sy))
5790 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5791 parseerror(parser, "internal error: leaked operands");
5792 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5800 /* a constant initialized to an inexact value should be marked inexact:
5801 * const float x = <inexact>; should propagate the inexact flag
5803 if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5804 if (cval && cval->hasvalue && cval->cvq == CV_CONST)
5805 var->inexact = cval->inexact;
5810 if (parser->tok == ',') {
5811 if (!parser_next(parser)) {
5812 parseerror(parser, "expected another variable");
5816 if (parser->tok != TOKEN_IDENT) {
5817 parseerror(parser, "expected another variable");
5820 var = ast_value_copy(basetype);
5822 ast_value_set_name(var, parser_tokval(parser));
5823 if (!parser_next(parser)) {
5824 parseerror(parser, "error parsing variable declaration");
5830 if (parser->tok != ';') {
5831 parseerror(parser, "missing semicolon after variables");
5835 if (!parser_next(parser)) {
5836 parseerror(parser, "parse error after variable declaration");
5840 ast_delete(basetype);
5844 if (cleanvar && var)
5846 ast_delete(basetype);
5850 ast_delete(basetype);
5851 if (cleanvar && var)
5853 if (me[0]) ast_member_delete(me[0]);
5854 if (me[1]) ast_member_delete(me[1]);
5855 if (me[2]) ast_member_delete(me[2]);
5859 static bool parser_global_statement(parser_t *parser)
5863 bool is_static = false;
5864 uint32_t qflags = 0;
5865 ast_value *istype = NULL;
5866 char *vstring = NULL;
5868 if (parser->tok == TOKEN_IDENT)
5869 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5871 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5873 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5875 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5877 if (cvq == CV_WRONG)
5879 return parse_variable(parser, NULL, false, cvq, NULL, noref, is_static, qflags, vstring);
5881 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5883 return parse_enum(parser);
5885 else if (parser->tok == TOKEN_KEYWORD)
5887 if (!strcmp(parser_tokval(parser), "typedef")) {
5888 if (!parser_next(parser)) {
5889 parseerror(parser, "expected type definition after 'typedef'");
5892 return parse_typedef(parser);
5894 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5897 else if (parser->tok == '#')
5899 return parse_pragma(parser);
5901 else if (parser->tok == '$')
5903 if (!parser_next(parser)) {
5904 parseerror(parser, "parse error");
5910 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5916 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5918 return util_crc16(old, str, strlen(str));
5921 static void progdefs_crc_file(const char *str)
5923 /* write to progdefs.h here */
5927 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5929 old = progdefs_crc_sum(old, str);
5930 progdefs_crc_file(str);
5934 static void generate_checksum(parser_t *parser, ir_builder *ir)
5936 uint16_t crc = 0xFFFF;
5940 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5941 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5943 progdefs_crc_file("\tint\tpad;\n");
5944 progdefs_crc_file("\tint\tofs_return[3];\n");
5945 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5946 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5947 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5948 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5949 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5950 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5951 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5952 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5954 for (i = 0; i < parser->crc_globals; ++i) {
5955 if (!ast_istype(parser->globals[i], ast_value))
5957 value = (ast_value*)(parser->globals[i]);
5958 switch (value->expression.vtype) {
5959 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5960 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5961 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5962 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5964 crc = progdefs_crc_both(crc, "\tint\t");
5967 crc = progdefs_crc_both(crc, value->name);
5968 crc = progdefs_crc_both(crc, ";\n");
5970 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5971 for (i = 0; i < parser->crc_fields; ++i) {
5972 if (!ast_istype(parser->fields[i], ast_value))
5974 value = (ast_value*)(parser->fields[i]);
5975 switch (value->expression.next->vtype) {
5976 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5977 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5978 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5979 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5981 crc = progdefs_crc_both(crc, "\tint\t");
5984 crc = progdefs_crc_both(crc, value->name);
5985 crc = progdefs_crc_both(crc, ";\n");
5987 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5988 ir->code->crc = crc;
5991 parser_t *parser_create()
5994 lex_ctx_t empty_ctx;
5997 parser = (parser_t*)mem_a(sizeof(parser_t));
6001 memset(parser, 0, sizeof(*parser));
6003 for (i = 0; i < operator_count; ++i) {
6004 if (operators[i].id == opid1('=')) {
6005 parser->assign_op = operators+i;
6009 if (!parser->assign_op) {
6010 con_err("internal error: initializing parser: failed to find assign operator\n");
6015 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6016 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6017 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6018 vec_push(parser->_blocktypedefs, 0);
6020 parser->aliases = util_htnew(PARSER_HT_SIZE);
6022 empty_ctx.file = "<internal>";
6024 empty_ctx.column = 0;
6025 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6026 parser->nil->cvq = CV_CONST;
6027 if (OPTS_FLAG(UNTYPED_NIL))
6028 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6030 parser->max_param_count = 1;
6032 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6033 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6034 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6036 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6037 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6038 parser->reserved_version->cvq = CV_CONST;
6039 parser->reserved_version->hasvalue = true;
6040 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6041 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6043 parser->reserved_version = NULL;
6046 parser->fold = fold_init (parser);
6047 parser->intrin = intrin_init(parser);
6051 static bool parser_compile(parser_t *parser)
6053 /* initial lexer/parser state */
6054 parser->lex->flags.noops = true;
6056 if (parser_next(parser))
6058 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6060 if (!parser_global_statement(parser)) {
6061 if (parser->tok == TOKEN_EOF)
6062 parseerror(parser, "unexpected end of file");
6063 else if (compile_errors)
6064 parseerror(parser, "there have been errors, bailing out");
6065 lex_close(parser->lex);
6071 parseerror(parser, "parse error");
6072 lex_close(parser->lex);
6077 lex_close(parser->lex);
6080 return !compile_errors;
6083 bool parser_compile_file(parser_t *parser, const char *filename)
6085 parser->lex = lex_open(filename);
6087 con_err("failed to open file \"%s\"\n", filename);
6090 return parser_compile(parser);
6093 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6095 parser->lex = lex_open_string(str, len, name);
6097 con_err("failed to create lexer for string \"%s\"\n", name);
6100 return parser_compile(parser);
6103 static void parser_remove_ast(parser_t *parser)
6106 if (parser->ast_cleaned)
6108 parser->ast_cleaned = true;
6109 for (i = 0; i < vec_size(parser->accessors); ++i) {
6110 ast_delete(parser->accessors[i]->constval.vfunc);
6111 parser->accessors[i]->constval.vfunc = NULL;
6112 ast_delete(parser->accessors[i]);
6114 for (i = 0; i < vec_size(parser->functions); ++i) {
6115 ast_delete(parser->functions[i]);
6117 for (i = 0; i < vec_size(parser->fields); ++i) {
6118 ast_delete(parser->fields[i]);
6120 for (i = 0; i < vec_size(parser->globals); ++i) {
6121 ast_delete(parser->globals[i]);
6123 vec_free(parser->accessors);
6124 vec_free(parser->functions);
6125 vec_free(parser->globals);
6126 vec_free(parser->fields);
6128 for (i = 0; i < vec_size(parser->variables); ++i)
6129 util_htdel(parser->variables[i]);
6130 vec_free(parser->variables);
6131 vec_free(parser->_blocklocals);
6132 vec_free(parser->_locals);
6134 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6135 ast_delete(parser->_typedefs[i]);
6136 vec_free(parser->_typedefs);
6137 for (i = 0; i < vec_size(parser->typedefs); ++i)
6138 util_htdel(parser->typedefs[i]);
6139 vec_free(parser->typedefs);
6140 vec_free(parser->_blocktypedefs);
6142 vec_free(parser->_block_ctx);
6144 vec_free(parser->labels);
6145 vec_free(parser->gotos);
6146 vec_free(parser->breaks);
6147 vec_free(parser->continues);
6149 ast_value_delete(parser->nil);
6151 ast_value_delete(parser->const_vec[0]);
6152 ast_value_delete(parser->const_vec[1]);
6153 ast_value_delete(parser->const_vec[2]);
6155 if (parser->reserved_version)
6156 ast_value_delete(parser->reserved_version);
6158 util_htdel(parser->aliases);
6159 fold_cleanup(parser->fold);
6160 intrin_cleanup(parser->intrin);
6163 void parser_cleanup(parser_t *parser)
6165 parser_remove_ast(parser);
6169 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6171 ast_expression *expr;
6175 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6179 for (i = 0; i != vec_size(parser->functions); ++i) {
6180 if (!strcmp(parser->functions[i]->name, "coverage")) {
6181 func = parser->functions[i];
6186 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6187 con_out("coverage support requested but no coverage() builtin declared\n");
6188 ir_builder_delete(ir);
6195 expr = (ast_expression*)cov;
6197 if (expr->vtype != TYPE_FUNCTION || vec_size(expr->params) != 0) {
6199 ast_type_to_string(expr, ty, sizeof(ty));
6200 con_out("invalid type for coverage(): %s\n", ty);
6201 ir_builder_delete(ir);
6205 ir->coverage_func = func->ir_func->value;
6209 bool parser_finish(parser_t *parser, const char *output)
6215 if (compile_errors) {
6216 con_out("*** there were compile errors\n");
6220 ir = ir_builder_new("gmqcc_out");
6222 con_out("failed to allocate builder\n");
6226 for (i = 0; i < vec_size(parser->fields); ++i) {
6229 if (!ast_istype(parser->fields[i], ast_value))
6231 field = (ast_value*)parser->fields[i];
6232 hasvalue = field->hasvalue;
6233 field->hasvalue = false;
6234 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6235 con_out("failed to generate field %s\n", field->name);
6236 ir_builder_delete(ir);
6241 ast_expression *subtype;
6242 field->hasvalue = true;
6243 subtype = field->expression.next;
6244 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6245 if (subtype->vtype == TYPE_FIELD)
6246 ifld->fieldtype = subtype->next->vtype;
6247 else if (subtype->vtype == TYPE_FUNCTION)
6248 ifld->outtype = subtype->next->vtype;
6249 (void)!ir_value_set_field(field->ir_v, ifld);
6252 for (i = 0; i < vec_size(parser->globals); ++i) {
6254 if (!ast_istype(parser->globals[i], ast_value))
6256 asvalue = (ast_value*)(parser->globals[i]);
6257 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6258 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6259 "unused global: `%s`", asvalue->name);
6261 if (!ast_global_codegen(asvalue, ir, false)) {
6262 con_out("failed to generate global %s\n", asvalue->name);
6263 ir_builder_delete(ir);
6267 /* Build function vararg accessor ast tree now before generating
6268 * immediates, because the accessors may add new immediates
6270 for (i = 0; i < vec_size(parser->functions); ++i) {
6271 ast_function *f = parser->functions[i];
6273 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6274 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6275 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6276 con_out("failed to generate vararg setter for %s\n", f->name);
6277 ir_builder_delete(ir);
6280 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6281 con_out("failed to generate vararg getter for %s\n", f->name);
6282 ir_builder_delete(ir);
6286 ast_delete(f->varargs);
6291 /* Now we can generate immediates */
6292 if (!fold_generate(parser->fold, ir))
6295 /* before generating any functions we need to set the coverage_func */
6296 if (!parser_set_coverage_func(parser, ir))
6299 for (i = 0; i < vec_size(parser->globals); ++i) {
6301 if (!ast_istype(parser->globals[i], ast_value))
6303 asvalue = (ast_value*)(parser->globals[i]);
6304 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6306 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6307 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6308 "uninitialized constant: `%s`",
6310 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6311 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6312 "uninitialized global: `%s`",
6315 if (!ast_generate_accessors(asvalue, ir)) {
6316 ir_builder_delete(ir);
6320 for (i = 0; i < vec_size(parser->fields); ++i) {
6322 asvalue = (ast_value*)(parser->fields[i]->next);
6324 if (!ast_istype((ast_expression*)asvalue, ast_value))
6326 if (asvalue->expression.vtype != TYPE_ARRAY)
6328 if (!ast_generate_accessors(asvalue, ir)) {
6329 ir_builder_delete(ir);
6333 if (parser->reserved_version &&
6334 !ast_global_codegen(parser->reserved_version, ir, false))
6336 con_out("failed to generate reserved::version");
6337 ir_builder_delete(ir);
6340 for (i = 0; i < vec_size(parser->functions); ++i) {
6341 ast_function *f = parser->functions[i];
6342 if (!ast_function_codegen(f, ir)) {
6343 con_out("failed to generate function %s\n", f->name);
6344 ir_builder_delete(ir);
6349 generate_checksum(parser, ir);
6351 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6352 ir_builder_dump(ir, con_out);
6353 for (i = 0; i < vec_size(parser->functions); ++i) {
6354 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6355 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6356 ir_builder_delete(ir);
6360 parser_remove_ast(parser);
6362 if (compile_Werrors) {
6363 con_out("*** there were warnings treated as errors\n");
6364 compile_show_werrors();
6369 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6370 ir_builder_dump(ir, con_out);
6372 if (!ir_builder_generate(ir, output)) {
6373 con_out("*** failed to generate output file\n");
6374 ir_builder_delete(ir);
6378 ir_builder_delete(ir);