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)
83 for (auto &it : parser->labels)
84 if (!strcmp(it->name, name))
85 return (ast_expression*)it;
89 ast_expression* parser_find_global(parser_t *parser, const char *name)
91 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
94 return (ast_expression*)util_htget(parser->htglobals, name);
97 static ast_expression* parser_find_param(parser_t *parser, const char *name)
100 if (!parser->function)
102 fun = parser->function->vtype;
103 for (auto &it : fun->expression.params) {
104 if (!strcmp(it->name, name))
105 return (ast_expression*)it;
110 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
115 hash = util_hthash(parser->htglobals, name);
118 for (i = vec_size(parser->variables); i > upto;) {
120 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
124 return parser_find_param(parser, name);
127 static ast_expression* parser_find_var(parser_t *parser, const char *name)
131 v = parser_find_local(parser, name, 0, &dummy);
132 if (!v) v = parser_find_global(parser, name);
136 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
140 hash = util_hthash(parser->typedefs[0], name);
142 for (i = vec_size(parser->typedefs); i > upto;) {
144 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
151 size_t etype; /* 0 = expression, others are operators */
155 ast_block *block; /* for commas and function calls */
174 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
185 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
189 e.out = (ast_expression*)v;
196 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
198 e.etype = 1 + (op - operators);
207 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
218 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
219 * so we need to rotate it to become ent.(foo[n]).
221 static bool rotate_entfield_array_index_nodes(ast_expression **out)
223 ast_array_index *index, *oldindex;
224 ast_entfield *entfield;
228 ast_expression *entity;
230 lex_ctx_t ctx = ast_ctx(*out);
232 if (!ast_istype(*out, ast_array_index))
234 index = (ast_array_index*)*out;
236 if (!ast_istype(index->array, ast_entfield))
238 entfield = (ast_entfield*)index->array;
240 if (!ast_istype(entfield->field, ast_value))
242 field = (ast_value*)entfield->field;
245 entity = entfield->entity;
249 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
250 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
251 *out = (ast_expression*)entfield;
253 oldindex->array = NULL;
254 oldindex->index = NULL;
255 ast_delete(oldindex);
260 static bool check_write_to(lex_ctx_t ctx, ast_expression *expr)
262 if (ast_istype(expr, ast_value)) {
263 ast_value *val = (ast_value*)expr;
264 if (val->cvq == CV_CONST) {
265 if (val->name[0] == '#') {
266 compile_error(ctx, "invalid assignment to a literal constant");
270 * To work around quakeworld we must elide the error and make it
273 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_QCC)
274 compile_error(ctx, "assignment to constant `%s`", val->name);
276 (void)!compile_warning(ctx, WARN_CONST_OVERWRITE, "assignment to constant `%s`", val->name);
283 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
287 ast_expression *out = NULL;
288 ast_expression *exprs[3];
289 ast_block *blocks[3];
290 ast_binstore *asbinstore;
291 size_t i, assignop, addop, subop;
292 qcint_t generated_op = 0;
297 if (!vec_size(sy->ops)) {
298 parseerror(parser, "internal error: missing operator");
302 if (vec_last(sy->ops).isparen) {
303 parseerror(parser, "unmatched parenthesis");
307 op = &operators[vec_last(sy->ops).etype - 1];
308 ctx = vec_last(sy->ops).ctx;
310 if (vec_size(sy->out) < op->operands) {
311 if (op->flags & OP_PREFIX)
312 compile_error(ctx, "expected expression after unary operator `%s`", op->op, (int)op->id);
313 else /* this should have errored previously already */
314 compile_error(ctx, "expected expression after operator `%s`", op->op, (int)op->id);
318 vec_shrinkby(sy->ops, 1);
320 /* op(:?) has no input and no output */
324 vec_shrinkby(sy->out, op->operands);
325 for (i = 0; i < op->operands; ++i) {
326 exprs[i] = sy->out[vec_size(sy->out)+i].out;
327 blocks[i] = sy->out[vec_size(sy->out)+i].block;
329 if (exprs[i]->vtype == TYPE_NOEXPR &&
330 !(i != 0 && op->id == opid2('?',':')) &&
331 !(i == 1 && op->id == opid1('.')))
333 if (ast_istype(exprs[i], ast_label))
334 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
336 compile_error(ast_ctx(exprs[i]), "not an expression");
337 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
341 if (blocks[0] && blocks[0]->exprs.empty() && op->id != opid1(',')) {
342 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
346 #define NotSameType(T) \
347 (exprs[0]->vtype != exprs[1]->vtype || \
348 exprs[0]->vtype != T)
353 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
357 if (exprs[0]->vtype == TYPE_VECTOR &&
358 exprs[1]->vtype == TYPE_NOEXPR)
360 if (exprs[1] == (ast_expression*)parser->const_vec[0])
361 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
362 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
363 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
364 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
365 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
367 compile_error(ctx, "access to invalid vector component");
371 else if (exprs[0]->vtype == TYPE_ENTITY) {
372 if (exprs[1]->vtype != TYPE_FIELD) {
373 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
376 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
378 else if (exprs[0]->vtype == TYPE_VECTOR) {
379 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
383 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
389 if (exprs[0]->vtype != TYPE_ARRAY &&
390 !(exprs[0]->vtype == TYPE_FIELD &&
391 exprs[0]->next->vtype == TYPE_ARRAY))
393 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
394 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
397 if (exprs[1]->vtype != TYPE_FLOAT) {
398 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
399 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
402 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
403 rotate_entfield_array_index_nodes(&out);
407 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
408 vec_push(sy->out, syexp(ctx, exprs[0]));
409 vec_push(sy->out, syexp(ctx, exprs[1]));
410 vec_last(sy->argc)++;
414 if (!ast_block_add_expr(blocks[0], exprs[1]))
417 blocks[0] = ast_block_new(ctx);
418 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
419 !ast_block_add_expr(blocks[0], exprs[1]))
424 ast_block_set_type(blocks[0], exprs[1]);
426 vec_push(sy->out, syblock(ctx, blocks[0]));
433 if ((out = fold_op(parser->fold, op, exprs)))
436 if (exprs[0]->vtype != TYPE_FLOAT &&
437 exprs[0]->vtype != TYPE_VECTOR) {
438 compile_error(ctx, "invalid types used in unary expression: cannot negate type %s",
439 type_name[exprs[0]->vtype]);
442 if (exprs[0]->vtype == TYPE_FLOAT)
443 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_F, exprs[0]);
445 out = (ast_expression*)ast_unary_new(ctx, VINSTR_NEG_V, exprs[0]);
449 if (!(out = fold_op(parser->fold, op, exprs))) {
450 switch (exprs[0]->vtype) {
452 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
455 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
458 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
459 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
461 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
463 /* we don't constant-fold NOT for these types */
465 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
468 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
471 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
472 type_name[exprs[0]->vtype]);
479 if (exprs[0]->vtype != exprs[1]->vtype ||
480 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
482 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
483 type_name[exprs[0]->vtype],
484 type_name[exprs[1]->vtype]);
487 if (!(out = fold_op(parser->fold, op, exprs))) {
488 switch (exprs[0]->vtype) {
490 out = fold_binary(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
493 out = fold_binary(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
496 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
497 type_name[exprs[0]->vtype],
498 type_name[exprs[1]->vtype]);
504 if (exprs[0]->vtype != exprs[1]->vtype ||
505 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
507 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
508 type_name[exprs[1]->vtype],
509 type_name[exprs[0]->vtype]);
512 if (!(out = fold_op(parser->fold, op, exprs))) {
513 switch (exprs[0]->vtype) {
515 out = fold_binary(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
518 out = fold_binary(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
521 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
522 type_name[exprs[1]->vtype],
523 type_name[exprs[0]->vtype]);
529 if (exprs[0]->vtype != exprs[1]->vtype &&
530 !(exprs[0]->vtype == TYPE_VECTOR &&
531 exprs[1]->vtype == TYPE_FLOAT) &&
532 !(exprs[1]->vtype == TYPE_VECTOR &&
533 exprs[0]->vtype == TYPE_FLOAT)
536 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
537 type_name[exprs[1]->vtype],
538 type_name[exprs[0]->vtype]);
541 if (!(out = fold_op(parser->fold, op, exprs))) {
542 switch (exprs[0]->vtype) {
544 if (exprs[1]->vtype == TYPE_VECTOR)
545 out = fold_binary(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
547 out = fold_binary(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
550 if (exprs[1]->vtype == TYPE_FLOAT)
551 out = fold_binary(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
553 out = fold_binary(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
556 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
557 type_name[exprs[1]->vtype],
558 type_name[exprs[0]->vtype]);
565 if (exprs[1]->vtype != TYPE_FLOAT) {
566 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
567 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
568 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
571 if (!(out = fold_op(parser->fold, op, exprs))) {
572 if (exprs[0]->vtype == TYPE_FLOAT)
573 out = fold_binary(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
575 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
576 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
577 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
584 if (NotSameType(TYPE_FLOAT)) {
585 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
586 type_name[exprs[0]->vtype],
587 type_name[exprs[1]->vtype]);
589 } else if (!(out = fold_op(parser->fold, op, exprs))) {
590 /* generate a call to __builtin_mod */
591 ast_expression *mod = intrin_func(parser->intrin, "mod");
592 ast_call *call = NULL;
593 if (!mod) return false; /* can return null for missing floor */
595 call = ast_call_new(parser_ctx(parser), mod);
596 call->params.push_back(exprs[0]);
597 call->params.push_back(exprs[1]);
599 out = (ast_expression*)call;
604 compile_error(ctx, "%= is unimplemented");
610 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
611 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
612 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
614 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
615 type_name[exprs[0]->vtype],
616 type_name[exprs[1]->vtype]);
620 if (!(out = fold_op(parser->fold, op, exprs))) {
622 * IF the first expression is float, the following will be too
623 * since scalar ^ vector is not allowed.
625 if (exprs[0]->vtype == TYPE_FLOAT) {
626 out = fold_binary(ctx,
627 (op->id == opid1('^') ? VINSTR_BITXOR : op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
631 * The first is a vector: vector is allowed to bitop with vector and
632 * with scalar, branch here for the second operand.
634 if (exprs[1]->vtype == TYPE_VECTOR) {
636 * Bitop all the values of the vector components against the
637 * vectors components in question.
639 out = fold_binary(ctx,
640 (op->id == opid1('^') ? VINSTR_BITXOR_V : op->id == opid1('|') ? VINSTR_BITOR_V : VINSTR_BITAND_V),
643 out = fold_binary(ctx,
644 (op->id == opid1('^') ? VINSTR_BITXOR_VF : op->id == opid1('|') ? VINSTR_BITOR_VF : VINSTR_BITAND_VF),
653 if (NotSameType(TYPE_FLOAT)) {
654 compile_error(ctx, "invalid types used in expression: cannot perform shift between types %s and %s",
655 type_name[exprs[0]->vtype],
656 type_name[exprs[1]->vtype]);
660 if (!(out = fold_op(parser->fold, op, exprs))) {
661 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid2('<','<')) ? "__builtin_lshift" : "__builtin_rshift");
662 ast_call *call = ast_call_new(parser_ctx(parser), shift);
663 call->params.push_back(exprs[0]);
664 call->params.push_back(exprs[1]);
665 out = (ast_expression*)call;
669 case opid3('<','<','='):
670 case opid3('>','>','='):
671 if (NotSameType(TYPE_FLOAT)) {
672 compile_error(ctx, "invalid types used in expression: cannot perform shift operation between types %s and %s",
673 type_name[exprs[0]->vtype],
674 type_name[exprs[1]->vtype]);
678 if(!(out = fold_op(parser->fold, op, exprs))) {
679 ast_expression *shift = intrin_func(parser->intrin, (op->id == opid3('<','<','=')) ? "__builtin_lshift" : "__builtin_rshift");
680 ast_call *call = ast_call_new(parser_ctx(parser), shift);
681 call->params.push_back(exprs[0]);
682 call->params.push_back(exprs[1]);
683 out = (ast_expression*)ast_store_new(
687 (ast_expression*)call
694 generated_op += 1; /* INSTR_OR */
696 generated_op += INSTR_AND;
697 if (!(out = fold_op(parser->fold, op, exprs))) {
698 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
699 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
700 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
701 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
704 for (i = 0; i < 2; ++i) {
705 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
706 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
708 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
710 exprs[i] = out; out = NULL;
711 if (OPTS_FLAG(PERL_LOGIC)) {
712 /* here we want to keep the right expressions' type */
716 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
717 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
721 exprs[i] = out; out = NULL;
722 if (OPTS_FLAG(PERL_LOGIC)) {
723 /* here we want to keep the right expressions' type */
728 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
733 if (vec_last(sy->paren) != PAREN_TERNARY2) {
734 compile_error(ctx, "mismatched parenthesis/ternary");
738 if (!ast_compare_type(exprs[1], exprs[2])) {
739 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
740 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
741 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
744 if (!(out = fold_op(parser->fold, op, exprs)))
745 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
748 case opid2('*', '*'):
749 if (NotSameType(TYPE_FLOAT)) {
750 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
751 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
752 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
757 if (!(out = fold_op(parser->fold, op, exprs))) {
758 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
759 gencall->params.push_back(exprs[0]);
760 gencall->params.push_back(exprs[1]);
761 out = (ast_expression*)gencall;
765 case opid2('>', '<'):
766 if (NotSameType(TYPE_VECTOR)) {
767 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
768 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
769 compile_error(ctx, "invalid types used in cross product: %s and %s",
774 if (!(out = fold_op(parser->fold, op, exprs))) {
785 case opid3('<','=','>'): /* -1, 0, or 1 */
786 if (NotSameType(TYPE_FLOAT)) {
787 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
788 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
789 compile_error(ctx, "invalid types used in comparision: %s and %s",
795 if (!(out = fold_op(parser->fold, op, exprs))) {
796 /* This whole block is NOT fold_binary safe */
797 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
799 eq->refs = AST_REF_NONE;
802 out = (ast_expression*)ast_ternary_new(ctx,
803 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
805 (ast_expression*)parser->fold->imm_float[2],
808 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
810 (ast_expression*)parser->fold->imm_float[0],
813 (ast_expression*)parser->fold->imm_float[1]
823 generated_op += 1; /* INSTR_GT */
825 generated_op += 1; /* INSTR_LT */
826 case opid2('>', '='):
827 generated_op += 1; /* INSTR_GE */
828 case opid2('<', '='):
829 generated_op += INSTR_LE;
830 if (NotSameType(TYPE_FLOAT)) {
831 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
832 type_name[exprs[0]->vtype],
833 type_name[exprs[1]->vtype]);
836 if (!(out = fold_op(parser->fold, op, exprs)))
837 out = fold_binary(ctx, generated_op, exprs[0], exprs[1]);
839 case opid2('!', '='):
840 if (exprs[0]->vtype != exprs[1]->vtype) {
841 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
842 type_name[exprs[0]->vtype],
843 type_name[exprs[1]->vtype]);
846 if (!(out = fold_op(parser->fold, op, exprs)))
847 out = fold_binary(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
849 case opid2('=', '='):
850 if (exprs[0]->vtype != exprs[1]->vtype) {
851 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
852 type_name[exprs[0]->vtype],
853 type_name[exprs[1]->vtype]);
856 if (!(out = fold_op(parser->fold, op, exprs)))
857 out = fold_binary(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
861 if (ast_istype(exprs[0], ast_entfield)) {
862 ast_expression *field = ((ast_entfield*)exprs[0])->field;
863 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
864 exprs[0]->vtype == TYPE_FIELD &&
865 exprs[0]->next->vtype == TYPE_VECTOR)
867 assignop = type_storep_instr[TYPE_VECTOR];
870 assignop = type_storep_instr[exprs[0]->vtype];
871 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
873 ast_type_to_string(field->next, ty1, sizeof(ty1));
874 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
875 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
876 field->next->vtype == TYPE_FUNCTION &&
877 exprs[1]->vtype == TYPE_FUNCTION)
879 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
880 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
883 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
888 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
889 exprs[0]->vtype == TYPE_FIELD &&
890 exprs[0]->next->vtype == TYPE_VECTOR)
892 assignop = type_store_instr[TYPE_VECTOR];
895 assignop = type_store_instr[exprs[0]->vtype];
898 if (assignop == VINSTR_END) {
899 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
900 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
901 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
903 else if (!ast_compare_type(exprs[0], exprs[1]))
905 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
906 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
907 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
908 exprs[0]->vtype == TYPE_FUNCTION &&
909 exprs[1]->vtype == TYPE_FUNCTION)
911 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
912 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
915 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
918 (void)check_write_to(ctx, exprs[0]);
919 /* When we're a vector of part of an entity field we use STOREP */
920 if (ast_istype(exprs[0], ast_member) && ast_istype(((ast_member*)exprs[0])->owner, ast_entfield))
921 assignop = INSTR_STOREP_F;
922 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
924 case opid3('+','+','P'):
925 case opid3('-','-','P'):
927 if (exprs[0]->vtype != TYPE_FLOAT) {
928 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
929 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
932 if (op->id == opid3('+','+','P'))
936 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
937 if (ast_istype(exprs[0], ast_entfield)) {
938 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
940 (ast_expression*)parser->fold->imm_float[1]);
942 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
944 (ast_expression*)parser->fold->imm_float[1]);
947 case opid3('S','+','+'):
948 case opid3('S','-','-'):
950 if (exprs[0]->vtype != TYPE_FLOAT) {
951 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
952 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
955 if (op->id == opid3('S','+','+')) {
962 (void)check_write_to(ast_ctx(exprs[0]), exprs[0]);
963 if (ast_istype(exprs[0], ast_entfield)) {
964 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
966 (ast_expression*)parser->fold->imm_float[1]);
968 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
970 (ast_expression*)parser->fold->imm_float[1]);
974 out = fold_binary(ctx, subop,
976 (ast_expression*)parser->fold->imm_float[1]);
981 if (exprs[0]->vtype != exprs[1]->vtype ||
982 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
984 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
985 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
986 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
990 (void)check_write_to(ctx, exprs[0]);
991 if (ast_istype(exprs[0], ast_entfield))
992 assignop = type_storep_instr[exprs[0]->vtype];
994 assignop = type_store_instr[exprs[0]->vtype];
995 switch (exprs[0]->vtype) {
997 out = (ast_expression*)ast_binstore_new(ctx, assignop,
998 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1002 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1003 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1004 exprs[0], exprs[1]);
1007 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1008 type_name[exprs[0]->vtype],
1009 type_name[exprs[1]->vtype]);
1013 case opid2('*','='):
1014 case opid2('/','='):
1015 if (exprs[1]->vtype != TYPE_FLOAT ||
1016 !(exprs[0]->vtype == TYPE_FLOAT ||
1017 exprs[0]->vtype == TYPE_VECTOR))
1019 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1020 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1021 compile_error(ctx, "invalid types used in expression: %s and %s",
1025 (void)check_write_to(ctx, exprs[0]);
1026 if (ast_istype(exprs[0], ast_entfield))
1027 assignop = type_storep_instr[exprs[0]->vtype];
1029 assignop = type_store_instr[exprs[0]->vtype];
1030 switch (exprs[0]->vtype) {
1032 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1033 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1034 exprs[0], exprs[1]);
1037 if (op->id == opid2('*','=')) {
1038 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1039 exprs[0], exprs[1]);
1041 out = fold_binary(ctx, INSTR_DIV_F,
1042 (ast_expression*)parser->fold->imm_float[1],
1045 compile_error(ctx, "internal error: failed to generate division");
1048 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1053 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1054 type_name[exprs[0]->vtype],
1055 type_name[exprs[1]->vtype]);
1059 case opid2('&','='):
1060 case opid2('|','='):
1061 case opid2('^','='):
1062 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1063 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1064 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1065 compile_error(ctx, "invalid types used in expression: %s and %s",
1069 (void)check_write_to(ctx, exprs[0]);
1070 if (ast_istype(exprs[0], ast_entfield))
1071 assignop = type_storep_instr[exprs[0]->vtype];
1073 assignop = type_store_instr[exprs[0]->vtype];
1074 if (exprs[0]->vtype == TYPE_FLOAT)
1075 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1076 (op->id == opid2('^','=') ? VINSTR_BITXOR : op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1077 exprs[0], exprs[1]);
1079 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1080 (op->id == opid2('^','=') ? VINSTR_BITXOR_V : op->id == opid2('&','=') ? VINSTR_BITAND_V : VINSTR_BITOR_V),
1081 exprs[0], exprs[1]);
1083 case opid3('&','~','='):
1084 /* This is like: a &= ~(b);
1085 * But QC has no bitwise-not, so we implement it as
1088 if (NotSameType(TYPE_FLOAT) && NotSameType(TYPE_VECTOR)) {
1089 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1090 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1091 compile_error(ctx, "invalid types used in expression: %s and %s",
1095 if (ast_istype(exprs[0], ast_entfield))
1096 assignop = type_storep_instr[exprs[0]->vtype];
1098 assignop = type_store_instr[exprs[0]->vtype];
1099 if (exprs[0]->vtype == TYPE_FLOAT)
1100 out = fold_binary(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1102 out = fold_binary(ctx, VINSTR_BITAND_V, exprs[0], exprs[1]);
1105 (void)check_write_to(ctx, exprs[0]);
1106 if (exprs[0]->vtype == TYPE_FLOAT)
1107 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1109 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_V, exprs[0], out);
1110 asbinstore->keep_dest = true;
1111 out = (ast_expression*)asbinstore;
1114 case opid3('l', 'e', 'n'):
1115 if (exprs[0]->vtype != TYPE_STRING && exprs[0]->vtype != TYPE_ARRAY) {
1116 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1117 compile_error(ast_ctx(exprs[0]), "invalid type for length operator: %s", ty1);
1120 /* strings must be const, arrays are statically sized */
1121 if (exprs[0]->vtype == TYPE_STRING &&
1122 !(((ast_value*)exprs[0])->hasvalue && ((ast_value*)exprs[0])->cvq == CV_CONST))
1124 compile_error(ast_ctx(exprs[0]), "operand of length operator not a valid constant expression");
1127 out = fold_op(parser->fold, op, exprs);
1130 case opid2('~', 'P'):
1131 if (exprs[0]->vtype != TYPE_FLOAT && exprs[0]->vtype != TYPE_VECTOR) {
1132 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1133 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1136 if (!(out = fold_op(parser->fold, op, exprs))) {
1137 if (exprs[0]->vtype == TYPE_FLOAT) {
1138 out = fold_binary(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1140 out = fold_binary(ctx, INSTR_SUB_V, (ast_expression*)parser->fold->imm_vector[1], exprs[0]);
1147 compile_error(ctx, "failed to apply operator %s", op->op);
1151 vec_push(sy->out, syexp(ctx, out));
1155 static bool parser_close_call(parser_t *parser, shunt *sy)
1157 /* was a function call */
1158 ast_expression *fun;
1159 ast_value *funval = NULL;
1163 size_t paramcount, i;
1166 fid = vec_last(sy->ops).off;
1167 vec_shrinkby(sy->ops, 1);
1169 /* out[fid] is the function
1170 * everything above is parameters...
1172 if (!vec_size(sy->argc)) {
1173 parseerror(parser, "internal error: no argument counter available");
1177 paramcount = vec_last(sy->argc);
1180 if (vec_size(sy->out) < fid) {
1181 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1182 (unsigned long)vec_size(sy->out),
1184 (unsigned long)paramcount);
1189 * TODO handle this at the intrinsic level with an ast_intrinsic
1192 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1194 if (fid+2 != vec_size(sy->out) ||
1195 vec_last(sy->out).block)
1197 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1200 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1201 ast_unref(vec_last(sy->out).out);
1202 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1203 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1204 vec_shrinkby(sy->out, 1);
1209 * Now we need to determine if the function that is being called is
1210 * an intrinsic so we can evaluate if the arguments to it are constant
1211 * and than fruitfully fold them.
1213 #define fold_can_1(X) \
1214 (ast_istype(((ast_expression*)(X)), ast_value) && (X)->hasvalue && ((X)->cvq == CV_CONST) && \
1215 ((ast_expression*)(X))->vtype != TYPE_FUNCTION)
1217 if (fid + 1 < vec_size(sy->out))
1220 for (i = 0; i < paramcount; ++i) {
1221 if (!fold_can_1((ast_value*)sy->out[fid + 1 + i].out)) {
1228 * All is well which ends well, if we make it into here we can ignore the
1229 * intrinsic call and just evaluate it i.e constant fold it.
1231 if (fold && ast_istype(fun, ast_value) && ((ast_value*)fun)->intrinsic) {
1232 ast_expression **exprs = NULL;
1233 ast_expression *foldval = NULL;
1235 for (i = 0; i < paramcount; i++)
1236 vec_push(exprs, sy->out[fid+1 + i].out);
1238 if (!(foldval = intrin_fold(parser->intrin, (ast_value*)fun, exprs))) {
1244 * Blub: what sorts of unreffing and resizing of
1245 * sy->out should I be doing here?
1247 sy->out[fid] = syexp(foldval->node.context, foldval);
1248 vec_shrinkby(sy->out, paramcount);
1255 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1260 if (fid+1 + paramcount != vec_size(sy->out)) {
1261 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1262 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1266 for (i = 0; i < paramcount; ++i)
1267 call->params.push_back(sy->out[fid+1 + i].out);
1268 vec_shrinkby(sy->out, paramcount);
1269 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1270 if (parser->max_param_count < paramcount)
1271 parser->max_param_count = paramcount;
1273 if (ast_istype(fun, ast_value)) {
1274 funval = (ast_value*)fun;
1275 if ((fun->flags & AST_FLAG_VARIADIC) &&
1276 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1278 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount, false);
1282 /* overwrite fid, the function, with a call */
1283 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1285 if (fun->vtype != TYPE_FUNCTION) {
1286 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1291 parseerror(parser, "could not determine function return type");
1294 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1296 if (fun->flags & AST_FLAG_DEPRECATED) {
1298 return !parsewarning(parser, WARN_DEPRECATED,
1299 "call to function (which is marked deprecated)\n",
1300 "-> it has been declared here: %s:%i",
1301 ast_ctx(fun).file, ast_ctx(fun).line);
1304 return !parsewarning(parser, WARN_DEPRECATED,
1305 "call to `%s` (which is marked deprecated)\n"
1306 "-> `%s` declared here: %s:%i",
1307 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1309 return !parsewarning(parser, WARN_DEPRECATED,
1310 "call to `%s` (deprecated: %s)\n"
1311 "-> `%s` declared here: %s:%i",
1312 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1316 if (fun->params.size() != paramcount &&
1317 !((fun->flags & AST_FLAG_VARIADIC) &&
1318 fun->params.size() < paramcount))
1320 const char *fewmany = (fun->params.size() > paramcount) ? "few" : "many";
1322 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1323 "too %s parameters for call to %s: expected %i, got %i\n"
1324 " -> `%s` has been declared here: %s:%i",
1325 fewmany, fval->name, (int)fun->params.size(), (int)paramcount,
1326 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1328 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1329 "too %s parameters for function call: expected %i, got %i\n"
1330 " -> it has been declared here: %s:%i",
1331 fewmany, (int)fun->params.size(), (int)paramcount,
1332 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1339 static bool parser_close_paren(parser_t *parser, shunt *sy)
1341 if (!vec_size(sy->ops)) {
1342 parseerror(parser, "unmatched closing paren");
1346 while (vec_size(sy->ops)) {
1347 if (vec_last(sy->ops).isparen) {
1348 if (vec_last(sy->paren) == PAREN_FUNC) {
1350 if (!parser_close_call(parser, sy))
1354 if (vec_last(sy->paren) == PAREN_EXPR) {
1356 if (!vec_size(sy->out)) {
1357 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1358 vec_shrinkby(sy->ops, 1);
1361 vec_shrinkby(sy->ops, 1);
1364 if (vec_last(sy->paren) == PAREN_INDEX) {
1366 /* pop off the parenthesis */
1367 vec_shrinkby(sy->ops, 1);
1368 /* then apply the index operator */
1369 if (!parser_sy_apply_operator(parser, sy))
1373 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1374 vec_last(sy->paren) = PAREN_TERNARY2;
1375 /* pop off the parenthesis */
1376 vec_shrinkby(sy->ops, 1);
1379 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1382 if (!parser_sy_apply_operator(parser, sy))
1388 static void parser_reclassify_token(parser_t *parser)
1391 if (parser->tok >= TOKEN_START)
1393 for (i = 0; i < operator_count; ++i) {
1394 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1395 parser->tok = TOKEN_OPERATOR;
1401 static ast_expression* parse_vararg_do(parser_t *parser)
1403 ast_expression *idx, *out;
1405 ast_value *funtype = parser->function->vtype;
1406 lex_ctx_t ctx = parser_ctx(parser);
1408 if (!parser->function->varargs) {
1409 parseerror(parser, "function has no variable argument list");
1413 if (!parser_next(parser) || parser->tok != '(') {
1414 parseerror(parser, "expected parameter index and type in parenthesis");
1417 if (!parser_next(parser)) {
1418 parseerror(parser, "error parsing parameter index");
1422 idx = parse_expression_leave(parser, true, false, false);
1426 if (parser->tok != ',') {
1427 if (parser->tok != ')') {
1429 parseerror(parser, "expected comma after parameter index");
1432 /* vararg piping: ...(start) */
1433 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1437 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1439 parseerror(parser, "expected typename for vararg");
1443 typevar = parse_typename(parser, NULL, NULL, NULL);
1449 if (parser->tok != ')') {
1451 ast_delete(typevar);
1452 parseerror(parser, "expected closing paren");
1456 if (funtype->expression.varparam &&
1457 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1461 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1462 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1463 compile_error(ast_ctx(typevar),
1464 "function was declared to take varargs of type `%s`, requested type is: %s",
1468 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1469 ast_type_adopt(out, typevar);
1470 ast_delete(typevar);
1474 static ast_expression* parse_vararg(parser_t *parser)
1476 bool old_noops = parser->lex->flags.noops;
1478 ast_expression *out;
1480 parser->lex->flags.noops = true;
1481 out = parse_vararg_do(parser);
1483 parser->lex->flags.noops = old_noops;
1487 /* not to be exposed */
1488 bool ftepp_predef_exists(const char *name);
1489 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1491 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1492 parser->tok == TOKEN_IDENT &&
1493 !strcmp(parser_tokval(parser), "_"))
1495 /* a translatable string */
1498 parser->lex->flags.noops = true;
1499 if (!parser_next(parser) || parser->tok != '(') {
1500 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1503 parser->lex->flags.noops = false;
1504 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1505 parseerror(parser, "expected a constant string in translatable-string extension");
1508 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1511 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1513 if (!parser_next(parser) || parser->tok != ')') {
1514 parseerror(parser, "expected closing paren after translatable string");
1519 else if (parser->tok == TOKEN_DOTS)
1522 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1523 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1526 va = parse_vararg(parser);
1529 vec_push(sy->out, syexp(parser_ctx(parser), va));
1532 else if (parser->tok == TOKEN_FLOATCONST) {
1533 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f), false);
1536 vec_push(sy->out, syexp(parser_ctx(parser), val));
1539 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1540 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i), false);
1543 vec_push(sy->out, syexp(parser_ctx(parser), val));
1546 else if (parser->tok == TOKEN_STRINGCONST) {
1547 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1550 vec_push(sy->out, syexp(parser_ctx(parser), val));
1553 else if (parser->tok == TOKEN_VECTORCONST) {
1554 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1557 vec_push(sy->out, syexp(parser_ctx(parser), val));
1560 else if (parser->tok == TOKEN_IDENT)
1562 const char *ctoken = parser_tokval(parser);
1563 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1564 ast_expression *var;
1565 /* a_vector.{x,y,z} */
1566 if (!vec_size(sy->ops) ||
1567 !vec_last(sy->ops).etype ||
1568 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1570 /* When adding more intrinsics, fix the above condition */
1573 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1575 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1577 var = parser_find_var(parser, parser_tokval(parser));
1579 var = parser_find_field(parser, parser_tokval(parser));
1581 if (!var && with_labels) {
1582 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1584 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1585 var = (ast_expression*)lbl;
1586 parser->labels.push_back(lbl);
1589 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1590 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1593 * now we try for the real intrinsic hashtable. If the string
1594 * begins with __builtin, we simply skip past it, otherwise we
1595 * use the identifier as is.
1597 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1598 var = intrin_func(parser->intrin, parser_tokval(parser));
1602 * Try it again, intrin_func deals with the alias method as well
1603 * the first one masks for __builtin though, we emit warning here.
1606 if ((var = intrin_func(parser->intrin, parser_tokval(parser)))) {
1607 (void)!compile_warning(
1610 "using implicitly defined builtin `__builtin_%s' for `%s'",
1611 parser_tokval(parser),
1612 parser_tokval(parser)
1620 * sometimes people use preprocessing predefs without enabling them
1621 * i've done this thousands of times already myself. Lets check for
1622 * it in the predef table. And diagnose it better :)
1624 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1625 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1629 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1635 if (ast_istype(var, ast_value)) {
1636 ((ast_value*)var)->uses++;
1638 else if (ast_istype(var, ast_member)) {
1639 ast_member *mem = (ast_member*)var;
1640 if (ast_istype(mem->owner, ast_value))
1641 ((ast_value*)(mem->owner))->uses++;
1644 vec_push(sy->out, syexp(parser_ctx(parser), var));
1647 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1651 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1653 ast_expression *expr = NULL;
1656 bool wantop = false;
1657 /* only warn once about an assignment in a truth value because the current code
1658 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1660 bool warn_parenthesis = true;
1662 /* count the parens because an if starts with one, so the
1663 * end of a condition is an unmatched closing paren
1667 memset(&sy, 0, sizeof(sy));
1669 parser->lex->flags.noops = false;
1671 parser_reclassify_token(parser);
1675 if (parser->tok == TOKEN_TYPENAME) {
1676 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1680 if (parser->tok == TOKEN_OPERATOR)
1682 /* classify the operator */
1683 const oper_info *op;
1684 const oper_info *olast = NULL;
1686 for (o = 0; o < operator_count; ++o) {
1687 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1688 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1689 !strcmp(parser_tokval(parser), operators[o].op))
1694 if (o == operator_count) {
1695 compile_error(parser_ctx(parser), "unexpected operator: %s", parser_tokval(parser));
1698 /* found an operator */
1701 /* when declaring variables, a comma starts a new variable */
1702 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1703 /* fixup the token */
1708 /* a colon without a pervious question mark cannot be a ternary */
1709 if (!ternaries && op->id == opid2(':','?')) {
1714 if (op->id == opid1(',')) {
1715 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1716 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1720 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1721 olast = &operators[vec_last(sy.ops).etype-1];
1723 /* first only apply higher precedences, assoc_left+equal comes after we warn about precedence rules */
1724 while (olast && op->prec < olast->prec)
1726 if (!parser_sy_apply_operator(parser, &sy))
1728 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1729 olast = &operators[vec_last(sy.ops).etype-1];
1734 #define IsAssignOp(x) (\
1735 (x) == opid1('=') || \
1736 (x) == opid2('+','=') || \
1737 (x) == opid2('-','=') || \
1738 (x) == opid2('*','=') || \
1739 (x) == opid2('/','=') || \
1740 (x) == opid2('%','=') || \
1741 (x) == opid2('&','=') || \
1742 (x) == opid2('|','=') || \
1743 (x) == opid3('&','~','=') \
1745 if (warn_parenthesis) {
1746 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1747 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1748 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1751 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1752 warn_parenthesis = false;
1755 if (olast && olast->id != op->id) {
1756 if ((op->id == opid1('&') || op->id == opid1('|') || op->id == opid1('^')) &&
1757 (olast->id == opid1('&') || olast->id == opid1('|') || olast->id == opid1('^')))
1759 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around bitwise operations");
1760 warn_parenthesis = false;
1762 else if ((op->id == opid2('&','&') || op->id == opid2('|','|')) &&
1763 (olast->id == opid2('&','&') || olast->id == opid2('|','|')))
1765 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around logical operations");
1766 warn_parenthesis = false;
1772 (op->prec < olast->prec) ||
1773 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1775 if (!parser_sy_apply_operator(parser, &sy))
1777 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1778 olast = &operators[vec_last(sy.ops).etype-1];
1783 if (op->id == opid1('(')) {
1785 size_t sycount = vec_size(sy.out);
1786 /* we expected an operator, this is the function-call operator */
1787 vec_push(sy.paren, PAREN_FUNC);
1788 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1789 vec_push(sy.argc, 0);
1791 vec_push(sy.paren, PAREN_EXPR);
1792 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1795 } else if (op->id == opid1('[')) {
1797 parseerror(parser, "unexpected array subscript");
1800 vec_push(sy.paren, PAREN_INDEX);
1801 /* push both the operator and the paren, this makes life easier */
1802 vec_push(sy.ops, syop(parser_ctx(parser), op));
1803 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1805 } else if (op->id == opid2('?',':')) {
1806 vec_push(sy.ops, syop(parser_ctx(parser), op));
1807 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1810 vec_push(sy.paren, PAREN_TERNARY1);
1811 } else if (op->id == opid2(':','?')) {
1812 if (!vec_size(sy.paren)) {
1813 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1816 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1817 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1820 if (!parser_close_paren(parser, &sy))
1822 vec_push(sy.ops, syop(parser_ctx(parser), op));
1826 vec_push(sy.ops, syop(parser_ctx(parser), op));
1827 wantop = !!(op->flags & OP_SUFFIX);
1830 else if (parser->tok == ')') {
1831 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1832 if (!parser_sy_apply_operator(parser, &sy))
1835 if (!vec_size(sy.paren))
1838 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1839 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1842 if (!parser_close_paren(parser, &sy))
1845 /* must be a function call without parameters */
1846 if (vec_last(sy.paren) != PAREN_FUNC) {
1847 parseerror(parser, "closing paren in invalid position");
1850 if (!parser_close_paren(parser, &sy))
1855 else if (parser->tok == '(') {
1856 parseerror(parser, "internal error: '(' should be classified as operator");
1859 else if (parser->tok == '[') {
1860 parseerror(parser, "internal error: '[' should be classified as operator");
1863 else if (parser->tok == ']') {
1864 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1865 if (!parser_sy_apply_operator(parser, &sy))
1868 if (!vec_size(sy.paren))
1870 if (vec_last(sy.paren) != PAREN_INDEX) {
1871 parseerror(parser, "mismatched parentheses, unexpected ']'");
1874 if (!parser_close_paren(parser, &sy))
1879 if (!parse_sya_operand(parser, &sy, with_labels))
1884 /* in this case we might want to allow constant string concatenation */
1885 bool concatenated = false;
1886 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1887 ast_expression *lexpr = vec_last(sy.out).out;
1888 if (ast_istype(lexpr, ast_value)) {
1889 ast_value *last = (ast_value*)lexpr;
1890 if (last->isimm == true && last->cvq == CV_CONST &&
1891 last->hasvalue && last->expression.vtype == TYPE_STRING)
1893 char *newstr = NULL;
1894 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1895 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1897 concatenated = true;
1901 if (!concatenated) {
1902 parseerror(parser, "expected operator or end of statement");
1907 if (!parser_next(parser)) {
1910 if (parser->tok == ';' ||
1911 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1912 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1918 while (vec_size(sy.ops)) {
1919 if (!parser_sy_apply_operator(parser, &sy))
1923 parser->lex->flags.noops = true;
1924 if (vec_size(sy.out) != 1) {
1925 parseerror(parser, "expression expected");
1928 expr = sy.out[0].out;
1931 if (vec_size(sy.paren)) {
1932 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1940 parser->lex->flags.noops = true;
1941 for (i = 0; i < vec_size(sy.out); ++i) {
1943 ast_unref(sy.out[i].out);
1952 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1954 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1957 if (parser->tok != ';') {
1958 parseerror(parser, "semicolon expected after expression");
1962 if (!parser_next(parser)) {
1969 static void parser_enterblock(parser_t *parser)
1971 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1972 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1973 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1974 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1975 vec_push(parser->_block_ctx, parser_ctx(parser));
1978 static bool parser_leaveblock(parser_t *parser)
1981 size_t locals, typedefs;
1983 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1984 parseerror(parser, "internal error: parser_leaveblock with no block");
1988 util_htdel(vec_last(parser->variables));
1990 vec_pop(parser->variables);
1991 if (!vec_size(parser->_blocklocals)) {
1992 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1996 locals = vec_last(parser->_blocklocals);
1997 vec_pop(parser->_blocklocals);
1998 while (vec_size(parser->_locals) != locals) {
1999 ast_expression *e = vec_last(parser->_locals);
2000 ast_value *v = (ast_value*)e;
2001 vec_pop(parser->_locals);
2002 if (ast_istype(e, ast_value) && !v->uses) {
2003 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2008 typedefs = vec_last(parser->_blocktypedefs);
2009 while (vec_size(parser->_typedefs) != typedefs) {
2010 ast_delete(vec_last(parser->_typedefs));
2011 vec_pop(parser->_typedefs);
2013 util_htdel(vec_last(parser->typedefs));
2014 vec_pop(parser->typedefs);
2016 vec_pop(parser->_block_ctx);
2021 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2023 vec_push(parser->_locals, e);
2024 util_htset(vec_last(parser->variables), name, (void*)e);
2027 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2029 vec_push(parser->globals, e);
2030 util_htset(parser->htglobals, name, e);
2033 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2037 ast_expression *prev;
2039 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2041 ast_type_to_string(cond, ty, sizeof(ty));
2042 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2045 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2048 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2051 parseerror(parser, "internal error: failed to process condition");
2056 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2058 /* vector types need to be cast to true booleans */
2059 ast_binary *bin = (ast_binary*)cond;
2060 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2062 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2064 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2067 parseerror(parser, "internal error: failed to process condition");
2074 unary = (ast_unary*)cond;
2075 /* ast_istype dereferences cond, should test here for safety */
2076 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2078 cond = unary->operand;
2079 unary->operand = NULL;
2082 unary = (ast_unary*)cond;
2086 parseerror(parser, "internal error: failed to process condition");
2088 if (ifnot) *_ifnot = !*_ifnot;
2092 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2095 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2098 lex_ctx_t ctx = parser_ctx(parser);
2100 (void)block; /* not touching */
2102 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2103 if (!parser_next(parser)) {
2104 parseerror(parser, "expected condition or 'not'");
2107 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2109 if (!parser_next(parser)) {
2110 parseerror(parser, "expected condition in parenthesis");
2114 if (parser->tok != '(') {
2115 parseerror(parser, "expected 'if' condition in parenthesis");
2118 /* parse into the expression */
2119 if (!parser_next(parser)) {
2120 parseerror(parser, "expected 'if' condition after opening paren");
2123 /* parse the condition */
2124 cond = parse_expression_leave(parser, false, true, false);
2128 if (parser->tok != ')') {
2129 parseerror(parser, "expected closing paren after 'if' condition");
2133 /* parse into the 'then' branch */
2134 if (!parser_next(parser)) {
2135 parseerror(parser, "expected statement for on-true branch of 'if'");
2139 if (!parse_statement_or_block(parser, &ontrue)) {
2144 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2145 /* check for an else */
2146 if (!strcmp(parser_tokval(parser), "else")) {
2147 /* parse into the 'else' branch */
2148 if (!parser_next(parser)) {
2149 parseerror(parser, "expected on-false branch after 'else'");
2154 if (!parse_statement_or_block(parser, &onfalse)) {
2161 cond = process_condition(parser, cond, &ifnot);
2163 if (ontrue) ast_delete(ontrue);
2164 if (onfalse) ast_delete(onfalse);
2169 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2171 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2172 *out = (ast_expression*)ifthen;
2176 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2177 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2182 /* skip the 'while' and get the body */
2183 if (!parser_next(parser)) {
2184 if (OPTS_FLAG(LOOP_LABELS))
2185 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2187 parseerror(parser, "expected 'while' condition in parenthesis");
2191 if (parser->tok == ':') {
2192 if (!OPTS_FLAG(LOOP_LABELS))
2193 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2194 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2195 parseerror(parser, "expected loop label");
2198 label = util_strdup(parser_tokval(parser));
2199 if (!parser_next(parser)) {
2201 parseerror(parser, "expected 'while' condition in parenthesis");
2206 if (parser->tok != '(') {
2207 parseerror(parser, "expected 'while' condition in parenthesis");
2211 parser->breaks.push_back(label);
2212 parser->continues.push_back(label);
2214 rv = parse_while_go(parser, block, out);
2217 if (parser->breaks.back() != label || parser->continues.back() != label) {
2218 parseerror(parser, "internal error: label stack corrupted");
2224 parser->breaks.pop_back();
2225 parser->continues.pop_back();
2230 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2233 ast_expression *cond, *ontrue;
2237 lex_ctx_t ctx = parser_ctx(parser);
2239 (void)block; /* not touching */
2241 /* parse into the expression */
2242 if (!parser_next(parser)) {
2243 parseerror(parser, "expected 'while' condition after opening paren");
2246 /* parse the condition */
2247 cond = parse_expression_leave(parser, false, true, false);
2251 if (parser->tok != ')') {
2252 parseerror(parser, "expected closing paren after 'while' condition");
2256 /* parse into the 'then' branch */
2257 if (!parser_next(parser)) {
2258 parseerror(parser, "expected while-loop body");
2262 if (!parse_statement_or_block(parser, &ontrue)) {
2267 cond = process_condition(parser, cond, &ifnot);
2272 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2273 *out = (ast_expression*)aloop;
2277 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2278 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2283 /* skip the 'do' and get the body */
2284 if (!parser_next(parser)) {
2285 if (OPTS_FLAG(LOOP_LABELS))
2286 parseerror(parser, "expected loop label or body");
2288 parseerror(parser, "expected loop body");
2292 if (parser->tok == ':') {
2293 if (!OPTS_FLAG(LOOP_LABELS))
2294 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2295 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2296 parseerror(parser, "expected loop label");
2299 label = util_strdup(parser_tokval(parser));
2300 if (!parser_next(parser)) {
2302 parseerror(parser, "expected loop body");
2307 parser->breaks.push_back(label);
2308 parser->continues.push_back(label);
2310 rv = parse_dowhile_go(parser, block, out);
2313 if (parser->breaks.back() != label || parser->continues.back() != label) {
2314 parseerror(parser, "internal error: label stack corrupted");
2317 * Test for NULL otherwise ast_delete dereferences null pointer
2325 parser->breaks.pop_back();
2326 parser->continues.pop_back();
2331 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2334 ast_expression *cond, *ontrue;
2338 lex_ctx_t ctx = parser_ctx(parser);
2340 (void)block; /* not touching */
2342 if (!parse_statement_or_block(parser, &ontrue))
2345 /* expect the "while" */
2346 if (parser->tok != TOKEN_KEYWORD ||
2347 strcmp(parser_tokval(parser), "while"))
2349 parseerror(parser, "expected 'while' and condition");
2354 /* skip the 'while' and check for opening paren */
2355 if (!parser_next(parser) || parser->tok != '(') {
2356 parseerror(parser, "expected 'while' condition in parenthesis");
2360 /* parse into the expression */
2361 if (!parser_next(parser)) {
2362 parseerror(parser, "expected 'while' condition after opening paren");
2366 /* parse the condition */
2367 cond = parse_expression_leave(parser, false, true, false);
2371 if (parser->tok != ')') {
2372 parseerror(parser, "expected closing paren after 'while' condition");
2378 if (!parser_next(parser) || parser->tok != ';') {
2379 parseerror(parser, "expected semicolon after condition");
2385 if (!parser_next(parser)) {
2386 parseerror(parser, "parse error");
2392 cond = process_condition(parser, cond, &ifnot);
2397 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2398 *out = (ast_expression*)aloop;
2402 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2403 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2408 /* skip the 'for' and check for opening paren */
2409 if (!parser_next(parser)) {
2410 if (OPTS_FLAG(LOOP_LABELS))
2411 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2413 parseerror(parser, "expected 'for' expressions in parenthesis");
2417 if (parser->tok == ':') {
2418 if (!OPTS_FLAG(LOOP_LABELS))
2419 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2420 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2421 parseerror(parser, "expected loop label");
2424 label = util_strdup(parser_tokval(parser));
2425 if (!parser_next(parser)) {
2427 parseerror(parser, "expected 'for' expressions in parenthesis");
2432 if (parser->tok != '(') {
2433 parseerror(parser, "expected 'for' expressions in parenthesis");
2437 parser->breaks.push_back(label);
2438 parser->continues.push_back(label);
2440 rv = parse_for_go(parser, block, out);
2443 if (parser->breaks.back() != label || parser->continues.back() != label) {
2444 parseerror(parser, "internal error: label stack corrupted");
2450 parser->breaks.pop_back();
2451 parser->continues.pop_back();
2455 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2458 ast_expression *initexpr, *cond, *increment, *ontrue;
2463 lex_ctx_t ctx = parser_ctx(parser);
2465 parser_enterblock(parser);
2472 /* parse into the expression */
2473 if (!parser_next(parser)) {
2474 parseerror(parser, "expected 'for' initializer after opening paren");
2479 if (parser->tok == TOKEN_IDENT)
2480 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2482 if (typevar || parser->tok == TOKEN_TYPENAME) {
2483 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2486 else if (parser->tok != ';')
2488 initexpr = parse_expression_leave(parser, false, false, false);
2492 /* move on to condition */
2493 if (parser->tok != ';') {
2494 parseerror(parser, "expected semicolon after for-loop initializer");
2498 if (!parser_next(parser)) {
2499 parseerror(parser, "expected for-loop condition");
2504 /* parse the condition */
2505 if (parser->tok != ';') {
2506 cond = parse_expression_leave(parser, false, true, false);
2511 /* move on to incrementor */
2512 if (parser->tok != ';') {
2513 parseerror(parser, "expected semicolon after for-loop initializer");
2516 if (!parser_next(parser)) {
2517 parseerror(parser, "expected for-loop condition");
2521 /* parse the incrementor */
2522 if (parser->tok != ')') {
2523 lex_ctx_t condctx = parser_ctx(parser);
2524 increment = parse_expression_leave(parser, false, false, false);
2527 if (!ast_side_effects(increment)) {
2528 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2534 if (parser->tok != ')') {
2535 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2538 /* parse into the 'then' branch */
2539 if (!parser_next(parser)) {
2540 parseerror(parser, "expected for-loop body");
2543 if (!parse_statement_or_block(parser, &ontrue))
2547 cond = process_condition(parser, cond, &ifnot);
2551 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2552 *out = (ast_expression*)aloop;
2554 if (!parser_leaveblock(parser)) {
2560 if (initexpr) ast_unref(initexpr);
2561 if (cond) ast_unref(cond);
2562 if (increment) ast_unref(increment);
2563 (void)!parser_leaveblock(parser);
2567 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2569 ast_expression *exp = NULL;
2570 ast_expression *var = NULL;
2571 ast_return *ret = NULL;
2572 ast_value *retval = parser->function->return_value;
2573 ast_value *expected = parser->function->vtype;
2575 lex_ctx_t ctx = parser_ctx(parser);
2577 (void)block; /* not touching */
2579 if (!parser_next(parser)) {
2580 parseerror(parser, "expected return expression");
2584 /* return assignments */
2585 if (parser->tok == '=') {
2586 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2587 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2591 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2593 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2594 parseerror(parser, "invalid return type: `%s'", ty1);
2598 if (!parser_next(parser)) {
2599 parseerror(parser, "expected return assignment expression");
2603 if (!(exp = parse_expression_leave(parser, false, false, false)))
2606 /* prepare the return value */
2608 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2609 ast_type_adopt(retval, expected->expression.next);
2610 parser->function->return_value = retval;
2613 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2614 char ty1[1024], ty2[1024];
2615 ast_type_to_string(exp, ty1, sizeof(ty1));
2616 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2617 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2620 /* store to 'return' local variable */
2621 var = (ast_expression*)ast_store_new(
2623 type_store_instr[expected->expression.next->vtype],
2624 (ast_expression*)retval, exp);
2631 if (parser->tok != ';')
2632 parseerror(parser, "missing semicolon after return assignment");
2633 else if (!parser_next(parser))
2634 parseerror(parser, "parse error after return assignment");
2640 if (parser->tok != ';') {
2641 exp = parse_expression(parser, false, false);
2645 if (exp->vtype != TYPE_NIL &&
2646 exp->vtype != ((ast_expression*)expected)->next->vtype)
2648 parseerror(parser, "return with invalid expression");
2651 ret = ast_return_new(ctx, exp);
2657 if (!parser_next(parser))
2658 parseerror(parser, "parse error");
2660 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2662 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2664 ret = ast_return_new(ctx, (ast_expression*)retval);
2666 *out = (ast_expression*)ret;
2670 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2673 unsigned int levels = 0;
2674 lex_ctx_t ctx = parser_ctx(parser);
2675 auto &loops = (is_continue ? parser->continues : parser->breaks);
2677 (void)block; /* not touching */
2678 if (!parser_next(parser)) {
2679 parseerror(parser, "expected semicolon or loop label");
2683 if (loops.empty()) {
2685 parseerror(parser, "`continue` can only be used inside loops");
2687 parseerror(parser, "`break` can only be used inside loops or switches");
2690 if (parser->tok == TOKEN_IDENT) {
2691 if (!OPTS_FLAG(LOOP_LABELS))
2692 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2695 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2698 parseerror(parser, "no such loop to %s: `%s`",
2699 (is_continue ? "continue" : "break out of"),
2700 parser_tokval(parser));
2705 if (!parser_next(parser)) {
2706 parseerror(parser, "expected semicolon");
2711 if (parser->tok != ';') {
2712 parseerror(parser, "expected semicolon");
2716 if (!parser_next(parser))
2717 parseerror(parser, "parse error");
2719 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2723 /* returns true when it was a variable qualifier, false otherwise!
2724 * on error, cvq is set to CV_WRONG
2726 struct attribute_t {
2731 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2733 bool had_const = false;
2734 bool had_var = false;
2735 bool had_noref = false;
2736 bool had_attrib = false;
2737 bool had_static = false;
2740 static attribute_t attributes[] = {
2741 { "noreturn", AST_FLAG_NORETURN },
2742 { "inline", AST_FLAG_INLINE },
2743 { "eraseable", AST_FLAG_ERASEABLE },
2744 { "accumulate", AST_FLAG_ACCUMULATE },
2745 { "last", AST_FLAG_FINAL_DECL }
2752 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2754 /* parse an attribute */
2755 if (!parser_next(parser)) {
2756 parseerror(parser, "expected attribute after `[[`");
2761 for (i = 0; i < GMQCC_ARRAY_COUNT(attributes); i++) {
2762 if (!strcmp(parser_tokval(parser), attributes[i].name)) {
2763 flags |= attributes[i].flag;
2764 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2765 parseerror(parser, "`%s` attribute has no parameters, expected `]]`",
2766 attributes[i].name);
2774 if (i != GMQCC_ARRAY_COUNT(attributes))
2778 if (!strcmp(parser_tokval(parser), "noref")) {
2780 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2781 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2786 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2787 flags |= AST_FLAG_ALIAS;
2790 if (!parser_next(parser)) {
2791 parseerror(parser, "parse error in attribute");
2795 if (parser->tok == '(') {
2796 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2797 parseerror(parser, "`alias` attribute missing parameter");
2801 *message = util_strdup(parser_tokval(parser));
2803 if (!parser_next(parser)) {
2804 parseerror(parser, "parse error in attribute");
2808 if (parser->tok != ')') {
2809 parseerror(parser, "`alias` attribute expected `)` after parameter");
2813 if (!parser_next(parser)) {
2814 parseerror(parser, "parse error in attribute");
2819 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2820 parseerror(parser, "`alias` attribute expected `]]`");
2824 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2825 flags |= AST_FLAG_DEPRECATED;
2828 if (!parser_next(parser)) {
2829 parseerror(parser, "parse error in attribute");
2833 if (parser->tok == '(') {
2834 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2835 parseerror(parser, "`deprecated` attribute missing parameter");
2839 *message = util_strdup(parser_tokval(parser));
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "parse error in attribute");
2846 if(parser->tok != ')') {
2847 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2851 if (!parser_next(parser)) {
2852 parseerror(parser, "parse error in attribute");
2857 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2858 parseerror(parser, "`deprecated` attribute expected `]]`");
2861 if (*message) mem_d(*message);
2867 else if (!strcmp(parser_tokval(parser), "coverage") && !(flags & AST_FLAG_COVERAGE)) {
2868 flags |= AST_FLAG_COVERAGE;
2869 if (!parser_next(parser)) {
2871 parseerror(parser, "parse error in coverage attribute");
2875 if (parser->tok == '(') {
2876 if (!parser_next(parser)) {
2878 parseerror(parser, "invalid parameter for coverage() attribute\n"
2879 "valid are: block");
2883 if (parser->tok != ')') {
2885 if (parser->tok != TOKEN_IDENT)
2886 goto bad_coverage_arg;
2887 if (!strcmp(parser_tokval(parser), "block"))
2888 flags |= AST_FLAG_BLOCK_COVERAGE;
2889 else if (!strcmp(parser_tokval(parser), "none"))
2890 flags &= ~(AST_FLAG_COVERAGE_MASK);
2892 goto bad_coverage_arg;
2893 if (!parser_next(parser))
2894 goto error_in_coverage;
2895 if (parser->tok == ',') {
2896 if (!parser_next(parser))
2897 goto error_in_coverage;
2899 } while (parser->tok != ')');
2901 if (parser->tok != ')' || !parser_next(parser))
2902 goto error_in_coverage;
2904 /* without parameter [[coverage]] equals [[coverage(block)]] */
2905 flags |= AST_FLAG_BLOCK_COVERAGE;
2910 /* Skip tokens until we hit a ]] */
2911 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2912 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2913 if (!parser_next(parser)) {
2914 parseerror(parser, "error inside attribute");
2921 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2923 else if (!strcmp(parser_tokval(parser), "const"))
2925 else if (!strcmp(parser_tokval(parser), "var"))
2927 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2929 else if (!strcmp(parser_tokval(parser), "noref"))
2931 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2938 if (!parser_next(parser))
2948 *is_static = had_static;
2952 parseerror(parser, "parse error after variable qualifier");
2957 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2958 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2963 /* skip the 'while' and get the body */
2964 if (!parser_next(parser)) {
2965 if (OPTS_FLAG(LOOP_LABELS))
2966 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2968 parseerror(parser, "expected 'switch' operand in parenthesis");
2972 if (parser->tok == ':') {
2973 if (!OPTS_FLAG(LOOP_LABELS))
2974 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2975 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2976 parseerror(parser, "expected loop label");
2979 label = util_strdup(parser_tokval(parser));
2980 if (!parser_next(parser)) {
2982 parseerror(parser, "expected 'switch' operand in parenthesis");
2987 if (parser->tok != '(') {
2988 parseerror(parser, "expected 'switch' operand in parenthesis");
2992 parser->breaks.push_back(label);
2994 rv = parse_switch_go(parser, block, out);
2997 if (parser->breaks.back() != label) {
2998 parseerror(parser, "internal error: label stack corrupted");
3004 parser->breaks.pop_back();
3009 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3011 ast_expression *operand;
3014 ast_switch *switchnode;
3015 ast_switch_case swcase;
3018 bool noref, is_static;
3019 uint32_t qflags = 0;
3021 lex_ctx_t ctx = parser_ctx(parser);
3023 (void)block; /* not touching */
3026 /* parse into the expression */
3027 if (!parser_next(parser)) {
3028 parseerror(parser, "expected switch operand");
3031 /* parse the operand */
3032 operand = parse_expression_leave(parser, false, false, false);
3036 switchnode = ast_switch_new(ctx, operand);
3039 if (parser->tok != ')') {
3040 ast_delete(switchnode);
3041 parseerror(parser, "expected closing paren after 'switch' operand");
3045 /* parse over the opening paren */
3046 if (!parser_next(parser) || parser->tok != '{') {
3047 ast_delete(switchnode);
3048 parseerror(parser, "expected list of cases");
3052 if (!parser_next(parser)) {
3053 ast_delete(switchnode);
3054 parseerror(parser, "expected 'case' or 'default'");
3058 /* new block; allow some variables to be declared here */
3059 parser_enterblock(parser);
3062 if (parser->tok == TOKEN_IDENT)
3063 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3064 if (typevar || parser->tok == TOKEN_TYPENAME) {
3065 if (!parse_variable(parser, block, true, CV_NONE, typevar, false, false, 0, NULL)) {
3066 ast_delete(switchnode);
3071 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3073 if (cvq == CV_WRONG) {
3074 ast_delete(switchnode);
3077 if (!parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, NULL)) {
3078 ast_delete(switchnode);
3087 while (parser->tok != '}') {
3088 ast_block *caseblock;
3090 if (!strcmp(parser_tokval(parser), "case")) {
3091 if (!parser_next(parser)) {
3092 ast_delete(switchnode);
3093 parseerror(parser, "expected expression for case");
3096 swcase.value = parse_expression_leave(parser, false, false, false);
3097 if (!swcase.value) {
3098 ast_delete(switchnode);
3099 parseerror(parser, "expected expression for case");
3102 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3103 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3104 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3110 else if (!strcmp(parser_tokval(parser), "default")) {
3111 swcase.value = NULL;
3112 if (!parser_next(parser)) {
3113 ast_delete(switchnode);
3114 parseerror(parser, "expected colon");
3119 ast_delete(switchnode);
3120 parseerror(parser, "expected 'case' or 'default'");
3124 /* Now the colon and body */
3125 if (parser->tok != ':') {
3126 if (swcase.value) ast_unref(swcase.value);
3127 ast_delete(switchnode);
3128 parseerror(parser, "expected colon");
3132 if (!parser_next(parser)) {
3133 if (swcase.value) ast_unref(swcase.value);
3134 ast_delete(switchnode);
3135 parseerror(parser, "expected statements or case");
3138 caseblock = ast_block_new(parser_ctx(parser));
3140 if (swcase.value) ast_unref(swcase.value);
3141 ast_delete(switchnode);
3144 swcase.code = (ast_expression*)caseblock;
3145 vec_push(switchnode->cases, swcase);
3147 ast_expression *expr;
3148 if (parser->tok == '}')
3150 if (parser->tok == TOKEN_KEYWORD) {
3151 if (!strcmp(parser_tokval(parser), "case") ||
3152 !strcmp(parser_tokval(parser), "default"))
3157 if (!parse_statement(parser, caseblock, &expr, true)) {
3158 ast_delete(switchnode);
3163 if (!ast_block_add_expr(caseblock, expr)) {
3164 ast_delete(switchnode);
3170 parser_leaveblock(parser);
3173 if (parser->tok != '}') {
3174 ast_delete(switchnode);
3175 parseerror(parser, "expected closing paren of case list");
3178 if (!parser_next(parser)) {
3179 ast_delete(switchnode);
3180 parseerror(parser, "parse error after switch");
3183 *out = (ast_expression*)switchnode;
3187 /* parse computed goto sides */
3188 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3189 ast_expression *on_true;
3190 ast_expression *on_false;
3191 ast_expression *cond;
3196 if (ast_istype(*side, ast_ternary)) {
3197 ast_ternary *tern = (ast_ternary*)*side;
3198 on_true = parse_goto_computed(parser, &tern->on_true);
3199 on_false = parse_goto_computed(parser, &tern->on_false);
3201 if (!on_true || !on_false) {
3202 parseerror(parser, "expected label or expression in ternary");
3203 if (on_true) ast_unref(on_true);
3204 if (on_false) ast_unref(on_false);
3212 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3213 } else if (ast_istype(*side, ast_label)) {
3214 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3215 ast_goto_set_label(gt, ((ast_label*)*side));
3217 return (ast_expression*)gt;
3222 static bool parse_goto(parser_t *parser, ast_expression **out)
3224 ast_goto *gt = NULL;
3225 ast_expression *lbl;
3227 if (!parser_next(parser))
3230 if (parser->tok != TOKEN_IDENT) {
3231 ast_expression *expression;
3233 /* could be an expression i.e computed goto :-) */
3234 if (parser->tok != '(') {
3235 parseerror(parser, "expected label name after `goto`");
3239 /* failed to parse expression for goto */
3240 if (!(expression = parse_expression(parser, false, true)) ||
3241 !(*out = parse_goto_computed(parser, &expression))) {
3242 parseerror(parser, "invalid goto expression");
3244 ast_unref(expression);
3251 /* not computed goto */
3252 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3253 lbl = parser_find_label(parser, gt->name);
3255 if (!ast_istype(lbl, ast_label)) {
3256 parseerror(parser, "internal error: label is not an ast_label");
3260 ast_goto_set_label(gt, (ast_label*)lbl);
3263 parser->gotos.push_back(gt);
3265 if (!parser_next(parser) || parser->tok != ';') {
3266 parseerror(parser, "semicolon expected after goto label");
3269 if (!parser_next(parser)) {
3270 parseerror(parser, "parse error after goto");
3274 *out = (ast_expression*)gt;
3278 static bool parse_skipwhite(parser_t *parser)
3281 if (!parser_next(parser))
3283 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3284 return parser->tok < TOKEN_ERROR;
3287 static bool parse_eol(parser_t *parser)
3289 if (!parse_skipwhite(parser))
3291 return parser->tok == TOKEN_EOL;
3294 static bool parse_pragma_do(parser_t *parser)
3296 if (!parser_next(parser) ||
3297 parser->tok != TOKEN_IDENT ||
3298 strcmp(parser_tokval(parser), "pragma"))
3300 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3303 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3304 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3308 if (!strcmp(parser_tokval(parser), "noref")) {
3309 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3310 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3313 parser->noref = !!parser_token(parser)->constval.i;
3314 if (!parse_eol(parser)) {
3315 parseerror(parser, "parse error after `noref` pragma");
3321 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3324 while (!parse_eol(parser)) {
3325 parser_next(parser);
3334 static bool parse_pragma(parser_t *parser)
3337 parser->lex->flags.preprocessing = true;
3338 parser->lex->flags.mergelines = true;
3339 rv = parse_pragma_do(parser);
3340 if (parser->tok != TOKEN_EOL) {
3341 parseerror(parser, "junk after pragma");
3344 parser->lex->flags.preprocessing = false;
3345 parser->lex->flags.mergelines = false;
3346 if (!parser_next(parser)) {
3347 parseerror(parser, "parse error after pragma");
3353 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3355 bool noref, is_static;
3357 uint32_t qflags = 0;
3358 ast_value *typevar = NULL;
3359 char *vstring = NULL;
3363 if (parser->tok == TOKEN_IDENT)
3364 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3366 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
3368 /* local variable */
3370 parseerror(parser, "cannot declare a variable from here");
3373 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3374 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3377 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3381 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3383 if (cvq == CV_WRONG)
3385 return parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, vstring);
3387 else if (parser->tok == TOKEN_KEYWORD)
3389 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3394 if (!parser_next(parser)) {
3395 parseerror(parser, "parse error after __builtin_debug_printtype");
3399 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3401 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3402 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3403 if (!parser_next(parser)) {
3404 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3410 if (!parse_statement(parser, block, out, allow_cases))
3413 con_out("__builtin_debug_printtype: got no output node\n");
3416 ast_type_to_string(*out, ty, sizeof(ty));
3417 con_out("__builtin_debug_printtype: `%s`\n", ty);
3422 else if (!strcmp(parser_tokval(parser), "return"))
3424 return parse_return(parser, block, out);
3426 else if (!strcmp(parser_tokval(parser), "if"))
3428 return parse_if(parser, block, out);
3430 else if (!strcmp(parser_tokval(parser), "while"))
3432 return parse_while(parser, block, out);
3434 else if (!strcmp(parser_tokval(parser), "do"))
3436 return parse_dowhile(parser, block, out);
3438 else if (!strcmp(parser_tokval(parser), "for"))
3440 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3441 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3444 return parse_for(parser, block, out);
3446 else if (!strcmp(parser_tokval(parser), "break"))
3448 return parse_break_continue(parser, block, out, false);
3450 else if (!strcmp(parser_tokval(parser), "continue"))
3452 return parse_break_continue(parser, block, out, true);
3454 else if (!strcmp(parser_tokval(parser), "switch"))
3456 return parse_switch(parser, block, out);
3458 else if (!strcmp(parser_tokval(parser), "case") ||
3459 !strcmp(parser_tokval(parser), "default"))
3462 parseerror(parser, "unexpected 'case' label");
3467 else if (!strcmp(parser_tokval(parser), "goto"))
3469 return parse_goto(parser, out);
3471 else if (!strcmp(parser_tokval(parser), "typedef"))
3473 if (!parser_next(parser)) {
3474 parseerror(parser, "expected type definition after 'typedef'");
3477 return parse_typedef(parser);
3479 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3482 else if (parser->tok == '{')
3485 inner = parse_block(parser);
3488 *out = (ast_expression*)inner;
3491 else if (parser->tok == ':')
3495 if (!parser_next(parser)) {
3496 parseerror(parser, "expected label name");
3499 if (parser->tok != TOKEN_IDENT) {
3500 parseerror(parser, "label must be an identifier");
3503 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3505 if (!label->undefined) {
3506 parseerror(parser, "label `%s` already defined", label->name);
3509 label->undefined = false;
3512 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3513 parser->labels.push_back(label);
3515 *out = (ast_expression*)label;
3516 if (!parser_next(parser)) {
3517 parseerror(parser, "parse error after label");
3520 for (i = 0; i < parser->gotos.size(); ++i) {
3521 if (!strcmp(parser->gotos[i]->name, label->name)) {
3522 ast_goto_set_label(parser->gotos[i], label);
3523 parser->gotos.erase(parser->gotos.begin() + i);
3529 else if (parser->tok == ';')
3531 if (!parser_next(parser)) {
3532 parseerror(parser, "parse error after empty statement");
3539 lex_ctx_t ctx = parser_ctx(parser);
3540 ast_expression *exp = parse_expression(parser, false, false);
3544 if (!ast_side_effects(exp)) {
3545 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3552 static bool parse_enum(parser_t *parser)
3555 bool reverse = false;
3557 ast_value **values = NULL;
3558 ast_value *var = NULL;
3561 ast_expression *old;
3563 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3564 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3568 /* enumeration attributes (can add more later) */
3569 if (parser->tok == ':') {
3570 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3571 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3576 if (!strcmp(parser_tokval(parser), "flag")) {
3580 else if (!strcmp(parser_tokval(parser), "reverse")) {
3584 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3588 if (!parser_next(parser) || parser->tok != '{') {
3589 parseerror(parser, "expected `{` after enum attribute ");
3595 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3596 if (parser->tok == '}') {
3597 /* allow an empty enum */
3600 parseerror(parser, "expected identifier or `}`");
3604 old = parser_find_field(parser, parser_tokval(parser));
3606 old = parser_find_global(parser, parser_tokval(parser));
3608 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3609 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3613 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3614 vec_push(values, var);
3615 var->cvq = CV_CONST;
3616 var->hasvalue = true;
3618 /* for flagged enumerations increment in POTs of TWO */
3619 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3620 parser_addglobal(parser, var->name, (ast_expression*)var);
3622 if (!parser_next(parser)) {
3623 parseerror(parser, "expected `=`, `}` or comma after identifier");
3627 if (parser->tok == ',')
3629 if (parser->tok == '}')
3631 if (parser->tok != '=') {
3632 parseerror(parser, "expected `=`, `}` or comma after identifier");
3636 if (!parser_next(parser)) {
3637 parseerror(parser, "expected expression after `=`");
3641 /* We got a value! */
3642 old = parse_expression_leave(parser, true, false, false);
3643 asvalue = (ast_value*)old;
3644 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3645 compile_error(ast_ctx(var), "constant value or expression expected");
3648 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3650 if (parser->tok == '}')
3652 if (parser->tok != ',') {
3653 parseerror(parser, "expected `}` or comma after expression");
3658 /* patch them all (for reversed attribute) */
3661 for (i = 0; i < vec_size(values); i++)
3662 values[i]->constval.vfloat = vec_size(values) - i - 1;
3665 if (parser->tok != '}') {
3666 parseerror(parser, "internal error: breaking without `}`");
3670 if (!parser_next(parser) || parser->tok != ';') {
3671 parseerror(parser, "expected semicolon after enumeration");
3675 if (!parser_next(parser)) {
3676 parseerror(parser, "parse error after enumeration");
3688 static bool parse_block_into(parser_t *parser, ast_block *block)
3692 parser_enterblock(parser);
3694 if (!parser_next(parser)) { /* skip the '{' */
3695 parseerror(parser, "expected function body");
3699 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3701 ast_expression *expr = NULL;
3702 if (parser->tok == '}')
3705 if (!parse_statement(parser, block, &expr, false)) {
3706 /* parseerror(parser, "parse error"); */
3712 if (!ast_block_add_expr(block, expr)) {
3719 if (parser->tok != '}') {
3722 (void)parser_next(parser);
3726 if (!parser_leaveblock(parser))
3728 return retval && !!block;
3731 static ast_block* parse_block(parser_t *parser)
3734 block = ast_block_new(parser_ctx(parser));
3737 if (!parse_block_into(parser, block)) {
3738 ast_block_delete(block);
3744 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3746 if (parser->tok == '{') {
3747 *out = (ast_expression*)parse_block(parser);
3750 return parse_statement(parser, NULL, out, false);
3753 static bool create_vector_members(ast_value *var, ast_member **me)
3756 size_t len = strlen(var->name);
3758 for (i = 0; i < 3; ++i) {
3759 char *name = (char*)mem_a(len+3);
3760 memcpy(name, var->name, len);
3762 name[len+1] = 'x'+i;
3764 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3773 do { ast_member_delete(me[--i]); } while(i);
3777 static bool parse_function_body(parser_t *parser, ast_value *var)
3779 ast_block *block = NULL;
3783 ast_expression *framenum = NULL;
3784 ast_expression *nextthink = NULL;
3785 /* None of the following have to be deleted */
3786 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3787 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3788 bool has_frame_think;
3792 has_frame_think = false;
3793 old = parser->function;
3795 if (var->expression.flags & AST_FLAG_ALIAS) {
3796 parseerror(parser, "function aliases cannot have bodies");
3800 if (parser->gotos.size() || parser->labels.size()) {
3801 parseerror(parser, "gotos/labels leaking");
3805 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3806 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3807 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3813 if (parser->tok == '[') {
3814 /* got a frame definition: [ framenum, nextthink ]
3815 * this translates to:
3816 * self.frame = framenum;
3817 * self.nextthink = time + 0.1;
3818 * self.think = nextthink;
3822 fld_think = parser_find_field(parser, "think");
3823 fld_nextthink = parser_find_field(parser, "nextthink");
3824 fld_frame = parser_find_field(parser, "frame");
3825 if (!fld_think || !fld_nextthink || !fld_frame) {
3826 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3827 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3830 gbl_time = parser_find_global(parser, "time");
3831 gbl_self = parser_find_global(parser, "self");
3832 if (!gbl_time || !gbl_self) {
3833 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3834 parseerror(parser, "please declare the following globals: `time`, `self`");
3838 if (!parser_next(parser))
3841 framenum = parse_expression_leave(parser, true, false, false);
3843 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3846 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3847 ast_unref(framenum);
3848 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3852 if (parser->tok != ',') {
3853 ast_unref(framenum);
3854 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3855 parseerror(parser, "Got a %i\n", parser->tok);
3859 if (!parser_next(parser)) {
3860 ast_unref(framenum);
3864 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3866 /* qc allows the use of not-yet-declared functions here
3867 * - this automatically creates a prototype */
3868 ast_value *thinkfunc;
3869 ast_expression *functype = fld_think->next;
3871 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3872 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3873 ast_unref(framenum);
3874 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3877 ast_type_adopt(thinkfunc, functype);
3879 if (!parser_next(parser)) {
3880 ast_unref(framenum);
3881 ast_delete(thinkfunc);
3885 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3887 nextthink = (ast_expression*)thinkfunc;
3890 nextthink = parse_expression_leave(parser, true, false, false);
3892 ast_unref(framenum);
3893 parseerror(parser, "expected a think-function in [frame,think] notation");
3898 if (!ast_istype(nextthink, ast_value)) {
3899 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3903 if (retval && parser->tok != ']') {
3904 parseerror(parser, "expected closing `]` for [frame,think] notation");
3908 if (retval && !parser_next(parser)) {
3912 if (retval && parser->tok != '{') {
3913 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3918 ast_unref(nextthink);
3919 ast_unref(framenum);
3923 has_frame_think = true;
3926 block = ast_block_new(parser_ctx(parser));
3928 parseerror(parser, "failed to allocate block");
3929 if (has_frame_think) {
3930 ast_unref(nextthink);
3931 ast_unref(framenum);
3936 if (has_frame_think) {
3937 if (!OPTS_FLAG(EMULATE_STATE)) {
3938 ast_state *state_op = ast_state_new(parser_ctx(parser), framenum, nextthink);
3939 if (!ast_block_add_expr(block, (ast_expression*)state_op)) {
3940 parseerror(parser, "failed to generate state op for [frame,think]");
3941 ast_unref(nextthink);
3942 ast_unref(framenum);
3947 /* emulate OP_STATE in code: */
3949 ast_expression *self_frame;
3950 ast_expression *self_nextthink;
3951 ast_expression *self_think;
3952 ast_expression *time_plus_1;
3953 ast_store *store_frame;
3954 ast_store *store_nextthink;
3955 ast_store *store_think;
3957 float frame_delta = 1.0f / (float)OPTS_OPTION_U32(OPTION_STATE_FPS);
3959 ctx = parser_ctx(parser);
3960 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3961 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3962 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3964 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3965 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, frame_delta, false));
3967 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3968 if (self_frame) ast_delete(self_frame);
3969 if (self_nextthink) ast_delete(self_nextthink);
3970 if (self_think) ast_delete(self_think);
3971 if (time_plus_1) ast_delete(time_plus_1);
3977 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3978 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3979 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3982 ast_delete(self_frame);
3985 if (!store_nextthink) {
3986 ast_delete(self_nextthink);
3990 ast_delete(self_think);
3994 if (store_frame) ast_delete(store_frame);
3995 if (store_nextthink) ast_delete(store_nextthink);
3996 if (store_think) ast_delete(store_think);
3999 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4000 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4001 !ast_block_add_expr(block, (ast_expression*)store_think))
4008 parseerror(parser, "failed to generate code for [frame,think]");
4009 ast_unref(nextthink);
4010 ast_unref(framenum);
4017 if (var->hasvalue) {
4018 if (!(var->expression.flags & AST_FLAG_ACCUMULATE)) {
4019 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4020 ast_block_delete(block);
4023 func = var->constval.vfunc;
4026 parseerror(parser, "internal error: NULL function: `%s`", var->name);
4027 ast_block_delete(block);
4031 func = ast_function_new(ast_ctx(var), var->name, var);
4034 parseerror(parser, "failed to allocate function for `%s`", var->name);
4035 ast_block_delete(block);
4038 vec_push(parser->functions, func);
4041 parser_enterblock(parser);
4043 for (auto &it : var->expression.params) {
4047 if (it->expression.vtype != TYPE_VECTOR &&
4048 (it->expression.vtype != TYPE_FIELD ||
4049 it->expression.next->vtype != TYPE_VECTOR))
4054 if (!create_vector_members(it, me)) {
4055 ast_block_delete(block);
4059 for (e = 0; e < 3; ++e) {
4060 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4061 ast_block_collect(block, (ast_expression*)me[e]);
4065 if (var->argcounter && !func->argc) {
4066 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4067 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4071 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC && !func->varargs) {
4073 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4074 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4075 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4076 varargs->expression.count = 0;
4077 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4078 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4079 ast_delete(varargs);
4080 ast_block_delete(block);
4083 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4084 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4085 ast_delete(varargs);
4086 ast_block_delete(block);
4089 func->varargs = varargs;
4090 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, var->expression.params.size(), false);
4093 parser->function = func;
4094 if (!parse_block_into(parser, block)) {
4095 ast_block_delete(block);
4099 vec_push(func->blocks, block);
4101 parser->function = old;
4102 if (!parser_leaveblock(parser))
4104 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4105 parseerror(parser, "internal error: local scopes left");
4109 if (parser->tok == ';')
4110 return parser_next(parser);
4111 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4112 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4116 (void)!parser_leaveblock(parser);
4117 vec_pop(parser->functions);
4118 ast_function_delete(func);
4119 var->constval.vfunc = NULL;
4122 parser->function = old;
4126 static ast_expression *array_accessor_split(
4131 ast_expression *left,
4132 ast_expression *right
4138 lex_ctx_t ctx = ast_ctx(array);
4140 if (!left || !right) {
4141 if (left) ast_delete(left);
4142 if (right) ast_delete(right);
4146 cmp = ast_binary_new(ctx, INSTR_LT,
4147 (ast_expression*)index,
4148 (ast_expression*)fold_constgen_float(parser->fold, middle, false));
4152 parseerror(parser, "internal error: failed to create comparison for array setter");
4156 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4158 ast_delete(cmp); /* will delete left and right */
4159 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4163 return (ast_expression*)ifthen;
4166 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4168 lex_ctx_t ctx = ast_ctx(array);
4170 if (from+1 == afterend) {
4171 /* set this value */
4174 ast_array_index *subscript;
4176 int assignop = type_store_instr[value->expression.vtype];
4178 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4179 assignop = INSTR_STORE_V;
4181 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4185 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4187 ast_delete(subscript);
4191 block = ast_block_new(ctx);
4197 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4202 ret = ast_return_new(ctx, NULL);
4208 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4213 return (ast_expression*)block;
4215 ast_expression *left, *right;
4216 size_t diff = afterend - from;
4217 size_t middle = from + diff/2;
4218 left = array_setter_node(parser, array, index, value, from, middle);
4219 right = array_setter_node(parser, array, index, value, middle, afterend);
4220 return array_accessor_split(parser, array, index, middle, left, right);
4224 static ast_expression *array_field_setter_node(
4233 lex_ctx_t ctx = ast_ctx(array);
4235 if (from+1 == afterend) {
4236 /* set this value */
4239 ast_entfield *entfield;
4240 ast_array_index *subscript;
4242 int assignop = type_storep_instr[value->expression.vtype];
4244 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4245 assignop = INSTR_STOREP_V;
4247 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4251 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4252 subscript->expression.vtype = TYPE_FIELD;
4254 entfield = ast_entfield_new_force(ctx,
4255 (ast_expression*)entity,
4256 (ast_expression*)subscript,
4257 (ast_expression*)subscript);
4259 ast_delete(subscript);
4263 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4265 ast_delete(entfield);
4269 block = ast_block_new(ctx);
4275 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4280 ret = ast_return_new(ctx, NULL);
4286 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4291 return (ast_expression*)block;
4293 ast_expression *left, *right;
4294 size_t diff = afterend - from;
4295 size_t middle = from + diff/2;
4296 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4297 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4298 return array_accessor_split(parser, array, index, middle, left, right);
4302 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4304 lex_ctx_t ctx = ast_ctx(array);
4306 if (from+1 == afterend) {
4308 ast_array_index *subscript;
4310 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from, false));
4314 ret = ast_return_new(ctx, (ast_expression*)subscript);
4316 ast_delete(subscript);
4320 return (ast_expression*)ret;
4322 ast_expression *left, *right;
4323 size_t diff = afterend - from;
4324 size_t middle = from + diff/2;
4325 left = array_getter_node(parser, array, index, from, middle);
4326 right = array_getter_node(parser, array, index, middle, afterend);
4327 return array_accessor_split(parser, array, index, middle, left, right);
4331 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4333 ast_function *func = NULL;
4334 ast_value *fval = NULL;
4335 ast_block *body = NULL;
4337 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4339 parseerror(parser, "failed to create accessor function value");
4342 fval->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
4344 func = ast_function_new(ast_ctx(array), funcname, fval);
4347 parseerror(parser, "failed to create accessor function node");
4351 body = ast_block_new(ast_ctx(array));
4353 parseerror(parser, "failed to create block for array accessor");
4359 vec_push(func->blocks, body);
4362 vec_push(parser->accessors, fval);
4367 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4369 ast_value *index = NULL;
4370 ast_value *value = NULL;
4374 if (!ast_istype(array->expression.next, ast_value)) {
4375 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4379 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4381 func = fval->constval.vfunc;
4382 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4384 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4385 value = ast_value_copy((ast_value*)array->expression.next);
4387 if (!index || !value) {
4388 parseerror(parser, "failed to create locals for array accessor");
4391 (void)!ast_value_set_name(value, "value"); /* not important */
4392 fval->expression.params.push_back(index);
4393 fval->expression.params.push_back(value);
4395 array->setter = fval;
4398 if (index) ast_delete(index);
4399 if (value) ast_delete(value);
4405 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4407 ast_expression *root = NULL;
4408 root = array_setter_node(parser, array,
4409 array->setter->expression.params[0],
4410 array->setter->expression.params[1],
4411 0, array->expression.count);
4413 parseerror(parser, "failed to build accessor search tree");
4416 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4423 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4425 if (!parser_create_array_setter_proto(parser, array, funcname))
4427 return parser_create_array_setter_impl(parser, array);
4430 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4432 ast_expression *root = NULL;
4433 ast_value *entity = NULL;
4434 ast_value *index = NULL;
4435 ast_value *value = NULL;
4439 if (!ast_istype(array->expression.next, ast_value)) {
4440 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4444 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4446 func = fval->constval.vfunc;
4447 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4449 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4450 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4451 value = ast_value_copy((ast_value*)array->expression.next);
4452 if (!entity || !index || !value) {
4453 parseerror(parser, "failed to create locals for array accessor");
4456 (void)!ast_value_set_name(value, "value"); /* not important */
4457 fval->expression.params.push_back(entity);
4458 fval->expression.params.push_back(index);
4459 fval->expression.params.push_back(value);
4461 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4463 parseerror(parser, "failed to build accessor search tree");
4467 array->setter = fval;
4468 return ast_block_add_expr(func->blocks[0], root);
4470 if (entity) ast_delete(entity);
4471 if (index) ast_delete(index);
4472 if (value) ast_delete(value);
4473 if (root) ast_delete(root);
4479 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4481 ast_value *index = NULL;
4485 /* NOTE: checking array->expression.next rather than elemtype since
4486 * for fields elemtype is a temporary fieldtype.
4488 if (!ast_istype(array->expression.next, ast_value)) {
4489 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4493 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4495 func = fval->constval.vfunc;
4496 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4498 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4501 parseerror(parser, "failed to create locals for array accessor");
4504 fval->expression.params.push_back(index);
4506 array->getter = fval;
4509 if (index) ast_delete(index);
4515 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4517 ast_expression *root = NULL;
4519 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4521 parseerror(parser, "failed to build accessor search tree");
4524 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4531 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4533 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4535 return parser_create_array_getter_impl(parser, array);
4538 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4540 lex_ctx_t ctx = parser_ctx(parser);
4541 std::vector<ast_value *> params;
4544 bool variadic = false;
4545 ast_value *varparam = NULL;
4546 char *argcounter = NULL;
4548 /* for the sake of less code we parse-in in this function */
4549 if (!parser_next(parser)) {
4551 parseerror(parser, "expected parameter list");
4555 /* parse variables until we hit a closing paren */
4556 while (parser->tok != ')') {
4557 bool is_varargs = false;
4560 /* there must be commas between them */
4561 if (parser->tok != ',') {
4562 parseerror(parser, "expected comma or end of parameter list");
4565 if (!parser_next(parser)) {
4566 parseerror(parser, "expected parameter");
4572 ast_value *param = parse_typename(parser, NULL, NULL, &is_varargs);
4573 if (!param && !is_varargs)
4576 /* '...' indicates a varargs function */
4578 if (parser->tok != ')' && parser->tok != TOKEN_IDENT) {
4579 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4582 if (parser->tok == TOKEN_IDENT) {
4583 argcounter = util_strdup(parser_tokval(parser));
4584 if (!parser_next(parser) || parser->tok != ')') {
4585 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4590 params.push_back(param);
4591 if (param->expression.vtype >= TYPE_VARIANT) {
4592 char tname[1024]; /* typename is reserved in C++ */
4593 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4594 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4597 /* type-restricted varargs */
4598 if (parser->tok == TOKEN_DOTS) {
4600 varparam = params.back();
4602 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4603 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4606 if (parser->tok == TOKEN_IDENT) {
4607 argcounter = util_strdup(parser_tokval(parser));
4608 ast_value_set_name(param, argcounter);
4609 if (!parser_next(parser) || parser->tok != ')') {
4610 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4615 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC && param->name[0] == '<') {
4616 parseerror(parser, "parameter name omitted");
4622 if (params.size() == 1 && params[0]->expression.vtype == TYPE_VOID)
4626 if (params.size() > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4627 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4630 if (!parser_next(parser)) {
4631 parseerror(parser, "parse error after typename");
4635 /* now turn 'var' into a function type */
4636 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4637 fval->expression.next = (ast_expression*)var;
4639 fval->expression.flags |= AST_FLAG_VARIADIC;
4642 var->expression.params = params;
4643 var->expression.varparam = (ast_expression*)varparam;
4644 var->argcounter = argcounter;
4652 ast_delete(varparam);
4654 for (auto &it : params)
4659 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4661 ast_expression *cexp;
4662 ast_value *cval, *tmp;
4665 ctx = parser_ctx(parser);
4667 if (!parser_next(parser)) {
4669 parseerror(parser, "expected array-size");
4673 if (parser->tok != ']') {
4674 cexp = parse_expression_leave(parser, true, false, false);
4676 if (!cexp || !ast_istype(cexp, ast_value)) {
4680 parseerror(parser, "expected array-size as constant positive integer");
4683 cval = (ast_value*)cexp;
4690 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4691 tmp->expression.next = (ast_expression*)var;
4695 if (cval->expression.vtype == TYPE_INTEGER)
4696 tmp->expression.count = cval->constval.vint;
4697 else if (cval->expression.vtype == TYPE_FLOAT)
4698 tmp->expression.count = cval->constval.vfloat;
4702 parseerror(parser, "array-size must be a positive integer constant");
4708 var->expression.count = -1;
4709 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4712 if (parser->tok != ']') {
4714 parseerror(parser, "expected ']' after array-size");
4717 if (!parser_next(parser)) {
4719 parseerror(parser, "error after parsing array size");
4725 /* Parse a complete typename.
4726 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4727 * but when parsing variables separated by comma
4728 * 'storebase' should point to where the base-type should be kept.
4729 * The base type makes up every bit of type information which comes *before* the
4732 * NOTE: The value must either be named, have a NULL name, or a name starting
4733 * with '<'. In the first case, this will be the actual variable or type
4734 * name, in the other cases it is assumed that the name will appear
4735 * later, and an error is generated otherwise.
4737 * The following will be parsed in its entirety:
4739 * The 'basetype' in this case is 'void()'
4740 * and if there's a comma after it, say:
4742 * then the type-information 'void()' can be stored in 'storebase'
4744 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef, bool *is_vararg)
4746 ast_value *var, *tmp;
4749 const char *name = NULL;
4750 bool isfield = false;
4751 bool wasarray = false;
4752 size_t morefields = 0;
4754 bool vararg = (parser->tok == TOKEN_DOTS);
4756 ctx = parser_ctx(parser);
4758 /* types may start with a dot */
4759 if (parser->tok == '.' || parser->tok == TOKEN_DOTS) {
4761 if (parser->tok == TOKEN_DOTS)
4763 /* if we parsed a dot we need a typename now */
4764 if (!parser_next(parser)) {
4765 parseerror(parser, "expected typename for field definition");
4769 /* Further dots are handled seperately because they won't be part of the
4773 if (parser->tok == '.')
4775 else if (parser->tok == TOKEN_DOTS)
4780 if (!parser_next(parser)) {
4781 parseerror(parser, "expected typename for field definition");
4786 if (parser->tok == TOKEN_IDENT)
4787 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4788 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4789 if (vararg && is_vararg) {
4793 parseerror(parser, "expected typename");
4797 /* generate the basic type value */
4798 if (cached_typedef) {
4799 var = ast_value_copy(cached_typedef);
4800 ast_value_set_name(var, "<type(from_def)>");
4802 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4804 for (; morefields; --morefields) {
4805 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4806 tmp->expression.next = (ast_expression*)var;
4810 /* do not yet turn into a field - remember:
4811 * .void() foo; is a field too
4812 * .void()() foo; is a function
4816 if (!parser_next(parser)) {
4818 parseerror(parser, "parse error after typename");
4822 /* an opening paren now starts the parameter-list of a function
4823 * this is where original-QC has parameter lists.
4824 * We allow a single parameter list here.
4825 * Much like fteqcc we don't allow `float()() x`
4827 if (parser->tok == '(') {
4828 var = parse_parameter_list(parser, var);
4833 /* store the base if requested */
4835 *storebase = ast_value_copy(var);
4837 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4838 tmp->expression.next = (ast_expression*)*storebase;
4843 /* there may be a name now */
4844 if (parser->tok == TOKEN_IDENT || parser->tok == TOKEN_KEYWORD) {
4845 if (!strcmp(parser_tokval(parser), "break"))
4846 (void)!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
4847 else if (parser->tok == TOKEN_KEYWORD)
4850 name = util_strdup(parser_tokval(parser));
4853 if (!parser_next(parser)) {
4856 parseerror(parser, "error after variable or field declaration");
4862 /* now this may be an array */
4863 if (parser->tok == '[') {
4865 var = parse_arraysize(parser, var);
4867 if (name) mem_d(name);
4872 /* This is the point where we can turn it into a field */
4874 /* turn it into a field if desired */
4875 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4876 tmp->expression.next = (ast_expression*)var;
4880 /* now there may be function parens again */
4881 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4882 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4883 if (parser->tok == '(' && wasarray)
4884 parseerror(parser, "arrays as part of a return type is not supported");
4885 while (parser->tok == '(') {
4886 var = parse_parameter_list(parser, var);
4888 if (name) mem_d(name);
4893 /* finally name it */
4895 if (!ast_value_set_name(var, name)) {
4898 parseerror(parser, "internal error: failed to set name");
4901 /* free the name, ast_value_set_name duplicates */
4908 static bool parse_typedef(parser_t *parser)
4910 ast_value *typevar, *oldtype;
4911 ast_expression *old;
4913 typevar = parse_typename(parser, NULL, NULL, NULL);
4918 /* while parsing types, the ast_value's get named '<something>' */
4919 if (!typevar->name || typevar->name[0] == '<') {
4920 parseerror(parser, "missing name in typedef");
4921 ast_delete(typevar);
4925 if ( (old = parser_find_var(parser, typevar->name)) ) {
4926 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4927 " -> `%s` has been declared here: %s:%i",
4928 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4929 ast_delete(typevar);
4933 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4934 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4935 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4936 ast_delete(typevar);
4940 vec_push(parser->_typedefs, typevar);
4941 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4943 if (parser->tok != ';') {
4944 parseerror(parser, "expected semicolon after typedef");
4947 if (!parser_next(parser)) {
4948 parseerror(parser, "parse error after typedef");
4955 static const char *cvq_to_str(int cvq) {
4957 case CV_NONE: return "none";
4958 case CV_VAR: return "`var`";
4959 case CV_CONST: return "`const`";
4960 default: return "<INVALID>";
4964 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4967 if (proto->cvq != var->cvq) {
4968 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4969 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4970 parser->tok == '='))
4972 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4973 "`%s` declared with different qualifiers: %s\n"
4974 " -> previous declaration here: %s:%i uses %s",
4975 var->name, cvq_to_str(var->cvq),
4976 ast_ctx(proto).file, ast_ctx(proto).line,
4977 cvq_to_str(proto->cvq));
4980 av = (var ->expression.flags & AST_FLAG_NORETURN);
4981 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4983 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4984 "`%s` declared with different attributes%s\n"
4985 " -> previous declaration here: %s:%i",
4986 var->name, (av ? ": noreturn" : ""),
4987 ast_ctx(proto).file, ast_ctx(proto).line,
4988 (ao ? ": noreturn" : ""));
4993 static bool create_array_accessors(parser_t *parser, ast_value *var)
4996 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4997 if (!parser_create_array_setter(parser, var, name))
4999 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5000 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5005 static bool parse_array(parser_t *parser, ast_value *array)
5008 if (array->initlist) {
5009 parseerror(parser, "array already initialized elsewhere");
5012 if (!parser_next(parser)) {
5013 parseerror(parser, "parse error in array initializer");
5017 while (parser->tok != '}') {
5018 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5021 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5023 parseerror(parser, "initializing element must be a compile time constant");
5026 vec_push(array->initlist, v->constval);
5027 if (v->expression.vtype == TYPE_STRING) {
5028 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5032 if (parser->tok == '}')
5034 if (parser->tok != ',' || !parser_next(parser)) {
5035 parseerror(parser, "expected comma or '}' in element list");
5039 if (!parser_next(parser) || parser->tok != ';') {
5040 parseerror(parser, "expected semicolon after initializer, got %s");
5044 if (!parser_next(parser)) {
5045 parseerror(parser, "parse error after initializer");
5050 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5051 if (array->expression.count != (size_t)-1) {
5052 parseerror(parser, "array `%s' has already been initialized with %u elements",
5053 array->name, (unsigned)array->expression.count);
5055 array->expression.count = vec_size(array->initlist);
5056 if (!create_array_accessors(parser, array))
5062 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)
5066 ast_expression *old;
5070 ast_value *basetype = NULL;
5072 bool isparam = false;
5073 bool isvector = false;
5074 bool cleanvar = true;
5075 bool wasarray = false;
5077 ast_member *me[3] = { NULL, NULL, NULL };
5078 ast_member *last_me[3] = { NULL, NULL, NULL };
5080 if (!localblock && is_static)
5081 parseerror(parser, "`static` qualifier is not supported in global scope");
5083 /* get the first complete variable */
5084 var = parse_typename(parser, &basetype, cached_typedef, NULL);
5087 ast_delete(basetype);
5091 /* while parsing types, the ast_value's get named '<something>' */
5092 if (!var->name || var->name[0] == '<') {
5093 parseerror(parser, "declaration does not declare anything");
5095 ast_delete(basetype);
5103 /* Part 0: finish the type */
5104 if (parser->tok == '(') {
5105 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5106 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5107 var = parse_parameter_list(parser, var);
5113 /* we only allow 1-dimensional arrays */
5114 if (parser->tok == '[') {
5116 var = parse_arraysize(parser, var);
5122 if (parser->tok == '(' && wasarray) {
5123 parseerror(parser, "arrays as part of a return type is not supported");
5124 /* we'll still parse the type completely for now */
5126 /* for functions returning functions */
5127 while (parser->tok == '(') {
5128 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5129 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5130 var = parse_parameter_list(parser, var);
5137 var->cvq = qualifier;
5138 if (qflags & AST_FLAG_COVERAGE) /* specified in QC, drop our default */
5139 var->expression.flags &= ~(AST_FLAG_COVERAGE_MASK);
5140 var->expression.flags |= qflags;
5143 * store the vstring back to var for alias and
5144 * deprecation messages.
5146 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5147 var->expression.flags & AST_FLAG_ALIAS)
5148 var->desc = vstring;
5150 if (parser_find_global(parser, var->name) && var->expression.flags & AST_FLAG_ALIAS) {
5151 parseerror(parser, "function aliases cannot be forward declared");
5158 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5159 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5160 * is then filled with the previous definition and the parameter-names replaced.
5162 if (!strcmp(var->name, "nil")) {
5163 if (OPTS_FLAG(UNTYPED_NIL)) {
5164 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5165 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5167 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5170 /* Deal with end_sys_ vars */
5172 if (!strcmp(var->name, "end_sys_globals")) {
5174 parser->crc_globals = vec_size(parser->globals);
5177 else if (!strcmp(var->name, "end_sys_fields")) {
5179 parser->crc_fields = vec_size(parser->fields);
5182 if (was_end && var->expression.vtype == TYPE_FIELD) {
5183 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5184 "global '%s' hint should not be a field",
5185 parser_tokval(parser)))
5192 if (!nofields && var->expression.vtype == TYPE_FIELD)
5194 /* deal with field declarations */
5195 old = parser_find_field(parser, var->name);
5197 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5198 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5207 parseerror(parser, "field `%s` already declared here: %s:%i",
5208 var->name, ast_ctx(old).file, ast_ctx(old).line);
5213 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5214 (old = parser_find_global(parser, var->name)))
5216 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5217 parseerror(parser, "field `%s` already declared here: %s:%i",
5218 var->name, ast_ctx(old).file, ast_ctx(old).line);
5225 /* deal with other globals */
5226 old = parser_find_global(parser, var->name);
5227 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5229 /* This is a function which had a prototype */
5230 if (!ast_istype(old, ast_value)) {
5231 parseerror(parser, "internal error: prototype is not an ast_value");
5235 proto = (ast_value*)old;
5236 proto->desc = var->desc;
5237 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5238 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5240 ast_ctx(proto).file, ast_ctx(proto).line);
5244 /* we need the new parameter-names */
5245 for (i = 0; i < proto->expression.params.size(); ++i)
5246 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5247 if (!parser_check_qualifiers(parser, var, proto)) {
5254 proto->expression.flags |= var->expression.flags;
5262 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5263 "global `%s` already declared here: %s:%i",
5264 var->name, ast_ctx(old).file, ast_ctx(old).line))
5269 if (old->flags & AST_FLAG_FINAL_DECL) {
5270 parseerror(parser, "cannot redeclare variable `%s`, declared final here: %s:%i",
5271 var->name, ast_ctx(old).file, ast_ctx(old).line);
5275 proto = (ast_value*)old;
5276 if (!ast_istype(old, ast_value)) {
5277 parseerror(parser, "internal error: not an ast_value");
5282 if (!parser_check_qualifiers(parser, var, proto)) {
5287 proto->expression.flags |= var->expression.flags;
5288 /* copy the context for finals,
5289 * so the error can show where it was actually made 'final'
5291 if (proto->expression.flags & AST_FLAG_FINAL_DECL)
5292 ast_ctx(old) = ast_ctx(var);
5296 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5297 (old = parser_find_field(parser, var->name)))
5299 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5300 parseerror(parser, "global `%s` already declared here: %s:%i",
5301 var->name, ast_ctx(old).file, ast_ctx(old).line);
5308 else /* it's not a global */
5310 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5311 if (old && !isparam) {
5312 parseerror(parser, "local `%s` already declared here: %s:%i",
5313 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5317 /* doing this here as the above is just for a single scope */
5318 old = parser_find_local(parser, var->name, 0, &isparam);
5319 if (old && isparam) {
5320 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5321 "local `%s` is shadowing a parameter", var->name))
5323 parseerror(parser, "local `%s` already declared here: %s:%i",
5324 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5328 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5330 if (ast_istype(old, ast_value))
5331 var = proto = (ast_value*)old;
5340 /* in a noref section we simply bump the usecount */
5341 if (noref || parser->noref)
5345 * Create the global/local, and deal with vector types.
5348 if (var->expression.vtype == TYPE_VECTOR)
5350 else if (var->expression.vtype == TYPE_FIELD &&
5351 var->expression.next->vtype == TYPE_VECTOR)
5355 if (!create_vector_members(var, me)) {
5362 /* deal with global variables, fields, functions */
5363 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5364 var->isfield = true;
5365 vec_push(parser->fields, (ast_expression*)var);
5366 util_htset(parser->htfields, var->name, var);
5368 for (i = 0; i < 3; ++i) {
5369 vec_push(parser->fields, (ast_expression*)me[i]);
5370 util_htset(parser->htfields, me[i]->name, me[i]);
5375 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5376 parser_addglobal(parser, var->name, (ast_expression*)var);
5378 for (i = 0; i < 3; ++i) {
5379 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5383 ast_expression *find = parser_find_global(parser, var->desc);
5386 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5390 if (!ast_compare_type((ast_expression*)var, find)) {
5394 ast_type_to_string(find, ty1, sizeof(ty1));
5395 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5397 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5403 util_htset(parser->aliases, var->name, find);
5405 /* generate aliases for vector components */
5409 util_asprintf(&buffer[0], "%s_x", var->desc);
5410 util_asprintf(&buffer[1], "%s_y", var->desc);
5411 util_asprintf(&buffer[2], "%s_z", var->desc);
5413 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5414 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5415 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5425 /* a static adds itself to be generated like any other global
5426 * but is added to the local namespace instead
5428 char *defname = NULL;
5429 size_t prefix_len, ln;
5432 ln = strlen(parser->function->name);
5433 vec_append(defname, ln, parser->function->name);
5435 vec_append(defname, 2, "::");
5436 /* remember the length up to here */
5437 prefix_len = vec_size(defname);
5439 /* Add it to the local scope */
5440 util_htset(vec_last(parser->variables), var->name, (void*)var);
5442 /* now rename the global */
5443 ln = strlen(var->name);
5444 vec_append(defname, ln, var->name);
5445 /* if a variable of that name already existed, add the
5447 * The counter is incremented either way.
5449 sn_size = vec_size(parser->function->static_names);
5450 for (sn = 0; sn != sn_size; ++sn) {
5451 if (strcmp(parser->function->static_names[sn], var->name) == 0)
5454 if (sn != sn_size) {
5456 int len = util_asprintf(&num, "#%u", parser->function->static_count);
5457 vec_append(defname, len, num);
5461 vec_push(parser->function->static_names, util_strdup(var->name));
5462 parser->function->static_count++;
5463 ast_value_set_name(var, defname);
5465 /* push it to the to-be-generated globals */
5466 vec_push(parser->globals, (ast_expression*)var);
5468 /* same game for the vector members */
5470 for (i = 0; i < 3; ++i) {
5471 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5473 vec_shrinkto(defname, prefix_len);
5474 ln = strlen(me[i]->name);
5475 vec_append(defname, ln, me[i]->name);
5476 ast_member_set_name(me[i], defname);
5478 vec_push(parser->globals, (ast_expression*)me[i]);
5483 localblock->locals.push_back(var);
5484 parser_addlocal(parser, var->name, (ast_expression*)var);
5486 for (i = 0; i < 3; ++i) {
5487 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5488 ast_block_collect(localblock, (ast_expression*)me[i]);
5494 memcpy(last_me, me, sizeof(me));
5495 me[0] = me[1] = me[2] = NULL;
5500 if (var->expression.vtype == TYPE_ARRAY) {
5501 if (var->expression.count != (size_t)-1) {
5502 if (!create_array_accessors(parser, var))
5506 else if (!localblock && !nofields &&
5507 var->expression.vtype == TYPE_FIELD &&
5508 var->expression.next->vtype == TYPE_ARRAY)
5511 ast_expression *telem;
5513 ast_value *array = (ast_value*)var->expression.next;
5515 if (!ast_istype(var->expression.next, ast_value)) {
5516 parseerror(parser, "internal error: field element type must be an ast_value");
5520 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5521 if (!parser_create_array_field_setter(parser, array, name))
5524 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5525 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5526 tfield->expression.next = telem;
5527 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5528 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5536 if (parser->tok == ';') {
5537 ast_delete(basetype);
5538 if (!parser_next(parser)) {
5539 parseerror(parser, "error after variable declaration");
5545 if (parser->tok == ',')
5549 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5552 parseerror(parser, "missing comma or semicolon while parsing variables");
5556 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5557 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5558 "initializing expression turns variable `%s` into a constant in this standard",
5565 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5566 if (parser->tok != '=') {
5567 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5571 if (!parser_next(parser)) {
5572 parseerror(parser, "error parsing initializer");
5576 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5577 parseerror(parser, "expected '=' before function body in this standard");
5580 if (parser->tok == '#') {
5581 ast_function *func = NULL;
5582 ast_value *number = NULL;
5588 parseerror(parser, "cannot declare builtins within functions");
5591 if (var->expression.vtype != TYPE_FUNCTION) {
5592 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5595 if (!parser_next(parser)) {
5596 parseerror(parser, "expected builtin number");
5600 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5601 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5603 parseerror(parser, "builtin number expected");
5606 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5609 parseerror(parser, "builtin number must be a compile time constant");
5612 if (number->expression.vtype == TYPE_INTEGER)
5613 builtin_num = number->constval.vint;
5614 else if (number->expression.vtype == TYPE_FLOAT)
5615 builtin_num = number->constval.vfloat;
5618 parseerror(parser, "builtin number must be an integer constant");
5623 fractional = modff(builtin_num, &integral);
5624 if (builtin_num < 0 || fractional != 0) {
5625 parseerror(parser, "builtin number must be an integer greater than zero");
5629 /* we only want the integral part anyways */
5630 builtin_num = integral;
5631 } else if (parser->tok == TOKEN_INTCONST) {
5632 builtin_num = parser_token(parser)->constval.i;
5634 parseerror(parser, "builtin number must be a compile time constant");
5638 if (var->hasvalue) {
5639 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5640 "builtin `%s` has already been defined\n"
5641 " -> previous declaration here: %s:%i",
5642 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5646 func = ast_function_new(ast_ctx(var), var->name, var);
5648 parseerror(parser, "failed to allocate function for `%s`", var->name);
5651 vec_push(parser->functions, func);
5653 func->builtin = -builtin_num-1;
5656 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5657 ? (parser->tok != ',' && parser->tok != ';')
5658 : (!parser_next(parser)))
5660 parseerror(parser, "expected comma or semicolon");
5662 ast_function_delete(func);
5663 var->constval.vfunc = NULL;
5667 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5670 /* Note that fteqcc and most others don't even *have*
5671 * local arrays, so this is not a high priority.
5673 parseerror(parser, "TODO: initializers for local arrays");
5677 var->hasvalue = true;
5678 if (!parse_array(parser, var))
5681 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5684 parseerror(parser, "cannot declare functions within functions");
5689 ast_ctx(proto) = parser_ctx(parser);
5691 if (!parse_function_body(parser, var))
5693 ast_delete(basetype);
5694 for (auto &it : parser->gotos)
5695 parseerror(parser, "undefined label: `%s`", it->name);
5698 ast_expression *cexp;
5700 bool folded_const = false;
5702 cexp = parse_expression_leave(parser, true, false, false);
5705 cval = ast_istype(cexp, ast_value) ? (ast_value*)cexp : NULL;
5707 /* deal with foldable constants: */
5709 var->cvq == CV_CONST && cval && cval->hasvalue && cval->cvq == CV_CONST && !cval->isfield)
5711 /* remove it from the current locals */
5713 for (i = 0; i < 3; ++i) {
5714 vec_pop(parser->_locals);
5715 localblock->collect.pop_back();
5718 /* do sanity checking, this function really needs refactoring */
5719 if (vec_last(parser->_locals) != (ast_expression*)var)
5720 parseerror(parser, "internal error: unexpected change in local variable handling");
5722 vec_pop(parser->_locals);
5723 if (localblock->locals.back() != var)
5724 parseerror(parser, "internal error: unexpected change in local variable handling (2)");
5726 localblock->locals.pop_back();
5727 /* push it to the to-be-generated globals */
5728 vec_push(parser->globals, (ast_expression*)var);
5730 for (i = 0; i < 3; ++i)
5731 vec_push(parser->globals, (ast_expression*)last_me[i]);
5732 folded_const = true;
5735 if (folded_const || !localblock || is_static) {
5736 if (cval != parser->nil &&
5737 (!cval || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5740 parseerror(parser, "initializer is non constant");
5745 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5746 qualifier != CV_VAR)
5748 var->cvq = CV_CONST;
5750 if (cval == parser->nil)
5751 var->expression.flags |= AST_FLAG_INITIALIZED;
5754 var->hasvalue = true;
5755 if (cval->expression.vtype == TYPE_STRING)
5756 var->constval.vstring = parser_strdup(cval->constval.vstring);
5757 else if (cval->expression.vtype == TYPE_FIELD)
5758 var->constval.vfield = cval;
5760 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5766 shunt sy = { NULL, NULL, NULL, NULL };
5769 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5770 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5771 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5772 if (!parser_sy_apply_operator(parser, &sy))
5775 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5776 parseerror(parser, "internal error: leaked operands");
5777 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5785 /* a constant initialized to an inexact value should be marked inexact:
5786 * const float x = <inexact>; should propagate the inexact flag
5788 if (var->cvq == CV_CONST && var->expression.vtype == TYPE_FLOAT) {
5789 if (cval && cval->hasvalue && cval->cvq == CV_CONST)
5790 var->inexact = cval->inexact;
5795 if (parser->tok == ',') {
5796 if (!parser_next(parser)) {
5797 parseerror(parser, "expected another variable");
5801 if (parser->tok != TOKEN_IDENT) {
5802 parseerror(parser, "expected another variable");
5805 var = ast_value_copy(basetype);
5807 ast_value_set_name(var, parser_tokval(parser));
5808 if (!parser_next(parser)) {
5809 parseerror(parser, "error parsing variable declaration");
5815 if (parser->tok != ';') {
5816 parseerror(parser, "missing semicolon after variables");
5820 if (!parser_next(parser)) {
5821 parseerror(parser, "parse error after variable declaration");
5825 ast_delete(basetype);
5829 if (cleanvar && var)
5831 ast_delete(basetype);
5835 ast_delete(basetype);
5836 if (cleanvar && var)
5838 if (me[0]) ast_member_delete(me[0]);
5839 if (me[1]) ast_member_delete(me[1]);
5840 if (me[2]) ast_member_delete(me[2]);
5844 static bool parser_global_statement(parser_t *parser)
5848 bool is_static = false;
5849 uint32_t qflags = 0;
5850 ast_value *istype = NULL;
5851 char *vstring = NULL;
5853 if (parser->tok == TOKEN_IDENT)
5854 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5856 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.' || parser->tok == TOKEN_DOTS)
5858 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5860 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5862 if (cvq == CV_WRONG)
5864 return parse_variable(parser, NULL, false, cvq, NULL, noref, is_static, qflags, vstring);
5866 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5868 return parse_enum(parser);
5870 else if (parser->tok == TOKEN_KEYWORD)
5872 if (!strcmp(parser_tokval(parser), "typedef")) {
5873 if (!parser_next(parser)) {
5874 parseerror(parser, "expected type definition after 'typedef'");
5877 return parse_typedef(parser);
5879 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5882 else if (parser->tok == '#')
5884 return parse_pragma(parser);
5886 else if (parser->tok == '$')
5888 if (!parser_next(parser)) {
5889 parseerror(parser, "parse error");
5895 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5901 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5903 return util_crc16(old, str, strlen(str));
5906 static void progdefs_crc_file(const char *str)
5908 /* write to progdefs.h here */
5912 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5914 old = progdefs_crc_sum(old, str);
5915 progdefs_crc_file(str);
5919 static void generate_checksum(parser_t *parser, ir_builder *ir)
5921 uint16_t crc = 0xFFFF;
5925 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5926 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5928 progdefs_crc_file("\tint\tpad;\n");
5929 progdefs_crc_file("\tint\tofs_return[3];\n");
5930 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5931 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5932 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5933 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5934 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5935 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5936 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5937 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5939 for (i = 0; i < parser->crc_globals; ++i) {
5940 if (!ast_istype(parser->globals[i], ast_value))
5942 value = (ast_value*)(parser->globals[i]);
5943 switch (value->expression.vtype) {
5944 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5945 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5946 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5947 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5949 crc = progdefs_crc_both(crc, "\tint\t");
5952 crc = progdefs_crc_both(crc, value->name);
5953 crc = progdefs_crc_both(crc, ";\n");
5955 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5956 for (i = 0; i < parser->crc_fields; ++i) {
5957 if (!ast_istype(parser->fields[i], ast_value))
5959 value = (ast_value*)(parser->fields[i]);
5960 switch (value->expression.next->vtype) {
5961 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5962 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5963 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5964 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5966 crc = progdefs_crc_both(crc, "\tint\t");
5969 crc = progdefs_crc_both(crc, value->name);
5970 crc = progdefs_crc_both(crc, ";\n");
5972 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5973 ir->code->crc = crc;
5976 parser_t *parser_create()
5979 lex_ctx_t empty_ctx;
5982 parser = (parser_t*)mem_a(sizeof(parser_t));
5986 memset(parser, 0, sizeof(*parser));
5989 new (parser) parser_t();
5991 for (i = 0; i < operator_count; ++i) {
5992 if (operators[i].id == opid1('=')) {
5993 parser->assign_op = operators+i;
5997 if (!parser->assign_op) {
5998 con_err("internal error: initializing parser: failed to find assign operator\n");
6003 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6004 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6005 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6006 vec_push(parser->_blocktypedefs, 0);
6008 parser->aliases = util_htnew(PARSER_HT_SIZE);
6010 empty_ctx.file = "<internal>";
6012 empty_ctx.column = 0;
6013 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6014 parser->nil->cvq = CV_CONST;
6015 if (OPTS_FLAG(UNTYPED_NIL))
6016 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6018 parser->max_param_count = 1;
6020 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6021 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6022 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6024 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6025 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6026 parser->reserved_version->cvq = CV_CONST;
6027 parser->reserved_version->hasvalue = true;
6028 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6029 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6031 parser->reserved_version = NULL;
6034 parser->fold = fold_init (parser);
6035 parser->intrin = intrin_init(parser);
6039 static bool parser_compile(parser_t *parser)
6041 /* initial lexer/parser state */
6042 parser->lex->flags.noops = true;
6044 if (parser_next(parser))
6046 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6048 if (!parser_global_statement(parser)) {
6049 if (parser->tok == TOKEN_EOF)
6050 parseerror(parser, "unexpected end of file");
6051 else if (compile_errors)
6052 parseerror(parser, "there have been errors, bailing out");
6053 lex_close(parser->lex);
6059 parseerror(parser, "parse error");
6060 lex_close(parser->lex);
6065 lex_close(parser->lex);
6068 return !compile_errors;
6071 bool parser_compile_file(parser_t *parser, const char *filename)
6073 parser->lex = lex_open(filename);
6075 con_err("failed to open file \"%s\"\n", filename);
6078 return parser_compile(parser);
6081 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6083 parser->lex = lex_open_string(str, len, name);
6085 con_err("failed to create lexer for string \"%s\"\n", name);
6088 return parser_compile(parser);
6091 static void parser_remove_ast(parser_t *parser)
6094 if (parser->ast_cleaned)
6096 parser->ast_cleaned = true;
6097 for (i = 0; i < vec_size(parser->accessors); ++i) {
6098 ast_delete(parser->accessors[i]->constval.vfunc);
6099 parser->accessors[i]->constval.vfunc = NULL;
6100 ast_delete(parser->accessors[i]);
6102 for (i = 0; i < vec_size(parser->functions); ++i) {
6103 ast_delete(parser->functions[i]);
6105 for (i = 0; i < vec_size(parser->fields); ++i) {
6106 ast_delete(parser->fields[i]);
6108 for (i = 0; i < vec_size(parser->globals); ++i) {
6109 ast_delete(parser->globals[i]);
6111 vec_free(parser->accessors);
6112 vec_free(parser->functions);
6113 vec_free(parser->globals);
6114 vec_free(parser->fields);
6116 for (i = 0; i < vec_size(parser->variables); ++i)
6117 util_htdel(parser->variables[i]);
6118 vec_free(parser->variables);
6119 vec_free(parser->_blocklocals);
6120 vec_free(parser->_locals);
6122 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6123 ast_delete(parser->_typedefs[i]);
6124 vec_free(parser->_typedefs);
6125 for (i = 0; i < vec_size(parser->typedefs); ++i)
6126 util_htdel(parser->typedefs[i]);
6127 vec_free(parser->typedefs);
6128 vec_free(parser->_blocktypedefs);
6130 vec_free(parser->_block_ctx);
6132 ast_value_delete(parser->nil);
6134 ast_value_delete(parser->const_vec[0]);
6135 ast_value_delete(parser->const_vec[1]);
6136 ast_value_delete(parser->const_vec[2]);
6138 if (parser->reserved_version)
6139 ast_value_delete(parser->reserved_version);
6141 util_htdel(parser->aliases);
6142 fold_cleanup(parser->fold);
6143 intrin_cleanup(parser->intrin);
6146 void parser_cleanup(parser_t *parser)
6148 parser_remove_ast(parser);
6152 static bool parser_set_coverage_func(parser_t *parser, ir_builder *ir) {
6154 ast_expression *expr;
6158 if (!OPTS_OPTION_BOOL(OPTION_COVERAGE))
6162 for (i = 0; i != vec_size(parser->functions); ++i) {
6163 if (!strcmp(parser->functions[i]->name, "coverage")) {
6164 func = parser->functions[i];
6169 if (OPTS_OPTION_BOOL(OPTION_COVERAGE)) {
6170 con_out("coverage support requested but no coverage() builtin declared\n");
6171 ir_builder_delete(ir);
6178 expr = (ast_expression*)cov;
6180 if (expr->vtype != TYPE_FUNCTION || expr->params.size()) {
6182 ast_type_to_string(expr, ty, sizeof(ty));
6183 con_out("invalid type for coverage(): %s\n", ty);
6184 ir_builder_delete(ir);
6188 ir->coverage_func = func->ir_func->value;
6192 bool parser_finish(parser_t *parser, const char *output)
6198 if (compile_errors) {
6199 con_out("*** there were compile errors\n");
6203 ir = ir_builder_new("gmqcc_out");
6205 con_out("failed to allocate builder\n");
6209 for (i = 0; i < vec_size(parser->fields); ++i) {
6212 if (!ast_istype(parser->fields[i], ast_value))
6214 field = (ast_value*)parser->fields[i];
6215 hasvalue = field->hasvalue;
6216 field->hasvalue = false;
6217 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6218 con_out("failed to generate field %s\n", field->name);
6219 ir_builder_delete(ir);
6224 ast_expression *subtype;
6225 field->hasvalue = true;
6226 subtype = field->expression.next;
6227 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6228 if (subtype->vtype == TYPE_FIELD)
6229 ifld->fieldtype = subtype->next->vtype;
6230 else if (subtype->vtype == TYPE_FUNCTION)
6231 ifld->outtype = subtype->next->vtype;
6232 (void)!ir_value_set_field(field->ir_v, ifld);
6235 for (i = 0; i < vec_size(parser->globals); ++i) {
6237 if (!ast_istype(parser->globals[i], ast_value))
6239 asvalue = (ast_value*)(parser->globals[i]);
6240 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6241 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6242 "unused global: `%s`", asvalue->name);
6244 if (!ast_global_codegen(asvalue, ir, false)) {
6245 con_out("failed to generate global %s\n", asvalue->name);
6246 ir_builder_delete(ir);
6250 /* Build function vararg accessor ast tree now before generating
6251 * immediates, because the accessors may add new immediates
6253 for (i = 0; i < vec_size(parser->functions); ++i) {
6254 ast_function *f = parser->functions[i];
6256 if (parser->max_param_count > f->vtype->expression.params.size()) {
6257 f->varargs->expression.count = parser->max_param_count - f->vtype->expression.params.size();
6258 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6259 con_out("failed to generate vararg setter for %s\n", f->name);
6260 ir_builder_delete(ir);
6263 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6264 con_out("failed to generate vararg getter for %s\n", f->name);
6265 ir_builder_delete(ir);
6269 ast_delete(f->varargs);
6274 /* Now we can generate immediates */
6275 if (!fold_generate(parser->fold, ir))
6278 /* before generating any functions we need to set the coverage_func */
6279 if (!parser_set_coverage_func(parser, ir))
6282 for (i = 0; i < vec_size(parser->globals); ++i) {
6284 if (!ast_istype(parser->globals[i], ast_value))
6286 asvalue = (ast_value*)(parser->globals[i]);
6287 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6289 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6290 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6291 "uninitialized constant: `%s`",
6293 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6294 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6295 "uninitialized global: `%s`",
6298 if (!ast_generate_accessors(asvalue, ir)) {
6299 ir_builder_delete(ir);
6303 for (i = 0; i < vec_size(parser->fields); ++i) {
6305 asvalue = (ast_value*)(parser->fields[i]->next);
6307 if (!ast_istype((ast_expression*)asvalue, ast_value))
6309 if (asvalue->expression.vtype != TYPE_ARRAY)
6311 if (!ast_generate_accessors(asvalue, ir)) {
6312 ir_builder_delete(ir);
6316 if (parser->reserved_version &&
6317 !ast_global_codegen(parser->reserved_version, ir, false))
6319 con_out("failed to generate reserved::version");
6320 ir_builder_delete(ir);
6323 for (i = 0; i < vec_size(parser->functions); ++i) {
6324 ast_function *f = parser->functions[i];
6325 if (!ast_function_codegen(f, ir)) {
6326 con_out("failed to generate function %s\n", f->name);
6327 ir_builder_delete(ir);
6332 generate_checksum(parser, ir);
6334 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6335 ir_builder_dump(ir, con_out);
6336 for (i = 0; i < vec_size(parser->functions); ++i) {
6337 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6338 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6339 ir_builder_delete(ir);
6343 parser_remove_ast(parser);
6345 if (compile_Werrors) {
6346 con_out("*** there were warnings treated as errors\n");
6347 compile_show_werrors();
6352 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6353 ir_builder_dump(ir, con_out);
6355 if (!ir_builder_generate(ir, output)) {
6356 con_out("*** failed to generate output file\n");
6357 ir_builder_delete(ir);
6361 ir_builder_delete(ir);