2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 #define PARSER_HT_LOCALS 2
29 #define PARSER_HT_SIZE 512
30 #define TYPEDEF_HT_SIZE 512
32 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
34 static void parser_enterblock(parser_t *parser);
35 static bool parser_leaveblock(parser_t *parser);
36 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
37 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
38 static bool parse_typedef(parser_t *parser);
39 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);
40 static ast_block* parse_block(parser_t *parser);
41 static bool parse_block_into(parser_t *parser, ast_block *block);
42 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
43 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
44 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
45 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
46 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
47 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
48 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
50 static void parseerror(parser_t *parser, const char *fmt, ...)
54 vcompile_error(parser->lex->tok.ctx, fmt, ap);
58 /* returns true if it counts as an error */
59 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
64 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
69 /**********************************************************************
73 static bool parser_next(parser_t *parser)
75 /* lex_do kills the previous token */
76 parser->tok = lex_do(parser->lex);
77 if (parser->tok == TOKEN_EOF)
79 if (parser->tok >= TOKEN_ERROR) {
80 parseerror(parser, "lex error");
86 #define parser_tokval(p) ((p)->lex->tok.value)
87 #define parser_token(p) (&((p)->lex->tok))
89 char *parser_strdup(const char *str)
92 /* actually dup empty strings */
93 char *out = (char*)mem_a(1);
97 return util_strdup(str);
100 static ast_expression* parser_find_field(parser_t *parser, const char *name)
102 return ( ast_expression*)util_htget(parser->htfields, name);
105 static ast_expression* parser_find_label(parser_t *parser, const char *name)
108 for(i = 0; i < vec_size(parser->labels); i++)
109 if (!strcmp(parser->labels[i]->name, name))
110 return (ast_expression*)parser->labels[i];
114 static ast_expression* parser_find_global(parser_t *parser, const char *name)
116 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
119 return (ast_expression*)util_htget(parser->htglobals, name);
122 static ast_expression* parser_find_param(parser_t *parser, const char *name)
126 if (!parser->function)
128 fun = parser->function->vtype;
129 for (i = 0; i < vec_size(fun->expression.params); ++i) {
130 if (!strcmp(fun->expression.params[i]->name, name))
131 return (ast_expression*)(fun->expression.params[i]);
136 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
141 hash = util_hthash(parser->htglobals, name);
144 for (i = vec_size(parser->variables); i > upto;) {
146 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
150 return parser_find_param(parser, name);
153 static ast_expression* parser_find_var(parser_t *parser, const char *name)
157 v = parser_find_local(parser, name, 0, &dummy);
158 if (!v) v = parser_find_global(parser, name);
162 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
166 hash = util_hthash(parser->typedefs[0], name);
168 for (i = vec_size(parser->typedefs); i > upto;) {
170 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 /* include intrinsics */
181 size_t etype; /* 0 = expression, others are operators */
185 ast_block *block; /* for commas and function calls */
204 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
215 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
219 e.out = (ast_expression*)v;
226 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
228 e.etype = 1 + (op - operators);
237 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
248 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
249 * so we need to rotate it to become ent.(foo[n]).
251 static bool rotate_entfield_array_index_nodes(ast_expression **out)
253 ast_array_index *index, *oldindex;
254 ast_entfield *entfield;
258 ast_expression *entity;
260 lex_ctx_t ctx = ast_ctx(*out);
262 if (!ast_istype(*out, ast_array_index))
264 index = (ast_array_index*)*out;
266 if (!ast_istype(index->array, ast_entfield))
268 entfield = (ast_entfield*)index->array;
270 if (!ast_istype(entfield->field, ast_value))
272 field = (ast_value*)entfield->field;
275 entity = entfield->entity;
279 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
280 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
281 *out = (ast_expression*)entfield;
283 oldindex->array = NULL;
284 oldindex->index = NULL;
285 ast_delete(oldindex);
290 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
294 ast_expression *out = NULL;
295 ast_expression *exprs[3];
296 ast_block *blocks[3];
297 ast_value *asvalue[3];
298 ast_binstore *asbinstore;
299 size_t i, assignop, addop, subop;
300 qcint_t generated_op = 0;
305 if (!vec_size(sy->ops)) {
306 parseerror(parser, "internal error: missing operator");
310 if (vec_last(sy->ops).isparen) {
311 parseerror(parser, "unmatched parenthesis");
315 op = &operators[vec_last(sy->ops).etype - 1];
316 ctx = vec_last(sy->ops).ctx;
318 if (vec_size(sy->out) < op->operands) {
319 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
320 op->op, (int)op->id);
324 vec_shrinkby(sy->ops, 1);
326 /* op(:?) has no input and no output */
330 vec_shrinkby(sy->out, op->operands);
331 for (i = 0; i < op->operands; ++i) {
332 exprs[i] = sy->out[vec_size(sy->out)+i].out;
333 blocks[i] = sy->out[vec_size(sy->out)+i].block;
334 asvalue[i] = (ast_value*)exprs[i];
336 if (exprs[i]->vtype == TYPE_NOEXPR &&
337 !(i != 0 && op->id == opid2('?',':')) &&
338 !(i == 1 && op->id == opid1('.')))
340 if (ast_istype(exprs[i], ast_label))
341 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
343 compile_error(ast_ctx(exprs[i]), "not an expression");
344 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
348 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
349 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
353 #define NotSameType(T) \
354 (exprs[0]->vtype != exprs[1]->vtype || \
355 exprs[0]->vtype != T)
357 /* preform any constant folding on operator usage first */
358 if ((out = fold_op(parser->fold, op, exprs)))
364 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
368 if (exprs[0]->vtype == TYPE_VECTOR &&
369 exprs[1]->vtype == TYPE_NOEXPR)
371 if (exprs[1] == (ast_expression*)parser->const_vec[0])
372 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
373 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
374 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
375 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
376 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
378 compile_error(ctx, "access to invalid vector component");
382 else if (exprs[0]->vtype == TYPE_ENTITY) {
383 if (exprs[1]->vtype != TYPE_FIELD) {
384 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
387 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
389 else if (exprs[0]->vtype == TYPE_VECTOR) {
390 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
394 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
400 if (exprs[0]->vtype != TYPE_ARRAY &&
401 !(exprs[0]->vtype == TYPE_FIELD &&
402 exprs[0]->next->vtype == TYPE_ARRAY))
404 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
405 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
408 if (exprs[1]->vtype != TYPE_FLOAT) {
409 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
410 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
413 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
414 if (rotate_entfield_array_index_nodes(&out))
417 /* This is not broken in fteqcc anymore */
418 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
419 /* this error doesn't need to make us bail out */
420 (void)!parsewarning(parser, WARN_EXTENSIONS,
421 "accessing array-field members of an entity without parenthesis\n"
422 " -> this is an extension from -std=gmqcc");
429 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
430 vec_push(sy->out, syexp(ctx, exprs[0]));
431 vec_push(sy->out, syexp(ctx, exprs[1]));
432 vec_last(sy->argc)++;
436 if (!ast_block_add_expr(blocks[0], exprs[1]))
439 blocks[0] = ast_block_new(ctx);
440 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
441 !ast_block_add_expr(blocks[0], exprs[1]))
446 ast_block_set_type(blocks[0], exprs[1]);
448 vec_push(sy->out, syblock(ctx, blocks[0]));
455 switch (exprs[0]->vtype) {
457 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
458 (ast_expression*)parser->fold->imm_float[0],
462 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
463 (ast_expression*)parser->fold->imm_vector[0],
467 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
468 type_name[exprs[0]->vtype]);
474 switch (exprs[0]->vtype) {
476 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
479 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
482 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
483 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
485 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
487 /* we don't constant-fold NOT for these types */
489 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
495 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
496 type_name[exprs[0]->vtype]);
502 if (exprs[0]->vtype != exprs[1]->vtype ||
503 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
505 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
506 type_name[exprs[0]->vtype],
507 type_name[exprs[1]->vtype]);
510 switch (exprs[0]->vtype) {
512 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
515 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
518 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
519 type_name[exprs[0]->vtype],
520 type_name[exprs[1]->vtype]);
525 if (exprs[0]->vtype != exprs[1]->vtype ||
526 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
528 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
529 type_name[exprs[1]->vtype],
530 type_name[exprs[0]->vtype]);
533 switch (exprs[0]->vtype) {
535 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
538 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
541 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
542 type_name[exprs[1]->vtype],
543 type_name[exprs[0]->vtype]);
548 if (exprs[0]->vtype != exprs[1]->vtype &&
549 !(exprs[0]->vtype == TYPE_VECTOR &&
550 exprs[1]->vtype == TYPE_FLOAT) &&
551 !(exprs[1]->vtype == TYPE_VECTOR &&
552 exprs[0]->vtype == TYPE_FLOAT)
555 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
556 type_name[exprs[1]->vtype],
557 type_name[exprs[0]->vtype]);
560 switch (exprs[0]->vtype) {
562 if (exprs[1]->vtype == TYPE_VECTOR)
563 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
565 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
568 if (exprs[1]->vtype == TYPE_FLOAT)
569 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
571 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
574 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
575 type_name[exprs[1]->vtype],
576 type_name[exprs[0]->vtype]);
581 if (exprs[1]->vtype != TYPE_FLOAT) {
582 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
583 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
584 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
587 if (exprs[0]->vtype == TYPE_FLOAT)
588 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
589 else if (exprs[0]->vtype == TYPE_VECTOR)
590 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
593 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
594 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
595 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
601 if (NotSameType(TYPE_FLOAT)) {
602 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
603 type_name[exprs[0]->vtype],
604 type_name[exprs[1]->vtype]);
607 /* generate a call to __builtin_mod */
608 ast_expression *mod = intrin_func(parser, "mod");
609 ast_call *call = NULL;
610 if (!mod) return false; /* can return null for missing floor */
612 call = ast_call_new(parser_ctx(parser), mod);
613 vec_push(call->params, exprs[0]);
614 vec_push(call->params, exprs[1]);
616 out = (ast_expression*)call;
621 compile_error(ctx, "%= is unimplemented");
626 if (NotSameType(TYPE_FLOAT)) {
627 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
628 type_name[exprs[0]->vtype],
629 type_name[exprs[1]->vtype]);
632 out = (ast_expression*)ast_binary_new(ctx,
633 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
638 * Okay lets designate what the hell is an acceptable use
639 * of the ^ operator. In many vector processing units, XOR
640 * is allowed to be used on vectors, but only if the first
641 * operand is a vector, the second operand can be a float
642 * or vector. It's never legal for the first operand to be
643 * a float, and then the following operand to be a vector.
644 * Further more, the only time it is legal to do XOR otherwise
645 * is when both operand are floats. This nicely crafted if
646 * statement catches them all.
648 * In the event that the first operand is a vector, two
649 * possible situations can arise, thus, each element of
650 * vector A (operand A) is exclusive-ORed with the corresponding
651 * element of vector B (operand B), If B is scalar, the
652 * scalar value is first replicated for each element.
654 * The QCVM itself lacks a BITXOR instruction. Thus emulating
655 * the mathematics of it is required. The following equation
656 * is used: (LHS | RHS) & ~(LHS & RHS). However, due to the
657 * QCVM also lacking a BITNEG instruction, we need to emulate
658 * ~FOO with -1 - FOO, the whole process becoming this nicely
659 * crafted expression: (LHS | RHS) & (-1 - (LHS & RHS)).
661 * When A is not scalar, this process is repeated for all
662 * components of vector A with the value in operand B,
663 * only if operand B is scalar. When A is not scalar, and B
664 * is also not scalar, this process is repeated for all
665 * components of the vector A with the components of vector B.
666 * Finally when A is scalar and B is scalar, this process is
667 * simply used once for A and B being LHS and RHS respectfully.
669 * Yes the semantics are a bit strange (no pun intended).
670 * But then again BITXOR is strange itself, consdering it's
671 * commutative, assocative, and elements of the BITXOR operation
672 * are their own inverse.
674 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
675 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
676 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
678 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
679 type_name[exprs[0]->vtype],
680 type_name[exprs[1]->vtype]);
685 * IF the first expression is float, the following will be too
686 * since scalar ^ vector is not allowed.
688 if (exprs[0]->vtype == TYPE_FLOAT) {
689 ast_binary *expr = ast_binary_new(
692 (ast_expression*)parser->fold->imm_float[2],
693 (ast_expression*)ast_binary_new(
700 expr->refs = AST_REF_NONE;
702 out = (ast_expression*)
706 (ast_expression*)ast_binary_new(
712 (ast_expression*)expr
716 * The first is a vector: vector is allowed to xor with vector and
717 * with scalar, branch here for the second operand.
719 if (exprs[1]->vtype == TYPE_VECTOR) {
721 * Xor all the values of the vector components against the
722 * vectors components in question.
724 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against vector");
727 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against float");
736 case opid3('<','<','='):
737 case opid3('>','>','='):
738 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
742 generated_op += 1; /* INSTR_OR */
744 generated_op += INSTR_AND;
745 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
746 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
747 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
748 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
751 for (i = 0; i < 2; ++i) {
752 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
753 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
755 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
757 exprs[i] = out; out = NULL;
758 if (OPTS_FLAG(PERL_LOGIC)) {
759 /* here we want to keep the right expressions' type */
763 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
764 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
766 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
768 exprs[i] = out; out = NULL;
769 if (OPTS_FLAG(PERL_LOGIC)) {
770 /* here we want to keep the right expressions' type */
775 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
779 if (vec_last(sy->paren) != PAREN_TERNARY2) {
780 compile_error(ctx, "mismatched parenthesis/ternary");
784 if (!ast_compare_type(exprs[1], exprs[2])) {
785 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
786 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
787 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
790 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
793 case opid2('*', '*'):
794 if (NotSameType(TYPE_FLOAT)) {
795 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
796 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
797 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
802 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
803 vec_push(gencall->params, exprs[0]);
804 vec_push(gencall->params, exprs[1]);
805 out = (ast_expression*)gencall;
809 case opid3('<','=','>'): /* -1, 0, or 1 */
810 if (NotSameType(TYPE_FLOAT)) {
811 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
812 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
813 compile_error(ctx, "invalid types used in comparision: %s and %s",
818 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
820 eq->refs = AST_REF_NONE;
823 out = (ast_expression*)ast_ternary_new(ctx,
824 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
826 (ast_expression*)parser->fold->imm_float[2],
829 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
831 (ast_expression*)parser->fold->imm_float[0],
834 (ast_expression*)parser->fold->imm_float[1]
844 generated_op += 1; /* INSTR_GT */
846 generated_op += 1; /* INSTR_LT */
847 case opid2('>', '='):
848 generated_op += 1; /* INSTR_GE */
849 case opid2('<', '='):
850 generated_op += INSTR_LE;
851 if (NotSameType(TYPE_FLOAT)) {
852 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
853 type_name[exprs[0]->vtype],
854 type_name[exprs[1]->vtype]);
857 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
859 case opid2('!', '='):
860 if (exprs[0]->vtype != exprs[1]->vtype) {
861 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
862 type_name[exprs[0]->vtype],
863 type_name[exprs[1]->vtype]);
866 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
868 case opid2('=', '='):
869 if (exprs[0]->vtype != exprs[1]->vtype) {
870 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
871 type_name[exprs[0]->vtype],
872 type_name[exprs[1]->vtype]);
875 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
879 if (ast_istype(exprs[0], ast_entfield)) {
880 ast_expression *field = ((ast_entfield*)exprs[0])->field;
881 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
882 exprs[0]->vtype == TYPE_FIELD &&
883 exprs[0]->next->vtype == TYPE_VECTOR)
885 assignop = type_storep_instr[TYPE_VECTOR];
888 assignop = type_storep_instr[exprs[0]->vtype];
889 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
891 ast_type_to_string(field->next, ty1, sizeof(ty1));
892 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
893 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
894 field->next->vtype == TYPE_FUNCTION &&
895 exprs[1]->vtype == TYPE_FUNCTION)
897 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
898 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
901 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
906 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
907 exprs[0]->vtype == TYPE_FIELD &&
908 exprs[0]->next->vtype == TYPE_VECTOR)
910 assignop = type_store_instr[TYPE_VECTOR];
913 assignop = type_store_instr[exprs[0]->vtype];
916 if (assignop == VINSTR_END) {
917 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
918 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
919 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
921 else if (!ast_compare_type(exprs[0], exprs[1]))
923 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
924 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
925 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
926 exprs[0]->vtype == TYPE_FUNCTION &&
927 exprs[1]->vtype == TYPE_FUNCTION)
929 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
930 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
933 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
936 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
937 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
939 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
941 case opid3('+','+','P'):
942 case opid3('-','-','P'):
944 if (exprs[0]->vtype != TYPE_FLOAT) {
945 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
946 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
949 if (op->id == opid3('+','+','P'))
953 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
954 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
956 if (ast_istype(exprs[0], ast_entfield)) {
957 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
959 (ast_expression*)parser->fold->imm_float[1]);
961 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
963 (ast_expression*)parser->fold->imm_float[1]);
966 case opid3('S','+','+'):
967 case opid3('S','-','-'):
969 if (exprs[0]->vtype != TYPE_FLOAT) {
970 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
971 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
974 if (op->id == opid3('S','+','+')) {
981 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
982 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
984 if (ast_istype(exprs[0], ast_entfield)) {
985 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
987 (ast_expression*)parser->fold->imm_float[1]);
989 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
991 (ast_expression*)parser->fold->imm_float[1]);
995 out = (ast_expression*)ast_binary_new(ctx, subop,
997 (ast_expression*)parser->fold->imm_float[1]);
1000 case opid2('-','='):
1001 if (exprs[0]->vtype != exprs[1]->vtype ||
1002 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1004 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1005 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1006 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1010 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1011 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1013 if (ast_istype(exprs[0], ast_entfield))
1014 assignop = type_storep_instr[exprs[0]->vtype];
1016 assignop = type_store_instr[exprs[0]->vtype];
1017 switch (exprs[0]->vtype) {
1019 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1020 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1021 exprs[0], exprs[1]);
1024 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1025 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1026 exprs[0], exprs[1]);
1029 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1030 type_name[exprs[0]->vtype],
1031 type_name[exprs[1]->vtype]);
1035 case opid2('*','='):
1036 case opid2('/','='):
1037 if (exprs[1]->vtype != TYPE_FLOAT ||
1038 !(exprs[0]->vtype == TYPE_FLOAT ||
1039 exprs[0]->vtype == TYPE_VECTOR))
1041 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1042 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1043 compile_error(ctx, "invalid types used in expression: %s and %s",
1047 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1048 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1050 if (ast_istype(exprs[0], ast_entfield))
1051 assignop = type_storep_instr[exprs[0]->vtype];
1053 assignop = type_store_instr[exprs[0]->vtype];
1054 switch (exprs[0]->vtype) {
1056 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1057 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1058 exprs[0], exprs[1]);
1061 if (op->id == opid2('*','=')) {
1062 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1063 exprs[0], exprs[1]);
1065 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1066 (ast_expression*)parser->fold->imm_float[1],
1069 compile_error(ctx, "internal error: failed to generate division");
1072 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1077 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1078 type_name[exprs[0]->vtype],
1079 type_name[exprs[1]->vtype]);
1083 case opid2('&','='):
1084 case opid2('|','='):
1085 if (NotSameType(TYPE_FLOAT)) {
1086 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1087 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1088 compile_error(ctx, "invalid types used in expression: %s and %s",
1092 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1093 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
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 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1100 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1101 exprs[0], exprs[1]);
1103 case opid3('&','~','='):
1104 /* This is like: a &= ~(b);
1105 * But QC has no bitwise-not, so we implement it as
1108 if (NotSameType(TYPE_FLOAT)) {
1109 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1110 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1111 compile_error(ctx, "invalid types used in expression: %s and %s",
1115 if (ast_istype(exprs[0], ast_entfield))
1116 assignop = type_storep_instr[exprs[0]->vtype];
1118 assignop = type_store_instr[exprs[0]->vtype];
1119 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1122 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1123 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1125 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1126 asbinstore->keep_dest = true;
1127 out = (ast_expression*)asbinstore;
1130 case opid2('~', 'P'):
1131 if (exprs[0]->vtype != TYPE_FLOAT) {
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 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1142 compile_error(ctx, "failed to apply operator %s", op->op);
1146 vec_push(sy->out, syexp(ctx, out));
1150 static bool parser_close_call(parser_t *parser, shunt *sy)
1152 /* was a function call */
1153 ast_expression *fun;
1154 ast_value *funval = NULL;
1158 size_t paramcount, i;
1160 fid = vec_last(sy->ops).off;
1161 vec_shrinkby(sy->ops, 1);
1163 /* out[fid] is the function
1164 * everything above is parameters...
1166 if (!vec_size(sy->argc)) {
1167 parseerror(parser, "internal error: no argument counter available");
1171 paramcount = vec_last(sy->argc);
1174 if (vec_size(sy->out) < fid) {
1175 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1176 (unsigned long)vec_size(sy->out),
1178 (unsigned long)paramcount);
1182 fun = sy->out[fid].out;
1184 if (fun == intrinsic_debug_typestring) {
1186 if (fid+2 != vec_size(sy->out) ||
1187 vec_last(sy->out).block)
1189 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1192 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1193 ast_unref(vec_last(sy->out).out);
1194 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1195 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1196 vec_shrinkby(sy->out, 1);
1200 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1204 if (fid+1 < vec_size(sy->out))
1207 if (fid+1 + paramcount != vec_size(sy->out)) {
1208 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1209 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1213 for (i = 0; i < paramcount; ++i)
1214 vec_push(call->params, sy->out[fid+1 + i].out);
1215 vec_shrinkby(sy->out, paramcount);
1216 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1217 if (parser->max_param_count < paramcount)
1218 parser->max_param_count = paramcount;
1220 if (ast_istype(fun, ast_value)) {
1221 funval = (ast_value*)fun;
1222 if ((fun->flags & AST_FLAG_VARIADIC) &&
1223 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1225 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1229 /* overwrite fid, the function, with a call */
1230 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1232 if (fun->vtype != TYPE_FUNCTION) {
1233 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1238 parseerror(parser, "could not determine function return type");
1241 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1243 if (fun->flags & AST_FLAG_DEPRECATED) {
1245 return !parsewarning(parser, WARN_DEPRECATED,
1246 "call to function (which is marked deprecated)\n",
1247 "-> it has been declared here: %s:%i",
1248 ast_ctx(fun).file, ast_ctx(fun).line);
1251 return !parsewarning(parser, WARN_DEPRECATED,
1252 "call to `%s` (which is marked deprecated)\n"
1253 "-> `%s` declared here: %s:%i",
1254 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1256 return !parsewarning(parser, WARN_DEPRECATED,
1257 "call to `%s` (deprecated: %s)\n"
1258 "-> `%s` declared here: %s:%i",
1259 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1263 if (vec_size(fun->params) != paramcount &&
1264 !((fun->flags & AST_FLAG_VARIADIC) &&
1265 vec_size(fun->params) < paramcount))
1267 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1269 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1270 "too %s parameters for call to %s: expected %i, got %i\n"
1271 " -> `%s` has been declared here: %s:%i",
1272 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1273 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1275 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1276 "too %s parameters for function call: expected %i, got %i\n"
1277 " -> it has been declared here: %s:%i",
1278 fewmany, (int)vec_size(fun->params), (int)paramcount,
1279 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1286 static bool parser_close_paren(parser_t *parser, shunt *sy)
1288 if (!vec_size(sy->ops)) {
1289 parseerror(parser, "unmatched closing paren");
1293 while (vec_size(sy->ops)) {
1294 if (vec_last(sy->ops).isparen) {
1295 if (vec_last(sy->paren) == PAREN_FUNC) {
1297 if (!parser_close_call(parser, sy))
1301 if (vec_last(sy->paren) == PAREN_EXPR) {
1303 if (!vec_size(sy->out)) {
1304 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1305 vec_shrinkby(sy->ops, 1);
1308 vec_shrinkby(sy->ops, 1);
1311 if (vec_last(sy->paren) == PAREN_INDEX) {
1313 /* pop off the parenthesis */
1314 vec_shrinkby(sy->ops, 1);
1315 /* then apply the index operator */
1316 if (!parser_sy_apply_operator(parser, sy))
1320 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1321 vec_last(sy->paren) = PAREN_TERNARY2;
1322 /* pop off the parenthesis */
1323 vec_shrinkby(sy->ops, 1);
1326 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1329 if (!parser_sy_apply_operator(parser, sy))
1335 static void parser_reclassify_token(parser_t *parser)
1338 if (parser->tok >= TOKEN_START)
1340 for (i = 0; i < operator_count; ++i) {
1341 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1342 parser->tok = TOKEN_OPERATOR;
1348 static ast_expression* parse_vararg_do(parser_t *parser)
1350 ast_expression *idx, *out;
1352 ast_value *funtype = parser->function->vtype;
1353 lex_ctx_t ctx = parser_ctx(parser);
1355 if (!parser->function->varargs) {
1356 parseerror(parser, "function has no variable argument list");
1360 if (!parser_next(parser) || parser->tok != '(') {
1361 parseerror(parser, "expected parameter index and type in parenthesis");
1364 if (!parser_next(parser)) {
1365 parseerror(parser, "error parsing parameter index");
1369 idx = parse_expression_leave(parser, true, false, false);
1373 if (parser->tok != ',') {
1374 if (parser->tok != ')') {
1376 parseerror(parser, "expected comma after parameter index");
1379 /* vararg piping: ...(start) */
1380 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1384 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1386 parseerror(parser, "expected typename for vararg");
1390 typevar = parse_typename(parser, NULL, NULL);
1396 if (parser->tok != ')') {
1398 ast_delete(typevar);
1399 parseerror(parser, "expected closing paren");
1403 if (funtype->expression.varparam &&
1404 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1408 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1409 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1410 compile_error(ast_ctx(typevar),
1411 "function was declared to take varargs of type `%s`, requested type is: %s",
1415 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1416 ast_type_adopt(out, typevar);
1417 ast_delete(typevar);
1421 static ast_expression* parse_vararg(parser_t *parser)
1423 bool old_noops = parser->lex->flags.noops;
1425 ast_expression *out;
1427 parser->lex->flags.noops = true;
1428 out = parse_vararg_do(parser);
1430 parser->lex->flags.noops = old_noops;
1434 /* not to be exposed */
1435 extern bool ftepp_predef_exists(const char *name);
1437 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1439 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1440 parser->tok == TOKEN_IDENT &&
1441 !strcmp(parser_tokval(parser), "_"))
1443 /* a translatable string */
1446 parser->lex->flags.noops = true;
1447 if (!parser_next(parser) || parser->tok != '(') {
1448 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1451 parser->lex->flags.noops = false;
1452 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1453 parseerror(parser, "expected a constant string in translatable-string extension");
1456 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1459 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1461 if (!parser_next(parser) || parser->tok != ')') {
1462 parseerror(parser, "expected closing paren after translatable string");
1467 else if (parser->tok == TOKEN_DOTS)
1470 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1471 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1474 va = parse_vararg(parser);
1477 vec_push(sy->out, syexp(parser_ctx(parser), va));
1480 else if (parser->tok == TOKEN_FLOATCONST) {
1481 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1484 vec_push(sy->out, syexp(parser_ctx(parser), val));
1487 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1488 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1491 vec_push(sy->out, syexp(parser_ctx(parser), val));
1494 else if (parser->tok == TOKEN_STRINGCONST) {
1495 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1498 vec_push(sy->out, syexp(parser_ctx(parser), val));
1501 else if (parser->tok == TOKEN_VECTORCONST) {
1502 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1505 vec_push(sy->out, syexp(parser_ctx(parser), val));
1508 else if (parser->tok == TOKEN_IDENT)
1510 const char *ctoken = parser_tokval(parser);
1511 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1512 ast_expression *var;
1513 /* a_vector.{x,y,z} */
1514 if (!vec_size(sy->ops) ||
1515 !vec_last(sy->ops).etype ||
1516 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1517 (prev >= intrinsic_debug_typestring &&
1518 prev <= intrinsic_debug_typestring))
1520 /* When adding more intrinsics, fix the above condition */
1523 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1525 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1527 var = parser_find_var(parser, parser_tokval(parser));
1529 var = parser_find_field(parser, parser_tokval(parser));
1531 if (!var && with_labels) {
1532 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1534 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1535 var = (ast_expression*)lbl;
1536 vec_push(parser->labels, lbl);
1539 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1540 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1543 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1544 var = (ast_expression*)intrinsic_debug_typestring;
1546 /* now we try for the real intrinsic hashtable. If the string
1547 * begins with __builtin, we simply skip past it, otherwise we
1548 * use the identifier as is.
1550 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1551 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1555 char *correct = NULL;
1559 * sometimes people use preprocessing predefs without enabling them
1560 * i've done this thousands of times already myself. Lets check for
1561 * it in the predef table. And diagnose it better :)
1563 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1564 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1569 * TODO: determine the best score for the identifier: be it
1570 * a variable, a field.
1572 * We should also consider adding correction tables for
1573 * other things as well.
1575 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1577 correct_init(&corr);
1579 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1580 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1581 if (strcmp(correct, parser_tokval(parser))) {
1588 correct_free(&corr);
1591 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1596 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1602 if (ast_istype(var, ast_value)) {
1603 ((ast_value*)var)->uses++;
1605 else if (ast_istype(var, ast_member)) {
1606 ast_member *mem = (ast_member*)var;
1607 if (ast_istype(mem->owner, ast_value))
1608 ((ast_value*)(mem->owner))->uses++;
1611 vec_push(sy->out, syexp(parser_ctx(parser), var));
1614 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1618 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1620 ast_expression *expr = NULL;
1623 bool wantop = false;
1624 /* only warn once about an assignment in a truth value because the current code
1625 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1627 bool warn_truthvalue = true;
1629 /* count the parens because an if starts with one, so the
1630 * end of a condition is an unmatched closing paren
1634 memset(&sy, 0, sizeof(sy));
1636 parser->lex->flags.noops = false;
1638 parser_reclassify_token(parser);
1642 if (parser->tok == TOKEN_TYPENAME) {
1643 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1647 if (parser->tok == TOKEN_OPERATOR)
1649 /* classify the operator */
1650 const oper_info *op;
1651 const oper_info *olast = NULL;
1653 for (o = 0; o < operator_count; ++o) {
1654 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1655 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1656 !strcmp(parser_tokval(parser), operators[o].op))
1661 if (o == operator_count) {
1662 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1665 /* found an operator */
1668 /* when declaring variables, a comma starts a new variable */
1669 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1670 /* fixup the token */
1675 /* a colon without a pervious question mark cannot be a ternary */
1676 if (!ternaries && op->id == opid2(':','?')) {
1681 if (op->id == opid1(',')) {
1682 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1683 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1687 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1688 olast = &operators[vec_last(sy.ops).etype-1];
1690 #define IsAssignOp(x) (\
1691 (x) == opid1('=') || \
1692 (x) == opid2('+','=') || \
1693 (x) == opid2('-','=') || \
1694 (x) == opid2('*','=') || \
1695 (x) == opid2('/','=') || \
1696 (x) == opid2('%','=') || \
1697 (x) == opid2('&','=') || \
1698 (x) == opid2('|','=') || \
1699 (x) == opid3('&','~','=') \
1701 if (warn_truthvalue) {
1702 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1703 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1704 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1707 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1708 warn_truthvalue = false;
1713 (op->prec < olast->prec) ||
1714 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1716 if (!parser_sy_apply_operator(parser, &sy))
1718 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1719 olast = &operators[vec_last(sy.ops).etype-1];
1724 if (op->id == opid1('(')) {
1726 size_t sycount = vec_size(sy.out);
1727 /* we expected an operator, this is the function-call operator */
1728 vec_push(sy.paren, PAREN_FUNC);
1729 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1730 vec_push(sy.argc, 0);
1732 vec_push(sy.paren, PAREN_EXPR);
1733 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1736 } else if (op->id == opid1('[')) {
1738 parseerror(parser, "unexpected array subscript");
1741 vec_push(sy.paren, PAREN_INDEX);
1742 /* push both the operator and the paren, this makes life easier */
1743 vec_push(sy.ops, syop(parser_ctx(parser), op));
1744 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1746 } else if (op->id == opid2('?',':')) {
1747 vec_push(sy.ops, syop(parser_ctx(parser), op));
1748 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1751 vec_push(sy.paren, PAREN_TERNARY1);
1752 } else if (op->id == opid2(':','?')) {
1753 if (!vec_size(sy.paren)) {
1754 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1757 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1758 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1761 if (!parser_close_paren(parser, &sy))
1763 vec_push(sy.ops, syop(parser_ctx(parser), op));
1767 vec_push(sy.ops, syop(parser_ctx(parser), op));
1768 wantop = !!(op->flags & OP_SUFFIX);
1771 else if (parser->tok == ')') {
1772 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1773 if (!parser_sy_apply_operator(parser, &sy))
1776 if (!vec_size(sy.paren))
1779 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1780 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1783 if (!parser_close_paren(parser, &sy))
1786 /* must be a function call without parameters */
1787 if (vec_last(sy.paren) != PAREN_FUNC) {
1788 parseerror(parser, "closing paren in invalid position");
1791 if (!parser_close_paren(parser, &sy))
1796 else if (parser->tok == '(') {
1797 parseerror(parser, "internal error: '(' should be classified as operator");
1800 else if (parser->tok == '[') {
1801 parseerror(parser, "internal error: '[' should be classified as operator");
1804 else if (parser->tok == ']') {
1805 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1806 if (!parser_sy_apply_operator(parser, &sy))
1809 if (!vec_size(sy.paren))
1811 if (vec_last(sy.paren) != PAREN_INDEX) {
1812 parseerror(parser, "mismatched parentheses, unexpected ']'");
1815 if (!parser_close_paren(parser, &sy))
1820 if (!parse_sya_operand(parser, &sy, with_labels))
1823 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1824 vec_last(sy.argc)++;
1829 /* in this case we might want to allow constant string concatenation */
1830 bool concatenated = false;
1831 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1832 ast_expression *lexpr = vec_last(sy.out).out;
1833 if (ast_istype(lexpr, ast_value)) {
1834 ast_value *last = (ast_value*)lexpr;
1835 if (last->isimm == true && last->cvq == CV_CONST &&
1836 last->hasvalue && last->expression.vtype == TYPE_STRING)
1838 char *newstr = NULL;
1839 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1840 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1842 concatenated = true;
1846 if (!concatenated) {
1847 parseerror(parser, "expected operator or end of statement");
1852 if (!parser_next(parser)) {
1855 if (parser->tok == ';' ||
1856 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1857 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1863 while (vec_size(sy.ops)) {
1864 if (!parser_sy_apply_operator(parser, &sy))
1868 parser->lex->flags.noops = true;
1869 if (vec_size(sy.out) != 1) {
1870 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
1873 expr = sy.out[0].out;
1876 if (vec_size(sy.paren)) {
1877 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1885 parser->lex->flags.noops = true;
1886 for (i = 0; i < vec_size(sy.out); ++i) {
1888 ast_unref(sy.out[i].out);
1897 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1899 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1902 if (parser->tok != ';') {
1903 parseerror(parser, "semicolon expected after expression");
1907 if (!parser_next(parser)) {
1914 static void parser_enterblock(parser_t *parser)
1916 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1917 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1918 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1919 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1920 vec_push(parser->_block_ctx, parser_ctx(parser));
1923 vec_push(parser->correct_variables, correct_trie_new());
1924 vec_push(parser->correct_variables_score, NULL);
1927 static bool parser_leaveblock(parser_t *parser)
1930 size_t locals, typedefs;
1932 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1933 parseerror(parser, "internal error: parser_leaveblock with no block");
1937 util_htdel(vec_last(parser->variables));
1938 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1940 vec_pop(parser->variables);
1941 vec_pop(parser->correct_variables);
1942 vec_pop(parser->correct_variables_score);
1943 if (!vec_size(parser->_blocklocals)) {
1944 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1948 locals = vec_last(parser->_blocklocals);
1949 vec_pop(parser->_blocklocals);
1950 while (vec_size(parser->_locals) != locals) {
1951 ast_expression *e = vec_last(parser->_locals);
1952 ast_value *v = (ast_value*)e;
1953 vec_pop(parser->_locals);
1954 if (ast_istype(e, ast_value) && !v->uses) {
1955 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1960 typedefs = vec_last(parser->_blocktypedefs);
1961 while (vec_size(parser->_typedefs) != typedefs) {
1962 ast_delete(vec_last(parser->_typedefs));
1963 vec_pop(parser->_typedefs);
1965 util_htdel(vec_last(parser->typedefs));
1966 vec_pop(parser->typedefs);
1968 vec_pop(parser->_block_ctx);
1973 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1975 vec_push(parser->_locals, e);
1976 util_htset(vec_last(parser->variables), name, (void*)e);
1980 vec_last(parser->correct_variables),
1981 &vec_last(parser->correct_variables_score),
1986 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
1988 vec_push(parser->globals, e);
1989 util_htset(parser->htglobals, name, e);
1993 parser->correct_variables[0],
1994 &parser->correct_variables_score[0],
1999 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2003 ast_expression *prev;
2005 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2007 ast_type_to_string(cond, ty, sizeof(ty));
2008 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2011 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2014 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2017 parseerror(parser, "internal error: failed to process condition");
2022 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2024 /* vector types need to be cast to true booleans */
2025 ast_binary *bin = (ast_binary*)cond;
2026 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2028 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2030 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2033 parseerror(parser, "internal error: failed to process condition");
2040 unary = (ast_unary*)cond;
2041 /* ast_istype dereferences cond, should test here for safety */
2042 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2044 cond = unary->operand;
2045 unary->operand = NULL;
2048 unary = (ast_unary*)cond;
2052 parseerror(parser, "internal error: failed to process condition");
2054 if (ifnot) *_ifnot = !*_ifnot;
2058 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2061 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2064 lex_ctx_t ctx = parser_ctx(parser);
2066 (void)block; /* not touching */
2068 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2069 if (!parser_next(parser)) {
2070 parseerror(parser, "expected condition or 'not'");
2073 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2075 if (!parser_next(parser)) {
2076 parseerror(parser, "expected condition in parenthesis");
2080 if (parser->tok != '(') {
2081 parseerror(parser, "expected 'if' condition in parenthesis");
2084 /* parse into the expression */
2085 if (!parser_next(parser)) {
2086 parseerror(parser, "expected 'if' condition after opening paren");
2089 /* parse the condition */
2090 cond = parse_expression_leave(parser, false, true, false);
2094 if (parser->tok != ')') {
2095 parseerror(parser, "expected closing paren after 'if' condition");
2099 /* parse into the 'then' branch */
2100 if (!parser_next(parser)) {
2101 parseerror(parser, "expected statement for on-true branch of 'if'");
2105 if (!parse_statement_or_block(parser, &ontrue)) {
2110 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2111 /* check for an else */
2112 if (!strcmp(parser_tokval(parser), "else")) {
2113 /* parse into the 'else' branch */
2114 if (!parser_next(parser)) {
2115 parseerror(parser, "expected on-false branch after 'else'");
2120 if (!parse_statement_or_block(parser, &onfalse)) {
2127 cond = process_condition(parser, cond, &ifnot);
2129 if (ontrue) ast_delete(ontrue);
2130 if (onfalse) ast_delete(onfalse);
2135 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2137 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2138 *out = (ast_expression*)ifthen;
2142 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2143 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2148 /* skip the 'while' and get the body */
2149 if (!parser_next(parser)) {
2150 if (OPTS_FLAG(LOOP_LABELS))
2151 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2153 parseerror(parser, "expected 'while' condition in parenthesis");
2157 if (parser->tok == ':') {
2158 if (!OPTS_FLAG(LOOP_LABELS))
2159 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2160 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2161 parseerror(parser, "expected loop label");
2164 label = util_strdup(parser_tokval(parser));
2165 if (!parser_next(parser)) {
2167 parseerror(parser, "expected 'while' condition in parenthesis");
2172 if (parser->tok != '(') {
2173 parseerror(parser, "expected 'while' condition in parenthesis");
2177 vec_push(parser->breaks, label);
2178 vec_push(parser->continues, label);
2180 rv = parse_while_go(parser, block, out);
2183 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2184 parseerror(parser, "internal error: label stack corrupted");
2190 vec_pop(parser->breaks);
2191 vec_pop(parser->continues);
2196 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2199 ast_expression *cond, *ontrue;
2203 lex_ctx_t ctx = parser_ctx(parser);
2205 (void)block; /* not touching */
2207 /* parse into the expression */
2208 if (!parser_next(parser)) {
2209 parseerror(parser, "expected 'while' condition after opening paren");
2212 /* parse the condition */
2213 cond = parse_expression_leave(parser, false, true, false);
2217 if (parser->tok != ')') {
2218 parseerror(parser, "expected closing paren after 'while' condition");
2222 /* parse into the 'then' branch */
2223 if (!parser_next(parser)) {
2224 parseerror(parser, "expected while-loop body");
2228 if (!parse_statement_or_block(parser, &ontrue)) {
2233 cond = process_condition(parser, cond, &ifnot);
2238 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2239 *out = (ast_expression*)aloop;
2243 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2244 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2249 /* skip the 'do' and get the body */
2250 if (!parser_next(parser)) {
2251 if (OPTS_FLAG(LOOP_LABELS))
2252 parseerror(parser, "expected loop label or body");
2254 parseerror(parser, "expected loop body");
2258 if (parser->tok == ':') {
2259 if (!OPTS_FLAG(LOOP_LABELS))
2260 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2261 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2262 parseerror(parser, "expected loop label");
2265 label = util_strdup(parser_tokval(parser));
2266 if (!parser_next(parser)) {
2268 parseerror(parser, "expected loop body");
2273 vec_push(parser->breaks, label);
2274 vec_push(parser->continues, label);
2276 rv = parse_dowhile_go(parser, block, out);
2279 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2280 parseerror(parser, "internal error: label stack corrupted");
2283 * Test for NULL otherwise ast_delete dereferences null pointer
2291 vec_pop(parser->breaks);
2292 vec_pop(parser->continues);
2297 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2300 ast_expression *cond, *ontrue;
2304 lex_ctx_t ctx = parser_ctx(parser);
2306 (void)block; /* not touching */
2308 if (!parse_statement_or_block(parser, &ontrue))
2311 /* expect the "while" */
2312 if (parser->tok != TOKEN_KEYWORD ||
2313 strcmp(parser_tokval(parser), "while"))
2315 parseerror(parser, "expected 'while' and condition");
2320 /* skip the 'while' and check for opening paren */
2321 if (!parser_next(parser) || parser->tok != '(') {
2322 parseerror(parser, "expected 'while' condition in parenthesis");
2326 /* parse into the expression */
2327 if (!parser_next(parser)) {
2328 parseerror(parser, "expected 'while' condition after opening paren");
2332 /* parse the condition */
2333 cond = parse_expression_leave(parser, false, true, false);
2337 if (parser->tok != ')') {
2338 parseerror(parser, "expected closing paren after 'while' condition");
2344 if (!parser_next(parser) || parser->tok != ';') {
2345 parseerror(parser, "expected semicolon after condition");
2351 if (!parser_next(parser)) {
2352 parseerror(parser, "parse error");
2358 cond = process_condition(parser, cond, &ifnot);
2363 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2364 *out = (ast_expression*)aloop;
2368 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2369 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2374 /* skip the 'for' and check for opening paren */
2375 if (!parser_next(parser)) {
2376 if (OPTS_FLAG(LOOP_LABELS))
2377 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2379 parseerror(parser, "expected 'for' expressions in parenthesis");
2383 if (parser->tok == ':') {
2384 if (!OPTS_FLAG(LOOP_LABELS))
2385 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2386 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2387 parseerror(parser, "expected loop label");
2390 label = util_strdup(parser_tokval(parser));
2391 if (!parser_next(parser)) {
2393 parseerror(parser, "expected 'for' expressions in parenthesis");
2398 if (parser->tok != '(') {
2399 parseerror(parser, "expected 'for' expressions in parenthesis");
2403 vec_push(parser->breaks, label);
2404 vec_push(parser->continues, label);
2406 rv = parse_for_go(parser, block, out);
2409 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2410 parseerror(parser, "internal error: label stack corrupted");
2416 vec_pop(parser->breaks);
2417 vec_pop(parser->continues);
2421 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2424 ast_expression *initexpr, *cond, *increment, *ontrue;
2429 lex_ctx_t ctx = parser_ctx(parser);
2431 parser_enterblock(parser);
2438 /* parse into the expression */
2439 if (!parser_next(parser)) {
2440 parseerror(parser, "expected 'for' initializer after opening paren");
2445 if (parser->tok == TOKEN_IDENT)
2446 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2448 if (typevar || parser->tok == TOKEN_TYPENAME) {
2450 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2451 if (parsewarning(parser, WARN_EXTENSIONS,
2452 "current standard does not allow variable declarations in for-loop initializers"))
2456 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2459 else if (parser->tok != ';')
2461 initexpr = parse_expression_leave(parser, false, false, false);
2466 /* move on to condition */
2467 if (parser->tok != ';') {
2468 parseerror(parser, "expected semicolon after for-loop initializer");
2471 if (!parser_next(parser)) {
2472 parseerror(parser, "expected for-loop condition");
2476 /* parse the condition */
2477 if (parser->tok != ';') {
2478 cond = parse_expression_leave(parser, false, true, false);
2483 /* move on to incrementor */
2484 if (parser->tok != ';') {
2485 parseerror(parser, "expected semicolon after for-loop initializer");
2488 if (!parser_next(parser)) {
2489 parseerror(parser, "expected for-loop condition");
2493 /* parse the incrementor */
2494 if (parser->tok != ')') {
2495 lex_ctx_t condctx = parser_ctx(parser);
2496 increment = parse_expression_leave(parser, false, false, false);
2499 if (!ast_side_effects(increment)) {
2500 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2506 if (parser->tok != ')') {
2507 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2510 /* parse into the 'then' branch */
2511 if (!parser_next(parser)) {
2512 parseerror(parser, "expected for-loop body");
2515 if (!parse_statement_or_block(parser, &ontrue))
2519 cond = process_condition(parser, cond, &ifnot);
2523 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2524 *out = (ast_expression*)aloop;
2526 if (!parser_leaveblock(parser)) {
2532 if (initexpr) ast_unref(initexpr);
2533 if (cond) ast_unref(cond);
2534 if (increment) ast_unref(increment);
2535 (void)!parser_leaveblock(parser);
2539 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2541 ast_expression *exp = NULL;
2542 ast_expression *var = NULL;
2543 ast_return *ret = NULL;
2544 ast_value *retval = parser->function->return_value;
2545 ast_value *expected = parser->function->vtype;
2547 lex_ctx_t ctx = parser_ctx(parser);
2549 (void)block; /* not touching */
2551 if (!parser_next(parser)) {
2552 parseerror(parser, "expected return expression");
2556 /* return assignments */
2557 if (parser->tok == '=') {
2558 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2559 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2563 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2565 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2566 parseerror(parser, "invalid return type: `%s'", ty1);
2570 if (!parser_next(parser)) {
2571 parseerror(parser, "expected return assignment expression");
2575 if (!(exp = parse_expression_leave(parser, false, false, false)))
2578 /* prepare the return value */
2580 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2581 ast_type_adopt(retval, expected->expression.next);
2582 parser->function->return_value = retval;
2585 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2586 char ty1[1024], ty2[1024];
2587 ast_type_to_string(exp, ty1, sizeof(ty1));
2588 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2589 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2592 /* store to 'return' local variable */
2593 var = (ast_expression*)ast_store_new(
2595 type_store_instr[expected->expression.next->vtype],
2596 (ast_expression*)retval, exp);
2603 if (parser->tok != ';')
2604 parseerror(parser, "missing semicolon after return assignment");
2605 else if (!parser_next(parser))
2606 parseerror(parser, "parse error after return assignment");
2612 if (parser->tok != ';') {
2613 exp = parse_expression(parser, false, false);
2617 if (exp->vtype != TYPE_NIL &&
2618 exp->vtype != ((ast_expression*)expected)->next->vtype)
2620 parseerror(parser, "return with invalid expression");
2623 ret = ast_return_new(ctx, exp);
2629 if (!parser_next(parser))
2630 parseerror(parser, "parse error");
2632 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2634 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2636 ret = ast_return_new(ctx, (ast_expression*)retval);
2638 *out = (ast_expression*)ret;
2642 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2645 unsigned int levels = 0;
2646 lex_ctx_t ctx = parser_ctx(parser);
2647 const char **loops = (is_continue ? parser->continues : parser->breaks);
2649 (void)block; /* not touching */
2650 if (!parser_next(parser)) {
2651 parseerror(parser, "expected semicolon or loop label");
2655 if (!vec_size(loops)) {
2657 parseerror(parser, "`continue` can only be used inside loops");
2659 parseerror(parser, "`break` can only be used inside loops or switches");
2662 if (parser->tok == TOKEN_IDENT) {
2663 if (!OPTS_FLAG(LOOP_LABELS))
2664 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2665 i = vec_size(loops);
2667 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2670 parseerror(parser, "no such loop to %s: `%s`",
2671 (is_continue ? "continue" : "break out of"),
2672 parser_tokval(parser));
2677 if (!parser_next(parser)) {
2678 parseerror(parser, "expected semicolon");
2683 if (parser->tok != ';') {
2684 parseerror(parser, "expected semicolon");
2688 if (!parser_next(parser))
2689 parseerror(parser, "parse error");
2691 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2695 /* returns true when it was a variable qualifier, false otherwise!
2696 * on error, cvq is set to CV_WRONG
2698 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2700 bool had_const = false;
2701 bool had_var = false;
2702 bool had_noref = false;
2703 bool had_attrib = false;
2704 bool had_static = false;
2709 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2711 /* parse an attribute */
2712 if (!parser_next(parser)) {
2713 parseerror(parser, "expected attribute after `[[`");
2717 if (!strcmp(parser_tokval(parser), "noreturn")) {
2718 flags |= AST_FLAG_NORETURN;
2719 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2720 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2725 else if (!strcmp(parser_tokval(parser), "noref")) {
2727 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2728 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2733 else if (!strcmp(parser_tokval(parser), "inline")) {
2734 flags |= AST_FLAG_INLINE;
2735 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2736 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2741 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2742 flags |= AST_FLAG_ALIAS;
2745 if (!parser_next(parser)) {
2746 parseerror(parser, "parse error in attribute");
2750 if (parser->tok == '(') {
2751 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2752 parseerror(parser, "`alias` attribute missing parameter");
2756 *message = util_strdup(parser_tokval(parser));
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "parse error in attribute");
2763 if (parser->tok != ')') {
2764 parseerror(parser, "`alias` attribute expected `)` after parameter");
2768 if (!parser_next(parser)) {
2769 parseerror(parser, "parse error in attribute");
2774 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2775 parseerror(parser, "`alias` attribute expected `]]`");
2779 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2780 flags |= AST_FLAG_DEPRECATED;
2783 if (!parser_next(parser)) {
2784 parseerror(parser, "parse error in attribute");
2788 if (parser->tok == '(') {
2789 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2790 parseerror(parser, "`deprecated` attribute missing parameter");
2794 *message = util_strdup(parser_tokval(parser));
2796 if (!parser_next(parser)) {
2797 parseerror(parser, "parse error in attribute");
2801 if(parser->tok != ')') {
2802 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "parse error in attribute");
2812 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2813 parseerror(parser, "`deprecated` attribute expected `]]`");
2816 if (*message) mem_d(*message);
2824 /* Skip tokens until we hit a ]] */
2825 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2826 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2827 if (!parser_next(parser)) {
2828 parseerror(parser, "error inside attribute");
2835 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2837 else if (!strcmp(parser_tokval(parser), "const"))
2839 else if (!strcmp(parser_tokval(parser), "var"))
2841 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2843 else if (!strcmp(parser_tokval(parser), "noref"))
2845 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2850 if (!parser_next(parser))
2860 *is_static = had_static;
2864 parseerror(parser, "parse error after variable qualifier");
2869 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2870 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2875 /* skip the 'while' and get the body */
2876 if (!parser_next(parser)) {
2877 if (OPTS_FLAG(LOOP_LABELS))
2878 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2880 parseerror(parser, "expected 'switch' operand in parenthesis");
2884 if (parser->tok == ':') {
2885 if (!OPTS_FLAG(LOOP_LABELS))
2886 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2887 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2888 parseerror(parser, "expected loop label");
2891 label = util_strdup(parser_tokval(parser));
2892 if (!parser_next(parser)) {
2894 parseerror(parser, "expected 'switch' operand in parenthesis");
2899 if (parser->tok != '(') {
2900 parseerror(parser, "expected 'switch' operand in parenthesis");
2904 vec_push(parser->breaks, label);
2906 rv = parse_switch_go(parser, block, out);
2909 if (vec_last(parser->breaks) != label) {
2910 parseerror(parser, "internal error: label stack corrupted");
2916 vec_pop(parser->breaks);
2921 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2923 ast_expression *operand;
2926 ast_switch *switchnode;
2927 ast_switch_case swcase;
2930 bool noref, is_static;
2931 uint32_t qflags = 0;
2933 lex_ctx_t ctx = parser_ctx(parser);
2935 (void)block; /* not touching */
2938 /* parse into the expression */
2939 if (!parser_next(parser)) {
2940 parseerror(parser, "expected switch operand");
2943 /* parse the operand */
2944 operand = parse_expression_leave(parser, false, false, false);
2948 switchnode = ast_switch_new(ctx, operand);
2951 if (parser->tok != ')') {
2952 ast_delete(switchnode);
2953 parseerror(parser, "expected closing paren after 'switch' operand");
2957 /* parse over the opening paren */
2958 if (!parser_next(parser) || parser->tok != '{') {
2959 ast_delete(switchnode);
2960 parseerror(parser, "expected list of cases");
2964 if (!parser_next(parser)) {
2965 ast_delete(switchnode);
2966 parseerror(parser, "expected 'case' or 'default'");
2970 /* new block; allow some variables to be declared here */
2971 parser_enterblock(parser);
2974 if (parser->tok == TOKEN_IDENT)
2975 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2976 if (typevar || parser->tok == TOKEN_TYPENAME) {
2977 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2978 ast_delete(switchnode);
2983 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2985 if (cvq == CV_WRONG) {
2986 ast_delete(switchnode);
2989 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
2990 ast_delete(switchnode);
2999 while (parser->tok != '}') {
3000 ast_block *caseblock;
3002 if (!strcmp(parser_tokval(parser), "case")) {
3003 if (!parser_next(parser)) {
3004 ast_delete(switchnode);
3005 parseerror(parser, "expected expression for case");
3008 swcase.value = parse_expression_leave(parser, false, false, false);
3009 if (!swcase.value) {
3010 ast_delete(switchnode);
3011 parseerror(parser, "expected expression for case");
3014 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3015 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3016 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3022 else if (!strcmp(parser_tokval(parser), "default")) {
3023 swcase.value = NULL;
3024 if (!parser_next(parser)) {
3025 ast_delete(switchnode);
3026 parseerror(parser, "expected colon");
3031 ast_delete(switchnode);
3032 parseerror(parser, "expected 'case' or 'default'");
3036 /* Now the colon and body */
3037 if (parser->tok != ':') {
3038 if (swcase.value) ast_unref(swcase.value);
3039 ast_delete(switchnode);
3040 parseerror(parser, "expected colon");
3044 if (!parser_next(parser)) {
3045 if (swcase.value) ast_unref(swcase.value);
3046 ast_delete(switchnode);
3047 parseerror(parser, "expected statements or case");
3050 caseblock = ast_block_new(parser_ctx(parser));
3052 if (swcase.value) ast_unref(swcase.value);
3053 ast_delete(switchnode);
3056 swcase.code = (ast_expression*)caseblock;
3057 vec_push(switchnode->cases, swcase);
3059 ast_expression *expr;
3060 if (parser->tok == '}')
3062 if (parser->tok == TOKEN_KEYWORD) {
3063 if (!strcmp(parser_tokval(parser), "case") ||
3064 !strcmp(parser_tokval(parser), "default"))
3069 if (!parse_statement(parser, caseblock, &expr, true)) {
3070 ast_delete(switchnode);
3075 if (!ast_block_add_expr(caseblock, expr)) {
3076 ast_delete(switchnode);
3082 parser_leaveblock(parser);
3085 if (parser->tok != '}') {
3086 ast_delete(switchnode);
3087 parseerror(parser, "expected closing paren of case list");
3090 if (!parser_next(parser)) {
3091 ast_delete(switchnode);
3092 parseerror(parser, "parse error after switch");
3095 *out = (ast_expression*)switchnode;
3099 /* parse computed goto sides */
3100 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3101 ast_expression *on_true;
3102 ast_expression *on_false;
3103 ast_expression *cond;
3108 if (ast_istype(*side, ast_ternary)) {
3109 ast_ternary *tern = (ast_ternary*)*side;
3110 on_true = parse_goto_computed(parser, &tern->on_true);
3111 on_false = parse_goto_computed(parser, &tern->on_false);
3113 if (!on_true || !on_false) {
3114 parseerror(parser, "expected label or expression in ternary");
3115 if (on_true) ast_unref(on_true);
3116 if (on_false) ast_unref(on_false);
3124 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3125 } else if (ast_istype(*side, ast_label)) {
3126 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3127 ast_goto_set_label(gt, ((ast_label*)*side));
3129 return (ast_expression*)gt;
3134 static bool parse_goto(parser_t *parser, ast_expression **out)
3136 ast_goto *gt = NULL;
3137 ast_expression *lbl;
3139 if (!parser_next(parser))
3142 if (parser->tok != TOKEN_IDENT) {
3143 ast_expression *expression;
3145 /* could be an expression i.e computed goto :-) */
3146 if (parser->tok != '(') {
3147 parseerror(parser, "expected label name after `goto`");
3151 /* failed to parse expression for goto */
3152 if (!(expression = parse_expression(parser, false, true)) ||
3153 !(*out = parse_goto_computed(parser, &expression))) {
3154 parseerror(parser, "invalid goto expression");
3156 ast_unref(expression);
3163 /* not computed goto */
3164 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3165 lbl = parser_find_label(parser, gt->name);
3167 if (!ast_istype(lbl, ast_label)) {
3168 parseerror(parser, "internal error: label is not an ast_label");
3172 ast_goto_set_label(gt, (ast_label*)lbl);
3175 vec_push(parser->gotos, gt);
3177 if (!parser_next(parser) || parser->tok != ';') {
3178 parseerror(parser, "semicolon expected after goto label");
3181 if (!parser_next(parser)) {
3182 parseerror(parser, "parse error after goto");
3186 *out = (ast_expression*)gt;
3190 static bool parse_skipwhite(parser_t *parser)
3193 if (!parser_next(parser))
3195 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3196 return parser->tok < TOKEN_ERROR;
3199 static bool parse_eol(parser_t *parser)
3201 if (!parse_skipwhite(parser))
3203 return parser->tok == TOKEN_EOL;
3206 static bool parse_pragma_do(parser_t *parser)
3208 if (!parser_next(parser) ||
3209 parser->tok != TOKEN_IDENT ||
3210 strcmp(parser_tokval(parser), "pragma"))
3212 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3215 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3216 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3220 if (!strcmp(parser_tokval(parser), "noref")) {
3221 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3222 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3225 parser->noref = !!parser_token(parser)->constval.i;
3226 if (!parse_eol(parser)) {
3227 parseerror(parser, "parse error after `noref` pragma");
3233 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3240 static bool parse_pragma(parser_t *parser)
3243 parser->lex->flags.preprocessing = true;
3244 parser->lex->flags.mergelines = true;
3245 rv = parse_pragma_do(parser);
3246 if (parser->tok != TOKEN_EOL) {
3247 parseerror(parser, "junk after pragma");
3250 parser->lex->flags.preprocessing = false;
3251 parser->lex->flags.mergelines = false;
3252 if (!parser_next(parser)) {
3253 parseerror(parser, "parse error after pragma");
3259 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3261 bool noref, is_static;
3263 uint32_t qflags = 0;
3264 ast_value *typevar = NULL;
3265 char *vstring = NULL;
3269 if (parser->tok == TOKEN_IDENT)
3270 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3272 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3274 /* local variable */
3276 parseerror(parser, "cannot declare a variable from here");
3279 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3280 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3283 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3287 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3289 if (cvq == CV_WRONG)
3291 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3293 else if (parser->tok == TOKEN_KEYWORD)
3295 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3300 if (!parser_next(parser)) {
3301 parseerror(parser, "parse error after __builtin_debug_printtype");
3305 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3307 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3308 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3309 if (!parser_next(parser)) {
3310 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3316 if (!parse_statement(parser, block, out, allow_cases))
3319 con_out("__builtin_debug_printtype: got no output node\n");
3322 ast_type_to_string(*out, ty, sizeof(ty));
3323 con_out("__builtin_debug_printtype: `%s`\n", ty);
3328 else if (!strcmp(parser_tokval(parser), "return"))
3330 return parse_return(parser, block, out);
3332 else if (!strcmp(parser_tokval(parser), "if"))
3334 return parse_if(parser, block, out);
3336 else if (!strcmp(parser_tokval(parser), "while"))
3338 return parse_while(parser, block, out);
3340 else if (!strcmp(parser_tokval(parser), "do"))
3342 return parse_dowhile(parser, block, out);
3344 else if (!strcmp(parser_tokval(parser), "for"))
3346 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3347 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3350 return parse_for(parser, block, out);
3352 else if (!strcmp(parser_tokval(parser), "break"))
3354 return parse_break_continue(parser, block, out, false);
3356 else if (!strcmp(parser_tokval(parser), "continue"))
3358 return parse_break_continue(parser, block, out, true);
3360 else if (!strcmp(parser_tokval(parser), "switch"))
3362 return parse_switch(parser, block, out);
3364 else if (!strcmp(parser_tokval(parser), "case") ||
3365 !strcmp(parser_tokval(parser), "default"))
3368 parseerror(parser, "unexpected 'case' label");
3373 else if (!strcmp(parser_tokval(parser), "goto"))
3375 return parse_goto(parser, out);
3377 else if (!strcmp(parser_tokval(parser), "typedef"))
3379 if (!parser_next(parser)) {
3380 parseerror(parser, "expected type definition after 'typedef'");
3383 return parse_typedef(parser);
3385 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3388 else if (parser->tok == '{')
3391 inner = parse_block(parser);
3394 *out = (ast_expression*)inner;
3397 else if (parser->tok == ':')
3401 if (!parser_next(parser)) {
3402 parseerror(parser, "expected label name");
3405 if (parser->tok != TOKEN_IDENT) {
3406 parseerror(parser, "label must be an identifier");
3409 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3411 if (!label->undefined) {
3412 parseerror(parser, "label `%s` already defined", label->name);
3415 label->undefined = false;
3418 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3419 vec_push(parser->labels, label);
3421 *out = (ast_expression*)label;
3422 if (!parser_next(parser)) {
3423 parseerror(parser, "parse error after label");
3426 for (i = 0; i < vec_size(parser->gotos); ++i) {
3427 if (!strcmp(parser->gotos[i]->name, label->name)) {
3428 ast_goto_set_label(parser->gotos[i], label);
3429 vec_remove(parser->gotos, i, 1);
3435 else if (parser->tok == ';')
3437 if (!parser_next(parser)) {
3438 parseerror(parser, "parse error after empty statement");
3445 lex_ctx_t ctx = parser_ctx(parser);
3446 ast_expression *exp = parse_expression(parser, false, false);
3450 if (!ast_side_effects(exp)) {
3451 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3458 static bool parse_enum(parser_t *parser)
3461 bool reverse = false;
3463 ast_value **values = NULL;
3464 ast_value *var = NULL;
3467 ast_expression *old;
3469 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3470 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3474 /* enumeration attributes (can add more later) */
3475 if (parser->tok == ':') {
3476 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3477 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3482 if (!strcmp(parser_tokval(parser), "flag")) {
3486 else if (!strcmp(parser_tokval(parser), "reverse")) {
3490 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3494 if (!parser_next(parser) || parser->tok != '{') {
3495 parseerror(parser, "expected `{` after enum attribute ");
3501 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3502 if (parser->tok == '}') {
3503 /* allow an empty enum */
3506 parseerror(parser, "expected identifier or `}`");
3510 old = parser_find_field(parser, parser_tokval(parser));
3512 old = parser_find_global(parser, parser_tokval(parser));
3514 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3515 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3519 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3520 vec_push(values, var);
3521 var->cvq = CV_CONST;
3522 var->hasvalue = true;
3524 /* for flagged enumerations increment in POTs of TWO */
3525 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3526 parser_addglobal(parser, var->name, (ast_expression*)var);
3528 if (!parser_next(parser)) {
3529 parseerror(parser, "expected `=`, `}` or comma after identifier");
3533 if (parser->tok == ',')
3535 if (parser->tok == '}')
3537 if (parser->tok != '=') {
3538 parseerror(parser, "expected `=`, `}` or comma after identifier");
3542 if (!parser_next(parser)) {
3543 parseerror(parser, "expected expression after `=`");
3547 /* We got a value! */
3548 old = parse_expression_leave(parser, true, false, false);
3549 asvalue = (ast_value*)old;
3550 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3551 compile_error(ast_ctx(var), "constant value or expression expected");
3554 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3556 if (parser->tok == '}')
3558 if (parser->tok != ',') {
3559 parseerror(parser, "expected `}` or comma after expression");
3564 /* patch them all (for reversed attribute) */
3567 for (i = 0; i < vec_size(values); i++)
3568 values[i]->constval.vfloat = vec_size(values) - i - 1;
3571 if (parser->tok != '}') {
3572 parseerror(parser, "internal error: breaking without `}`");
3576 if (!parser_next(parser) || parser->tok != ';') {
3577 parseerror(parser, "expected semicolon after enumeration");
3581 if (!parser_next(parser)) {
3582 parseerror(parser, "parse error after enumeration");
3594 static bool parse_block_into(parser_t *parser, ast_block *block)
3598 parser_enterblock(parser);
3600 if (!parser_next(parser)) { /* skip the '{' */
3601 parseerror(parser, "expected function body");
3605 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3607 ast_expression *expr = NULL;
3608 if (parser->tok == '}')
3611 if (!parse_statement(parser, block, &expr, false)) {
3612 /* parseerror(parser, "parse error"); */
3618 if (!ast_block_add_expr(block, expr)) {
3625 if (parser->tok != '}') {
3628 (void)parser_next(parser);
3632 if (!parser_leaveblock(parser))
3634 return retval && !!block;
3637 static ast_block* parse_block(parser_t *parser)
3640 block = ast_block_new(parser_ctx(parser));
3643 if (!parse_block_into(parser, block)) {
3644 ast_block_delete(block);
3650 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3652 if (parser->tok == '{') {
3653 *out = (ast_expression*)parse_block(parser);
3656 return parse_statement(parser, NULL, out, false);
3659 static bool create_vector_members(ast_value *var, ast_member **me)
3662 size_t len = strlen(var->name);
3664 for (i = 0; i < 3; ++i) {
3665 char *name = (char*)mem_a(len+3);
3666 memcpy(name, var->name, len);
3668 name[len+1] = 'x'+i;
3670 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3679 do { ast_member_delete(me[--i]); } while(i);
3683 static bool parse_function_body(parser_t *parser, ast_value *var)
3685 ast_block *block = NULL;
3690 ast_expression *framenum = NULL;
3691 ast_expression *nextthink = NULL;
3692 /* None of the following have to be deleted */
3693 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3694 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3695 bool has_frame_think;
3699 has_frame_think = false;
3700 old = parser->function;
3702 if (var->expression.flags & AST_FLAG_ALIAS) {
3703 parseerror(parser, "function aliases cannot have bodies");
3707 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3708 parseerror(parser, "gotos/labels leaking");
3712 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3713 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3714 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3720 if (parser->tok == '[') {
3721 /* got a frame definition: [ framenum, nextthink ]
3722 * this translates to:
3723 * self.frame = framenum;
3724 * self.nextthink = time + 0.1;
3725 * self.think = nextthink;
3729 fld_think = parser_find_field(parser, "think");
3730 fld_nextthink = parser_find_field(parser, "nextthink");
3731 fld_frame = parser_find_field(parser, "frame");
3732 if (!fld_think || !fld_nextthink || !fld_frame) {
3733 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3734 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3737 gbl_time = parser_find_global(parser, "time");
3738 gbl_self = parser_find_global(parser, "self");
3739 if (!gbl_time || !gbl_self) {
3740 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3741 parseerror(parser, "please declare the following globals: `time`, `self`");
3745 if (!parser_next(parser))
3748 framenum = parse_expression_leave(parser, true, false, false);
3750 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3753 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3754 ast_unref(framenum);
3755 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3759 if (parser->tok != ',') {
3760 ast_unref(framenum);
3761 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3762 parseerror(parser, "Got a %i\n", parser->tok);
3766 if (!parser_next(parser)) {
3767 ast_unref(framenum);
3771 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3773 /* qc allows the use of not-yet-declared functions here
3774 * - this automatically creates a prototype */
3775 ast_value *thinkfunc;
3776 ast_expression *functype = fld_think->next;
3778 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3779 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3780 ast_unref(framenum);
3781 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3784 ast_type_adopt(thinkfunc, functype);
3786 if (!parser_next(parser)) {
3787 ast_unref(framenum);
3788 ast_delete(thinkfunc);
3792 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3794 nextthink = (ast_expression*)thinkfunc;
3797 nextthink = parse_expression_leave(parser, true, false, false);
3799 ast_unref(framenum);
3800 parseerror(parser, "expected a think-function in [frame,think] notation");
3805 if (!ast_istype(nextthink, ast_value)) {
3806 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3810 if (retval && parser->tok != ']') {
3811 parseerror(parser, "expected closing `]` for [frame,think] notation");
3815 if (retval && !parser_next(parser)) {
3819 if (retval && parser->tok != '{') {
3820 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3825 ast_unref(nextthink);
3826 ast_unref(framenum);
3830 has_frame_think = true;
3833 block = ast_block_new(parser_ctx(parser));
3835 parseerror(parser, "failed to allocate block");
3836 if (has_frame_think) {
3837 ast_unref(nextthink);
3838 ast_unref(framenum);
3843 if (has_frame_think) {
3845 ast_expression *self_frame;
3846 ast_expression *self_nextthink;
3847 ast_expression *self_think;
3848 ast_expression *time_plus_1;
3849 ast_store *store_frame;
3850 ast_store *store_nextthink;
3851 ast_store *store_think;
3853 ctx = parser_ctx(parser);
3854 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3855 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3856 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3858 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3859 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1));
3861 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3862 if (self_frame) ast_delete(self_frame);
3863 if (self_nextthink) ast_delete(self_nextthink);
3864 if (self_think) ast_delete(self_think);
3865 if (time_plus_1) ast_delete(time_plus_1);
3871 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3872 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3873 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3876 ast_delete(self_frame);
3879 if (!store_nextthink) {
3880 ast_delete(self_nextthink);
3884 ast_delete(self_think);
3888 if (store_frame) ast_delete(store_frame);
3889 if (store_nextthink) ast_delete(store_nextthink);
3890 if (store_think) ast_delete(store_think);
3893 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3894 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3895 !ast_block_add_expr(block, (ast_expression*)store_think))
3902 parseerror(parser, "failed to generate code for [frame,think]");
3903 ast_unref(nextthink);
3904 ast_unref(framenum);
3910 if (var->hasvalue) {
3911 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3912 ast_block_delete(block);
3916 func = ast_function_new(ast_ctx(var), var->name, var);
3918 parseerror(parser, "failed to allocate function for `%s`", var->name);
3919 ast_block_delete(block);
3922 vec_push(parser->functions, func);
3924 parser_enterblock(parser);
3926 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3928 ast_value *param = var->expression.params[parami];
3931 if (param->expression.vtype != TYPE_VECTOR &&
3932 (param->expression.vtype != TYPE_FIELD ||
3933 param->expression.next->vtype != TYPE_VECTOR))
3938 if (!create_vector_members(param, me)) {
3939 ast_block_delete(block);
3943 for (e = 0; e < 3; ++e) {
3944 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3945 ast_block_collect(block, (ast_expression*)me[e]);
3949 if (var->argcounter) {
3950 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3951 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3955 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3957 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3958 varargs->expression.flags |= AST_FLAG_IS_VARARG;
3959 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3960 varargs->expression.count = 0;
3961 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
3962 if (!parser_create_array_setter_proto(parser, varargs, name)) {
3963 ast_delete(varargs);
3964 ast_block_delete(block);
3967 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
3968 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
3969 ast_delete(varargs);
3970 ast_block_delete(block);
3973 func->varargs = varargs;
3974 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
3977 parser->function = func;
3978 if (!parse_block_into(parser, block)) {
3979 ast_block_delete(block);
3983 vec_push(func->blocks, block);
3986 parser->function = old;
3987 if (!parser_leaveblock(parser))
3989 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3990 parseerror(parser, "internal error: local scopes left");
3994 if (parser->tok == ';')
3995 return parser_next(parser);
3996 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
3997 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4001 (void)!parser_leaveblock(parser);
4002 vec_pop(parser->functions);
4003 ast_function_delete(func);
4004 var->constval.vfunc = NULL;
4007 parser->function = old;
4011 static ast_expression *array_accessor_split(
4016 ast_expression *left,
4017 ast_expression *right
4023 lex_ctx_t ctx = ast_ctx(array);
4025 if (!left || !right) {
4026 if (left) ast_delete(left);
4027 if (right) ast_delete(right);
4031 cmp = ast_binary_new(ctx, INSTR_LT,
4032 (ast_expression*)index,
4033 (ast_expression*)fold_constgen_float(parser->fold, middle));
4037 parseerror(parser, "internal error: failed to create comparison for array setter");
4041 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4043 ast_delete(cmp); /* will delete left and right */
4044 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4048 return (ast_expression*)ifthen;
4051 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4053 lex_ctx_t ctx = ast_ctx(array);
4055 if (from+1 == afterend) {
4056 /* set this value */
4059 ast_array_index *subscript;
4061 int assignop = type_store_instr[value->expression.vtype];
4063 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4064 assignop = INSTR_STORE_V;
4066 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4070 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4072 ast_delete(subscript);
4076 block = ast_block_new(ctx);
4082 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4087 ret = ast_return_new(ctx, NULL);
4093 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4098 return (ast_expression*)block;
4100 ast_expression *left, *right;
4101 size_t diff = afterend - from;
4102 size_t middle = from + diff/2;
4103 left = array_setter_node(parser, array, index, value, from, middle);
4104 right = array_setter_node(parser, array, index, value, middle, afterend);
4105 return array_accessor_split(parser, array, index, middle, left, right);
4109 static ast_expression *array_field_setter_node(
4118 lex_ctx_t ctx = ast_ctx(array);
4120 if (from+1 == afterend) {
4121 /* set this value */
4124 ast_entfield *entfield;
4125 ast_array_index *subscript;
4127 int assignop = type_storep_instr[value->expression.vtype];
4129 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4130 assignop = INSTR_STOREP_V;
4132 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4136 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4137 subscript->expression.vtype = TYPE_FIELD;
4139 entfield = ast_entfield_new_force(ctx,
4140 (ast_expression*)entity,
4141 (ast_expression*)subscript,
4142 (ast_expression*)subscript);
4144 ast_delete(subscript);
4148 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4150 ast_delete(entfield);
4154 block = ast_block_new(ctx);
4160 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4165 ret = ast_return_new(ctx, NULL);
4171 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4176 return (ast_expression*)block;
4178 ast_expression *left, *right;
4179 size_t diff = afterend - from;
4180 size_t middle = from + diff/2;
4181 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4182 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4183 return array_accessor_split(parser, array, index, middle, left, right);
4187 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4189 lex_ctx_t ctx = ast_ctx(array);
4191 if (from+1 == afterend) {
4193 ast_array_index *subscript;
4195 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4199 ret = ast_return_new(ctx, (ast_expression*)subscript);
4201 ast_delete(subscript);
4205 return (ast_expression*)ret;
4207 ast_expression *left, *right;
4208 size_t diff = afterend - from;
4209 size_t middle = from + diff/2;
4210 left = array_getter_node(parser, array, index, from, middle);
4211 right = array_getter_node(parser, array, index, middle, afterend);
4212 return array_accessor_split(parser, array, index, middle, left, right);
4216 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4218 ast_function *func = NULL;
4219 ast_value *fval = NULL;
4220 ast_block *body = NULL;
4222 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4224 parseerror(parser, "failed to create accessor function value");
4228 func = ast_function_new(ast_ctx(array), funcname, fval);
4231 parseerror(parser, "failed to create accessor function node");
4235 body = ast_block_new(ast_ctx(array));
4237 parseerror(parser, "failed to create block for array accessor");
4243 vec_push(func->blocks, body);
4246 vec_push(parser->accessors, fval);
4251 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4253 ast_value *index = NULL;
4254 ast_value *value = NULL;
4258 if (!ast_istype(array->expression.next, ast_value)) {
4259 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4263 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4265 func = fval->constval.vfunc;
4266 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4268 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4269 value = ast_value_copy((ast_value*)array->expression.next);
4271 if (!index || !value) {
4272 parseerror(parser, "failed to create locals for array accessor");
4275 (void)!ast_value_set_name(value, "value"); /* not important */
4276 vec_push(fval->expression.params, index);
4277 vec_push(fval->expression.params, value);
4279 array->setter = fval;
4282 if (index) ast_delete(index);
4283 if (value) ast_delete(value);
4289 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4291 ast_expression *root = NULL;
4292 root = array_setter_node(parser, array,
4293 array->setter->expression.params[0],
4294 array->setter->expression.params[1],
4295 0, array->expression.count);
4297 parseerror(parser, "failed to build accessor search tree");
4300 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4307 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4309 if (!parser_create_array_setter_proto(parser, array, funcname))
4311 return parser_create_array_setter_impl(parser, array);
4314 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4316 ast_expression *root = NULL;
4317 ast_value *entity = NULL;
4318 ast_value *index = NULL;
4319 ast_value *value = NULL;
4323 if (!ast_istype(array->expression.next, ast_value)) {
4324 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4328 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4330 func = fval->constval.vfunc;
4331 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4333 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4334 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4335 value = ast_value_copy((ast_value*)array->expression.next);
4336 if (!entity || !index || !value) {
4337 parseerror(parser, "failed to create locals for array accessor");
4340 (void)!ast_value_set_name(value, "value"); /* not important */
4341 vec_push(fval->expression.params, entity);
4342 vec_push(fval->expression.params, index);
4343 vec_push(fval->expression.params, value);
4345 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4347 parseerror(parser, "failed to build accessor search tree");
4351 array->setter = fval;
4352 return ast_block_add_expr(func->blocks[0], root);
4354 if (entity) ast_delete(entity);
4355 if (index) ast_delete(index);
4356 if (value) ast_delete(value);
4357 if (root) ast_delete(root);
4363 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4365 ast_value *index = NULL;
4369 /* NOTE: checking array->expression.next rather than elemtype since
4370 * for fields elemtype is a temporary fieldtype.
4372 if (!ast_istype(array->expression.next, ast_value)) {
4373 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4377 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4379 func = fval->constval.vfunc;
4380 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4382 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4385 parseerror(parser, "failed to create locals for array accessor");
4388 vec_push(fval->expression.params, index);
4390 array->getter = fval;
4393 if (index) ast_delete(index);
4399 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4401 ast_expression *root = NULL;
4403 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4405 parseerror(parser, "failed to build accessor search tree");
4408 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4415 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4417 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4419 return parser_create_array_getter_impl(parser, array);
4422 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4423 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4431 bool variadic = false;
4432 ast_value *varparam = NULL;
4433 char *argcounter = NULL;
4435 ctx = parser_ctx(parser);
4437 /* for the sake of less code we parse-in in this function */
4438 if (!parser_next(parser)) {
4440 parseerror(parser, "expected parameter list");
4446 /* parse variables until we hit a closing paren */
4447 while (parser->tok != ')') {
4449 /* there must be commas between them */
4450 if (parser->tok != ',') {
4451 parseerror(parser, "expected comma or end of parameter list");
4454 if (!parser_next(parser)) {
4455 parseerror(parser, "expected parameter");
4461 if (parser->tok == TOKEN_DOTS) {
4462 /* '...' indicates a varargs function */
4464 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4465 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4468 if (parser->tok == TOKEN_IDENT) {
4469 argcounter = util_strdup(parser_tokval(parser));
4470 if (!parser_next(parser) || parser->tok != ')') {
4471 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4478 /* for anything else just parse a typename */
4479 param = parse_typename(parser, NULL, NULL);
4482 vec_push(params, param);
4483 if (param->expression.vtype >= TYPE_VARIANT) {
4484 char tname[1024]; /* typename is reserved in C++ */
4485 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4486 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4489 /* type-restricted varargs */
4490 if (parser->tok == TOKEN_DOTS) {
4492 varparam = vec_last(params);
4494 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4495 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4498 if (parser->tok == TOKEN_IDENT) {
4499 argcounter = util_strdup(parser_tokval(parser));
4500 if (!parser_next(parser) || parser->tok != ')') {
4501 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4509 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4513 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4514 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4517 if (!parser_next(parser)) {
4518 parseerror(parser, "parse error after typename");
4522 /* now turn 'var' into a function type */
4523 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4524 fval->expression.next = (ast_expression*)var;
4526 fval->expression.flags |= AST_FLAG_VARIADIC;
4529 var->expression.params = params;
4530 var->expression.varparam = (ast_expression*)varparam;
4531 var->argcounter = argcounter;
4540 ast_delete(varparam);
4542 for (i = 0; i < vec_size(params); ++i)
4543 ast_delete(params[i]);
4548 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4550 ast_expression *cexp;
4551 ast_value *cval, *tmp;
4554 ctx = parser_ctx(parser);
4556 if (!parser_next(parser)) {
4558 parseerror(parser, "expected array-size");
4562 if (parser->tok != ']') {
4563 cexp = parse_expression_leave(parser, true, false, false);
4565 if (!cexp || !ast_istype(cexp, ast_value)) {
4569 parseerror(parser, "expected array-size as constant positive integer");
4572 cval = (ast_value*)cexp;
4579 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4580 tmp->expression.next = (ast_expression*)var;
4584 if (cval->expression.vtype == TYPE_INTEGER)
4585 tmp->expression.count = cval->constval.vint;
4586 else if (cval->expression.vtype == TYPE_FLOAT)
4587 tmp->expression.count = cval->constval.vfloat;
4591 parseerror(parser, "array-size must be a positive integer constant");
4597 var->expression.count = -1;
4598 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4601 if (parser->tok != ']') {
4603 parseerror(parser, "expected ']' after array-size");
4606 if (!parser_next(parser)) {
4608 parseerror(parser, "error after parsing array size");
4614 /* Parse a complete typename.
4615 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4616 * but when parsing variables separated by comma
4617 * 'storebase' should point to where the base-type should be kept.
4618 * The base type makes up every bit of type information which comes *before* the
4621 * The following will be parsed in its entirety:
4623 * The 'basetype' in this case is 'void()'
4624 * and if there's a comma after it, say:
4626 * then the type-information 'void()' can be stored in 'storebase'
4628 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4630 ast_value *var, *tmp;
4633 const char *name = NULL;
4634 bool isfield = false;
4635 bool wasarray = false;
4636 size_t morefields = 0;
4638 ctx = parser_ctx(parser);
4640 /* types may start with a dot */
4641 if (parser->tok == '.') {
4643 /* if we parsed a dot we need a typename now */
4644 if (!parser_next(parser)) {
4645 parseerror(parser, "expected typename for field definition");
4649 /* Further dots are handled seperately because they won't be part of the
4652 while (parser->tok == '.') {
4654 if (!parser_next(parser)) {
4655 parseerror(parser, "expected typename for field definition");
4660 if (parser->tok == TOKEN_IDENT)
4661 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4662 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4663 parseerror(parser, "expected typename");
4667 /* generate the basic type value */
4668 if (cached_typedef) {
4669 var = ast_value_copy(cached_typedef);
4670 ast_value_set_name(var, "<type(from_def)>");
4672 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4674 for (; morefields; --morefields) {
4675 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4676 tmp->expression.next = (ast_expression*)var;
4680 /* do not yet turn into a field - remember:
4681 * .void() foo; is a field too
4682 * .void()() foo; is a function
4686 if (!parser_next(parser)) {
4688 parseerror(parser, "parse error after typename");
4692 /* an opening paren now starts the parameter-list of a function
4693 * this is where original-QC has parameter lists.
4694 * We allow a single parameter list here.
4695 * Much like fteqcc we don't allow `float()() x`
4697 if (parser->tok == '(') {
4698 var = parse_parameter_list(parser, var);
4703 /* store the base if requested */
4705 *storebase = ast_value_copy(var);
4707 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4708 tmp->expression.next = (ast_expression*)*storebase;
4713 /* there may be a name now */
4714 if (parser->tok == TOKEN_IDENT) {
4715 name = util_strdup(parser_tokval(parser));
4717 if (!parser_next(parser)) {
4720 parseerror(parser, "error after variable or field declaration");
4725 /* now this may be an array */
4726 if (parser->tok == '[') {
4728 var = parse_arraysize(parser, var);
4730 if (name) mem_d(name);
4735 /* This is the point where we can turn it into a field */
4737 /* turn it into a field if desired */
4738 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4739 tmp->expression.next = (ast_expression*)var;
4743 /* now there may be function parens again */
4744 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4745 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4746 if (parser->tok == '(' && wasarray)
4747 parseerror(parser, "arrays as part of a return type is not supported");
4748 while (parser->tok == '(') {
4749 var = parse_parameter_list(parser, var);
4751 if (name) mem_d(name);
4756 /* finally name it */
4758 if (!ast_value_set_name(var, name)) {
4761 parseerror(parser, "internal error: failed to set name");
4764 /* free the name, ast_value_set_name duplicates */
4771 static bool parse_typedef(parser_t *parser)
4773 ast_value *typevar, *oldtype;
4774 ast_expression *old;
4776 typevar = parse_typename(parser, NULL, NULL);
4781 if ( (old = parser_find_var(parser, typevar->name)) ) {
4782 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4783 " -> `%s` has been declared here: %s:%i",
4784 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4785 ast_delete(typevar);
4789 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4790 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4791 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4792 ast_delete(typevar);
4796 vec_push(parser->_typedefs, typevar);
4797 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4799 if (parser->tok != ';') {
4800 parseerror(parser, "expected semicolon after typedef");
4803 if (!parser_next(parser)) {
4804 parseerror(parser, "parse error after typedef");
4811 static const char *cvq_to_str(int cvq) {
4813 case CV_NONE: return "none";
4814 case CV_VAR: return "`var`";
4815 case CV_CONST: return "`const`";
4816 default: return "<INVALID>";
4820 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4823 if (proto->cvq != var->cvq) {
4824 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4825 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4826 parser->tok == '='))
4828 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4829 "`%s` declared with different qualifiers: %s\n"
4830 " -> previous declaration here: %s:%i uses %s",
4831 var->name, cvq_to_str(var->cvq),
4832 ast_ctx(proto).file, ast_ctx(proto).line,
4833 cvq_to_str(proto->cvq));
4836 av = (var ->expression.flags & AST_FLAG_NORETURN);
4837 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4839 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4840 "`%s` declared with different attributes%s\n"
4841 " -> previous declaration here: %s:%i",
4842 var->name, (av ? ": noreturn" : ""),
4843 ast_ctx(proto).file, ast_ctx(proto).line,
4844 (ao ? ": noreturn" : ""));
4849 static bool create_array_accessors(parser_t *parser, ast_value *var)
4852 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4853 if (!parser_create_array_setter(parser, var, name))
4855 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4856 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4861 static bool parse_array(parser_t *parser, ast_value *array)
4864 if (array->initlist) {
4865 parseerror(parser, "array already initialized elsewhere");
4868 if (!parser_next(parser)) {
4869 parseerror(parser, "parse error in array initializer");
4873 while (parser->tok != '}') {
4874 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4877 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4879 parseerror(parser, "initializing element must be a compile time constant");
4882 vec_push(array->initlist, v->constval);
4883 if (v->expression.vtype == TYPE_STRING) {
4884 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4888 if (parser->tok == '}')
4890 if (parser->tok != ',' || !parser_next(parser)) {
4891 parseerror(parser, "expected comma or '}' in element list");
4895 if (!parser_next(parser) || parser->tok != ';') {
4896 parseerror(parser, "expected semicolon after initializer, got %s");
4900 if (!parser_next(parser)) {
4901 parseerror(parser, "parse error after initializer");
4906 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4907 if (array->expression.count != (size_t)-1) {
4908 parseerror(parser, "array `%s' has already been initialized with %u elements",
4909 array->name, (unsigned)array->expression.count);
4911 array->expression.count = vec_size(array->initlist);
4912 if (!create_array_accessors(parser, array))
4918 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)
4922 ast_expression *old;
4926 ast_value *basetype = NULL;
4928 bool isparam = false;
4929 bool isvector = false;
4930 bool cleanvar = true;
4931 bool wasarray = false;
4933 ast_member *me[3] = { NULL, NULL, NULL };
4935 if (!localblock && is_static)
4936 parseerror(parser, "`static` qualifier is not supported in global scope");
4938 /* get the first complete variable */
4939 var = parse_typename(parser, &basetype, cached_typedef);
4942 ast_delete(basetype);
4950 /* Part 0: finish the type */
4951 if (parser->tok == '(') {
4952 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4953 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4954 var = parse_parameter_list(parser, var);
4960 /* we only allow 1-dimensional arrays */
4961 if (parser->tok == '[') {
4963 var = parse_arraysize(parser, var);
4969 if (parser->tok == '(' && wasarray) {
4970 parseerror(parser, "arrays as part of a return type is not supported");
4971 /* we'll still parse the type completely for now */
4973 /* for functions returning functions */
4974 while (parser->tok == '(') {
4975 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4976 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4977 var = parse_parameter_list(parser, var);
4984 var->cvq = qualifier;
4985 var->expression.flags |= qflags;
4988 * store the vstring back to var for alias and
4989 * deprecation messages.
4991 if (var->expression.flags & AST_FLAG_DEPRECATED ||
4992 var->expression.flags & AST_FLAG_ALIAS)
4993 var->desc = vstring;
4996 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4997 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4998 * is then filled with the previous definition and the parameter-names replaced.
5000 if (!strcmp(var->name, "nil")) {
5001 if (OPTS_FLAG(UNTYPED_NIL)) {
5002 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5003 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5005 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5008 /* Deal with end_sys_ vars */
5010 if (!strcmp(var->name, "end_sys_globals")) {
5012 parser->crc_globals = vec_size(parser->globals);
5015 else if (!strcmp(var->name, "end_sys_fields")) {
5017 parser->crc_fields = vec_size(parser->fields);
5020 if (was_end && var->expression.vtype == TYPE_FIELD) {
5021 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5022 "global '%s' hint should not be a field",
5023 parser_tokval(parser)))
5030 if (!nofields && var->expression.vtype == TYPE_FIELD)
5032 /* deal with field declarations */
5033 old = parser_find_field(parser, var->name);
5035 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5036 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5045 parseerror(parser, "field `%s` already declared here: %s:%i",
5046 var->name, ast_ctx(old).file, ast_ctx(old).line);
5051 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5052 (old = parser_find_global(parser, var->name)))
5054 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5055 parseerror(parser, "field `%s` already declared here: %s:%i",
5056 var->name, ast_ctx(old).file, ast_ctx(old).line);
5063 /* deal with other globals */
5064 old = parser_find_global(parser, var->name);
5065 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5067 /* This is a function which had a prototype */
5068 if (!ast_istype(old, ast_value)) {
5069 parseerror(parser, "internal error: prototype is not an ast_value");
5073 proto = (ast_value*)old;
5074 proto->desc = var->desc;
5075 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5076 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5078 ast_ctx(proto).file, ast_ctx(proto).line);
5082 /* we need the new parameter-names */
5083 for (i = 0; i < vec_size(proto->expression.params); ++i)
5084 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5085 if (!parser_check_qualifiers(parser, var, proto)) {
5092 proto->expression.flags |= var->expression.flags;
5100 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5101 "global `%s` already declared here: %s:%i",
5102 var->name, ast_ctx(old).file, ast_ctx(old).line))
5107 proto = (ast_value*)old;
5108 if (!ast_istype(old, ast_value)) {
5109 parseerror(parser, "internal error: not an ast_value");
5114 if (!parser_check_qualifiers(parser, var, proto)) {
5119 proto->expression.flags |= var->expression.flags;
5123 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5124 (old = parser_find_field(parser, var->name)))
5126 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5127 parseerror(parser, "global `%s` already declared here: %s:%i",
5128 var->name, ast_ctx(old).file, ast_ctx(old).line);
5135 else /* it's not a global */
5137 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5138 if (old && !isparam) {
5139 parseerror(parser, "local `%s` already declared here: %s:%i",
5140 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5144 old = parser_find_local(parser, var->name, 0, &isparam);
5145 if (old && isparam) {
5146 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5147 "local `%s` is shadowing a parameter", var->name))
5149 parseerror(parser, "local `%s` already declared here: %s:%i",
5150 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5154 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5162 /* in a noref section we simply bump the usecount */
5163 if (noref || parser->noref)
5167 * Create the global/local, and deal with vector types.
5170 if (var->expression.vtype == TYPE_VECTOR)
5172 else if (var->expression.vtype == TYPE_FIELD &&
5173 var->expression.next->vtype == TYPE_VECTOR)
5177 if (!create_vector_members(var, me)) {
5184 /* deal with global variables, fields, functions */
5185 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5186 var->isfield = true;
5187 vec_push(parser->fields, (ast_expression*)var);
5188 util_htset(parser->htfields, var->name, var);
5190 for (i = 0; i < 3; ++i) {
5191 vec_push(parser->fields, (ast_expression*)me[i]);
5192 util_htset(parser->htfields, me[i]->name, me[i]);
5197 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5198 parser_addglobal(parser, var->name, (ast_expression*)var);
5200 for (i = 0; i < 3; ++i) {
5201 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5205 ast_expression *find = parser_find_global(parser, var->desc);
5208 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5212 if (var->expression.vtype != find->vtype) {
5216 ast_type_to_string(find, ty1, sizeof(ty1));
5217 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5219 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5226 * add alias to aliases table and to corrector
5227 * so corrections can apply for aliases as well.
5229 util_htset(parser->aliases, var->name, find);
5232 * add to corrector so corrections can work
5233 * even for aliases too.
5236 vec_last(parser->correct_variables),
5237 &vec_last(parser->correct_variables_score),
5241 /* generate aliases for vector components */
5245 util_asprintf(&buffer[0], "%s_x", var->desc);
5246 util_asprintf(&buffer[1], "%s_y", var->desc);
5247 util_asprintf(&buffer[2], "%s_z", var->desc);
5249 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5250 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5251 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5258 * add to corrector so corrections can work
5259 * even for aliases too.
5262 vec_last(parser->correct_variables),
5263 &vec_last(parser->correct_variables_score),
5267 vec_last(parser->correct_variables),
5268 &vec_last(parser->correct_variables_score),
5272 vec_last(parser->correct_variables),
5273 &vec_last(parser->correct_variables_score),
5281 /* a static adds itself to be generated like any other global
5282 * but is added to the local namespace instead
5284 char *defname = NULL;
5285 size_t prefix_len, ln;
5287 ln = strlen(parser->function->name);
5288 vec_append(defname, ln, parser->function->name);
5290 vec_append(defname, 2, "::");
5291 /* remember the length up to here */
5292 prefix_len = vec_size(defname);
5294 /* Add it to the local scope */
5295 util_htset(vec_last(parser->variables), var->name, (void*)var);
5299 vec_last(parser->correct_variables),
5300 &vec_last(parser->correct_variables_score),
5304 /* now rename the global */
5305 ln = strlen(var->name);
5306 vec_append(defname, ln, var->name);
5307 ast_value_set_name(var, defname);
5309 /* push it to the to-be-generated globals */
5310 vec_push(parser->globals, (ast_expression*)var);
5312 /* same game for the vector members */
5314 for (i = 0; i < 3; ++i) {
5315 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5319 vec_last(parser->correct_variables),
5320 &vec_last(parser->correct_variables_score),
5324 vec_shrinkto(defname, prefix_len);
5325 ln = strlen(me[i]->name);
5326 vec_append(defname, ln, me[i]->name);
5327 ast_member_set_name(me[i], defname);
5329 vec_push(parser->globals, (ast_expression*)me[i]);
5334 vec_push(localblock->locals, var);
5335 parser_addlocal(parser, var->name, (ast_expression*)var);
5337 for (i = 0; i < 3; ++i) {
5338 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5339 ast_block_collect(localblock, (ast_expression*)me[i]);
5345 me[0] = me[1] = me[2] = NULL;
5350 if (var->expression.vtype == TYPE_ARRAY) {
5351 if (var->expression.count != (size_t)-1) {
5352 if (!create_array_accessors(parser, var))
5356 else if (!localblock && !nofields &&
5357 var->expression.vtype == TYPE_FIELD &&
5358 var->expression.next->vtype == TYPE_ARRAY)
5361 ast_expression *telem;
5363 ast_value *array = (ast_value*)var->expression.next;
5365 if (!ast_istype(var->expression.next, ast_value)) {
5366 parseerror(parser, "internal error: field element type must be an ast_value");
5370 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5371 if (!parser_create_array_field_setter(parser, array, name))
5374 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5375 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5376 tfield->expression.next = telem;
5377 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5378 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5386 if (parser->tok == ';') {
5387 ast_delete(basetype);
5388 if (!parser_next(parser)) {
5389 parseerror(parser, "error after variable declaration");
5395 if (parser->tok == ',')
5399 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5402 parseerror(parser, "missing comma or semicolon while parsing variables");
5406 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5407 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5408 "initializing expression turns variable `%s` into a constant in this standard",
5415 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5416 if (parser->tok != '=') {
5417 if (!strcmp(parser_tokval(parser), "break")) {
5418 if (!parser_next(parser)) {
5419 parseerror(parser, "error parsing break definition");
5422 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5424 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5429 if (!parser_next(parser)) {
5430 parseerror(parser, "error parsing initializer");
5434 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5435 parseerror(parser, "expected '=' before function body in this standard");
5438 if (parser->tok == '#') {
5439 ast_function *func = NULL;
5440 ast_value *number = NULL;
5446 parseerror(parser, "cannot declare builtins within functions");
5449 if (var->expression.vtype != TYPE_FUNCTION) {
5450 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5453 if (!parser_next(parser)) {
5454 parseerror(parser, "expected builtin number");
5458 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5459 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5461 parseerror(parser, "builtin number expected");
5464 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5467 parseerror(parser, "builtin number must be a compile time constant");
5470 if (number->expression.vtype == TYPE_INTEGER)
5471 builtin_num = number->constval.vint;
5472 else if (number->expression.vtype == TYPE_FLOAT)
5473 builtin_num = number->constval.vfloat;
5476 parseerror(parser, "builtin number must be an integer constant");
5481 fractional = modff(builtin_num, &integral);
5482 if (builtin_num < 0 || fractional != 0) {
5483 parseerror(parser, "builtin number must be an integer greater than zero");
5487 /* we only want the integral part anyways */
5488 builtin_num = integral;
5489 } else if (parser->tok == TOKEN_INTCONST) {
5490 builtin_num = parser_token(parser)->constval.i;
5492 parseerror(parser, "builtin number must be a compile time constant");
5496 if (var->hasvalue) {
5497 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5498 "builtin `%s` has already been defined\n"
5499 " -> previous declaration here: %s:%i",
5500 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5504 func = ast_function_new(ast_ctx(var), var->name, var);
5506 parseerror(parser, "failed to allocate function for `%s`", var->name);
5509 vec_push(parser->functions, func);
5511 func->builtin = -builtin_num-1;
5514 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5515 ? (parser->tok != ',' && parser->tok != ';')
5516 : (!parser_next(parser)))
5518 parseerror(parser, "expected comma or semicolon");
5520 ast_function_delete(func);
5521 var->constval.vfunc = NULL;
5525 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5528 /* Note that fteqcc and most others don't even *have*
5529 * local arrays, so this is not a high priority.
5531 parseerror(parser, "TODO: initializers for local arrays");
5535 var->hasvalue = true;
5536 if (!parse_array(parser, var))
5539 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5542 parseerror(parser, "cannot declare functions within functions");
5547 ast_ctx(proto) = parser_ctx(parser);
5549 if (!parse_function_body(parser, var))
5551 ast_delete(basetype);
5552 for (i = 0; i < vec_size(parser->gotos); ++i)
5553 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5554 vec_free(parser->gotos);
5555 vec_free(parser->labels);
5558 ast_expression *cexp;
5561 cexp = parse_expression_leave(parser, true, false, false);
5566 cval = (ast_value*)cexp;
5567 if (cval != parser->nil &&
5568 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5571 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5575 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5576 qualifier != CV_VAR)
5578 var->cvq = CV_CONST;
5580 if (cval == parser->nil)
5581 var->expression.flags |= AST_FLAG_INITIALIZED;
5584 var->hasvalue = true;
5585 if (cval->expression.vtype == TYPE_STRING)
5586 var->constval.vstring = parser_strdup(cval->constval.vstring);
5587 else if (cval->expression.vtype == TYPE_FIELD)
5588 var->constval.vfield = cval;
5590 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5596 shunt sy = { NULL, NULL, NULL, NULL };
5599 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5600 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5601 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5602 if (!parser_sy_apply_operator(parser, &sy))
5605 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5606 parseerror(parser, "internal error: leaked operands");
5607 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5618 if (parser->tok == ',') {
5619 if (!parser_next(parser)) {
5620 parseerror(parser, "expected another variable");
5624 if (parser->tok != TOKEN_IDENT) {
5625 parseerror(parser, "expected another variable");
5628 var = ast_value_copy(basetype);
5630 ast_value_set_name(var, parser_tokval(parser));
5631 if (!parser_next(parser)) {
5632 parseerror(parser, "error parsing variable declaration");
5638 if (parser->tok != ';') {
5639 parseerror(parser, "missing semicolon after variables");
5643 if (!parser_next(parser)) {
5644 parseerror(parser, "parse error after variable declaration");
5648 ast_delete(basetype);
5652 if (cleanvar && var)
5654 ast_delete(basetype);
5658 ast_delete(basetype);
5659 if (cleanvar && var)
5661 if (me[0]) ast_member_delete(me[0]);
5662 if (me[1]) ast_member_delete(me[1]);
5663 if (me[2]) ast_member_delete(me[2]);
5667 static bool parser_global_statement(parser_t *parser)
5671 bool is_static = false;
5672 uint32_t qflags = 0;
5673 ast_value *istype = NULL;
5674 char *vstring = NULL;
5676 if (parser->tok == TOKEN_IDENT)
5677 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5679 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5681 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5683 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5685 if (cvq == CV_WRONG)
5687 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5689 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5691 return parse_enum(parser);
5693 else if (parser->tok == TOKEN_KEYWORD)
5695 if (!strcmp(parser_tokval(parser), "typedef")) {
5696 if (!parser_next(parser)) {
5697 parseerror(parser, "expected type definition after 'typedef'");
5700 return parse_typedef(parser);
5702 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5705 else if (parser->tok == '#')
5707 return parse_pragma(parser);
5709 else if (parser->tok == '$')
5711 if (!parser_next(parser)) {
5712 parseerror(parser, "parse error");
5718 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5724 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5726 return util_crc16(old, str, strlen(str));
5729 static void progdefs_crc_file(const char *str)
5731 /* write to progdefs.h here */
5735 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5737 old = progdefs_crc_sum(old, str);
5738 progdefs_crc_file(str);
5742 static void generate_checksum(parser_t *parser, ir_builder *ir)
5744 uint16_t crc = 0xFFFF;
5748 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5749 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5751 progdefs_crc_file("\tint\tpad;\n");
5752 progdefs_crc_file("\tint\tofs_return[3];\n");
5753 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5754 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5755 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5756 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5757 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5758 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5759 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5760 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5762 for (i = 0; i < parser->crc_globals; ++i) {
5763 if (!ast_istype(parser->globals[i], ast_value))
5765 value = (ast_value*)(parser->globals[i]);
5766 switch (value->expression.vtype) {
5767 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5768 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5769 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5770 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5772 crc = progdefs_crc_both(crc, "\tint\t");
5775 crc = progdefs_crc_both(crc, value->name);
5776 crc = progdefs_crc_both(crc, ";\n");
5778 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5779 for (i = 0; i < parser->crc_fields; ++i) {
5780 if (!ast_istype(parser->fields[i], ast_value))
5782 value = (ast_value*)(parser->fields[i]);
5783 switch (value->expression.next->vtype) {
5784 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5785 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5786 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5787 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5789 crc = progdefs_crc_both(crc, "\tint\t");
5792 crc = progdefs_crc_both(crc, value->name);
5793 crc = progdefs_crc_both(crc, ";\n");
5795 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5796 ir->code->crc = crc;
5799 parser_t *parser_create()
5802 lex_ctx_t empty_ctx;
5805 parser = (parser_t*)mem_a(sizeof(parser_t));
5809 memset(parser, 0, sizeof(*parser));
5811 for (i = 0; i < operator_count; ++i) {
5812 if (operators[i].id == opid1('=')) {
5813 parser->assign_op = operators+i;
5817 if (!parser->assign_op) {
5818 printf("internal error: initializing parser: failed to find assign operator\n");
5823 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5824 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5825 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5826 vec_push(parser->_blocktypedefs, 0);
5828 parser->aliases = util_htnew(PARSER_HT_SIZE);
5831 vec_push(parser->correct_variables, correct_trie_new());
5832 vec_push(parser->correct_variables_score, NULL);
5834 empty_ctx.file = "<internal>";
5836 empty_ctx.column = 0;
5837 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5838 parser->nil->cvq = CV_CONST;
5839 if (OPTS_FLAG(UNTYPED_NIL))
5840 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5842 parser->max_param_count = 1;
5844 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5845 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5846 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5848 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5849 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5850 parser->reserved_version->cvq = CV_CONST;
5851 parser->reserved_version->hasvalue = true;
5852 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5853 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5855 parser->reserved_version = NULL;
5858 parser->fold = fold_init(parser);
5862 static bool parser_compile(parser_t *parser)
5864 /* initial lexer/parser state */
5865 parser->lex->flags.noops = true;
5867 if (parser_next(parser))
5869 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5871 if (!parser_global_statement(parser)) {
5872 if (parser->tok == TOKEN_EOF)
5873 parseerror(parser, "unexpected end of file");
5874 else if (compile_errors)
5875 parseerror(parser, "there have been errors, bailing out");
5876 lex_close(parser->lex);
5882 parseerror(parser, "parse error");
5883 lex_close(parser->lex);
5888 lex_close(parser->lex);
5891 return !compile_errors;
5894 bool parser_compile_file(parser_t *parser, const char *filename)
5896 parser->lex = lex_open(filename);
5898 con_err("failed to open file \"%s\"\n", filename);
5901 return parser_compile(parser);
5904 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5906 parser->lex = lex_open_string(str, len, name);
5908 con_err("failed to create lexer for string \"%s\"\n", name);
5911 return parser_compile(parser);
5914 static void parser_remove_ast(parser_t *parser)
5917 if (parser->ast_cleaned)
5919 parser->ast_cleaned = true;
5920 for (i = 0; i < vec_size(parser->accessors); ++i) {
5921 ast_delete(parser->accessors[i]->constval.vfunc);
5922 parser->accessors[i]->constval.vfunc = NULL;
5923 ast_delete(parser->accessors[i]);
5925 for (i = 0; i < vec_size(parser->functions); ++i) {
5926 ast_delete(parser->functions[i]);
5928 for (i = 0; i < vec_size(parser->fields); ++i) {
5929 ast_delete(parser->fields[i]);
5931 for (i = 0; i < vec_size(parser->globals); ++i) {
5932 ast_delete(parser->globals[i]);
5934 vec_free(parser->accessors);
5935 vec_free(parser->functions);
5936 vec_free(parser->globals);
5937 vec_free(parser->fields);
5939 for (i = 0; i < vec_size(parser->variables); ++i)
5940 util_htdel(parser->variables[i]);
5941 vec_free(parser->variables);
5942 vec_free(parser->_blocklocals);
5943 vec_free(parser->_locals);
5946 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5947 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5949 vec_free(parser->correct_variables);
5950 vec_free(parser->correct_variables_score);
5952 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5953 ast_delete(parser->_typedefs[i]);
5954 vec_free(parser->_typedefs);
5955 for (i = 0; i < vec_size(parser->typedefs); ++i)
5956 util_htdel(parser->typedefs[i]);
5957 vec_free(parser->typedefs);
5958 vec_free(parser->_blocktypedefs);
5960 vec_free(parser->_block_ctx);
5962 vec_free(parser->labels);
5963 vec_free(parser->gotos);
5964 vec_free(parser->breaks);
5965 vec_free(parser->continues);
5967 ast_value_delete(parser->nil);
5969 ast_value_delete(parser->const_vec[0]);
5970 ast_value_delete(parser->const_vec[1]);
5971 ast_value_delete(parser->const_vec[2]);
5973 if (parser->reserved_version)
5974 ast_value_delete(parser->reserved_version);
5976 util_htdel(parser->aliases);
5977 intrin_intrinsics_destroy(parser);
5978 fold_cleanup(parser->fold);
5981 void parser_cleanup(parser_t *parser)
5983 parser_remove_ast(parser);
5987 bool parser_finish(parser_t *parser, const char *output)
5993 if (compile_errors) {
5994 con_out("*** there were compile errors\n");
5998 ir = ir_builder_new("gmqcc_out");
6000 con_out("failed to allocate builder\n");
6004 for (i = 0; i < vec_size(parser->fields); ++i) {
6007 if (!ast_istype(parser->fields[i], ast_value))
6009 field = (ast_value*)parser->fields[i];
6010 hasvalue = field->hasvalue;
6011 field->hasvalue = false;
6012 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6013 con_out("failed to generate field %s\n", field->name);
6014 ir_builder_delete(ir);
6019 ast_expression *subtype;
6020 field->hasvalue = true;
6021 subtype = field->expression.next;
6022 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6023 if (subtype->vtype == TYPE_FIELD)
6024 ifld->fieldtype = subtype->next->vtype;
6025 else if (subtype->vtype == TYPE_FUNCTION)
6026 ifld->outtype = subtype->next->vtype;
6027 (void)!ir_value_set_field(field->ir_v, ifld);
6030 for (i = 0; i < vec_size(parser->globals); ++i) {
6032 if (!ast_istype(parser->globals[i], ast_value))
6034 asvalue = (ast_value*)(parser->globals[i]);
6035 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6036 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6037 "unused global: `%s`", asvalue->name);
6039 if (!ast_global_codegen(asvalue, ir, false)) {
6040 con_out("failed to generate global %s\n", asvalue->name);
6041 ir_builder_delete(ir);
6045 /* Build function vararg accessor ast tree now before generating
6046 * immediates, because the accessors may add new immediates
6048 for (i = 0; i < vec_size(parser->functions); ++i) {
6049 ast_function *f = parser->functions[i];
6051 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6052 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6053 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6054 con_out("failed to generate vararg setter for %s\n", f->name);
6055 ir_builder_delete(ir);
6058 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6059 con_out("failed to generate vararg getter for %s\n", f->name);
6060 ir_builder_delete(ir);
6064 ast_delete(f->varargs);
6069 /* Now we can generate immediates */
6070 if (!fold_generate(parser->fold, ir))
6073 for (i = 0; i < vec_size(parser->globals); ++i) {
6075 if (!ast_istype(parser->globals[i], ast_value))
6077 asvalue = (ast_value*)(parser->globals[i]);
6078 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6080 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6081 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6082 "uninitialized constant: `%s`",
6084 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6085 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6086 "uninitialized global: `%s`",
6089 if (!ast_generate_accessors(asvalue, ir)) {
6090 ir_builder_delete(ir);
6094 for (i = 0; i < vec_size(parser->fields); ++i) {
6096 asvalue = (ast_value*)(parser->fields[i]->next);
6098 if (!ast_istype((ast_expression*)asvalue, ast_value))
6100 if (asvalue->expression.vtype != TYPE_ARRAY)
6102 if (!ast_generate_accessors(asvalue, ir)) {
6103 ir_builder_delete(ir);
6107 if (parser->reserved_version &&
6108 !ast_global_codegen(parser->reserved_version, ir, false))
6110 con_out("failed to generate reserved::version");
6111 ir_builder_delete(ir);
6114 for (i = 0; i < vec_size(parser->functions); ++i) {
6115 ast_function *f = parser->functions[i];
6116 if (!ast_function_codegen(f, ir)) {
6117 con_out("failed to generate function %s\n", f->name);
6118 ir_builder_delete(ir);
6123 generate_checksum(parser, ir);
6125 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6126 ir_builder_dump(ir, con_out);
6127 for (i = 0; i < vec_size(parser->functions); ++i) {
6128 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6129 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6130 ir_builder_delete(ir);
6134 parser_remove_ast(parser);
6136 if (compile_Werrors) {
6137 con_out("*** there were warnings treated as errors\n");
6138 compile_show_werrors();
6143 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6144 ir_builder_dump(ir, con_out);
6146 if (!ir_builder_generate(ir, output)) {
6147 con_out("*** failed to generate output file\n");
6148 ir_builder_delete(ir);
6152 ir_builder_delete(ir);