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 void parser_enterblock(parser_t *parser);
33 static bool parser_leaveblock(parser_t *parser);
34 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
35 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
36 static bool parse_typedef(parser_t *parser);
37 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);
38 static ast_block* parse_block(parser_t *parser);
39 static bool parse_block_into(parser_t *parser, ast_block *block);
40 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
41 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
42 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
43 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
44 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
45 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
46 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
48 static void parseerror(parser_t *parser, const char *fmt, ...)
52 vcompile_error(parser->lex->tok.ctx, fmt, ap);
56 /* returns true if it counts as an error */
57 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
62 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
67 /**********************************************************************
71 static bool parser_next(parser_t *parser)
73 /* lex_do kills the previous token */
74 parser->tok = lex_do(parser->lex);
75 if (parser->tok == TOKEN_EOF)
77 if (parser->tok >= TOKEN_ERROR) {
78 parseerror(parser, "lex error");
84 #define parser_tokval(p) ((p)->lex->tok.value)
85 #define parser_token(p) (&((p)->lex->tok))
87 char *parser_strdup(const char *str)
90 /* actually dup empty strings */
91 char *out = (char*)mem_a(1);
95 return util_strdup(str);
98 static ast_expression* parser_find_field(parser_t *parser, const char *name)
100 return ( ast_expression*)util_htget(parser->htfields, name);
103 static ast_expression* parser_find_label(parser_t *parser, const char *name)
106 for(i = 0; i < vec_size(parser->labels); i++)
107 if (!strcmp(parser->labels[i]->name, name))
108 return (ast_expression*)parser->labels[i];
112 ast_expression* parser_find_global(parser_t *parser, const char *name)
114 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
117 return (ast_expression*)util_htget(parser->htglobals, name);
120 static ast_expression* parser_find_param(parser_t *parser, const char *name)
124 if (!parser->function)
126 fun = parser->function->vtype;
127 for (i = 0; i < vec_size(fun->expression.params); ++i) {
128 if (!strcmp(fun->expression.params[i]->name, name))
129 return (ast_expression*)(fun->expression.params[i]);
134 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
139 hash = util_hthash(parser->htglobals, name);
142 for (i = vec_size(parser->variables); i > upto;) {
144 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
148 return parser_find_param(parser, name);
151 static ast_expression* parser_find_var(parser_t *parser, const char *name)
155 v = parser_find_local(parser, name, 0, &dummy);
156 if (!v) v = parser_find_global(parser, name);
160 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
164 hash = util_hthash(parser->typedefs[0], name);
166 for (i = vec_size(parser->typedefs); i > upto;) {
168 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 size_t etype; /* 0 = expression, others are operators */
180 ast_block *block; /* for commas and function calls */
199 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
210 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
214 e.out = (ast_expression*)v;
221 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
223 e.etype = 1 + (op - operators);
232 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
243 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
244 * so we need to rotate it to become ent.(foo[n]).
246 static bool rotate_entfield_array_index_nodes(ast_expression **out)
248 ast_array_index *index, *oldindex;
249 ast_entfield *entfield;
253 ast_expression *entity;
255 lex_ctx_t ctx = ast_ctx(*out);
257 if (!ast_istype(*out, ast_array_index))
259 index = (ast_array_index*)*out;
261 if (!ast_istype(index->array, ast_entfield))
263 entfield = (ast_entfield*)index->array;
265 if (!ast_istype(entfield->field, ast_value))
267 field = (ast_value*)entfield->field;
270 entity = entfield->entity;
274 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
275 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
276 *out = (ast_expression*)entfield;
278 oldindex->array = NULL;
279 oldindex->index = NULL;
280 ast_delete(oldindex);
285 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
289 ast_expression *out = NULL;
290 ast_expression *exprs[3];
291 ast_block *blocks[3];
292 ast_value *asvalue[3];
293 ast_binstore *asbinstore;
294 size_t i, assignop, addop, subop;
295 qcint_t generated_op = 0;
300 if (!vec_size(sy->ops)) {
301 parseerror(parser, "internal error: missing operator");
305 if (vec_last(sy->ops).isparen) {
306 parseerror(parser, "unmatched parenthesis");
310 op = &operators[vec_last(sy->ops).etype - 1];
311 ctx = vec_last(sy->ops).ctx;
313 if (vec_size(sy->out) < op->operands) {
314 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
315 op->op, (int)op->id);
319 vec_shrinkby(sy->ops, 1);
321 /* op(:?) has no input and no output */
325 vec_shrinkby(sy->out, op->operands);
326 for (i = 0; i < op->operands; ++i) {
327 exprs[i] = sy->out[vec_size(sy->out)+i].out;
328 blocks[i] = sy->out[vec_size(sy->out)+i].block;
329 asvalue[i] = (ast_value*)exprs[i];
331 if (exprs[i]->vtype == TYPE_NOEXPR &&
332 !(i != 0 && op->id == opid2('?',':')) &&
333 !(i == 1 && op->id == opid1('.')))
335 if (ast_istype(exprs[i], ast_label))
336 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
338 compile_error(ast_ctx(exprs[i]), "not an expression");
339 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
343 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
344 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
348 #define NotSameType(T) \
349 (exprs[0]->vtype != exprs[1]->vtype || \
350 exprs[0]->vtype != T)
354 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
358 if (exprs[0]->vtype == TYPE_VECTOR &&
359 exprs[1]->vtype == TYPE_NOEXPR)
361 if (exprs[1] == (ast_expression*)parser->const_vec[0])
362 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
363 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
364 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
365 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
366 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
368 compile_error(ctx, "access to invalid vector component");
372 else if (exprs[0]->vtype == TYPE_ENTITY) {
373 if (exprs[1]->vtype != TYPE_FIELD) {
374 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
377 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
379 else if (exprs[0]->vtype == TYPE_VECTOR) {
380 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
384 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
390 if (exprs[0]->vtype != TYPE_ARRAY &&
391 !(exprs[0]->vtype == TYPE_FIELD &&
392 exprs[0]->next->vtype == TYPE_ARRAY))
394 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
395 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
398 if (exprs[1]->vtype != TYPE_FLOAT) {
399 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
400 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
403 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
404 if (rotate_entfield_array_index_nodes(&out))
407 /* This is not broken in fteqcc anymore */
408 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
409 /* this error doesn't need to make us bail out */
410 (void)!parsewarning(parser, WARN_EXTENSIONS,
411 "accessing array-field members of an entity without parenthesis\n"
412 " -> this is an extension from -std=gmqcc");
419 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
420 vec_push(sy->out, syexp(ctx, exprs[0]));
421 vec_push(sy->out, syexp(ctx, exprs[1]));
422 vec_last(sy->argc)++;
426 if (!ast_block_add_expr(blocks[0], exprs[1]))
429 blocks[0] = ast_block_new(ctx);
430 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
431 !ast_block_add_expr(blocks[0], exprs[1]))
436 ast_block_set_type(blocks[0], exprs[1]);
438 vec_push(sy->out, syblock(ctx, blocks[0]));
445 if (!(out = fold_op(parser->fold, op, exprs))) {
446 switch (exprs[0]->vtype) {
448 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
449 (ast_expression*)parser->fold->imm_float[0],
453 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
454 (ast_expression*)parser->fold->imm_vector[0],
458 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
459 type_name[exprs[0]->vtype]);
466 if (!(out = fold_op(parser->fold, op, exprs))) {
467 switch (exprs[0]->vtype) {
469 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
472 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
475 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
476 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
478 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
480 /* we don't constant-fold NOT for these types */
482 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
485 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
488 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
489 type_name[exprs[0]->vtype]);
496 if (exprs[0]->vtype != exprs[1]->vtype ||
497 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
499 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
500 type_name[exprs[0]->vtype],
501 type_name[exprs[1]->vtype]);
504 if (!(out = fold_op(parser->fold, op, exprs))) {
505 switch (exprs[0]->vtype) {
507 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
510 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
513 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
514 type_name[exprs[0]->vtype],
515 type_name[exprs[1]->vtype]);
521 if (exprs[0]->vtype != exprs[1]->vtype ||
522 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
524 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
525 type_name[exprs[1]->vtype],
526 type_name[exprs[0]->vtype]);
529 if (!(out = fold_op(parser->fold, op, exprs))) {
530 switch (exprs[0]->vtype) {
532 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
535 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
538 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
539 type_name[exprs[1]->vtype],
540 type_name[exprs[0]->vtype]);
546 if (exprs[0]->vtype != exprs[1]->vtype &&
547 !(exprs[0]->vtype == TYPE_VECTOR &&
548 exprs[1]->vtype == TYPE_FLOAT) &&
549 !(exprs[1]->vtype == TYPE_VECTOR &&
550 exprs[0]->vtype == TYPE_FLOAT)
553 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
554 type_name[exprs[1]->vtype],
555 type_name[exprs[0]->vtype]);
558 if (!(out = fold_op(parser->fold, op, exprs))) {
559 switch (exprs[0]->vtype) {
561 if (exprs[1]->vtype == TYPE_VECTOR)
562 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
564 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
567 if (exprs[1]->vtype == TYPE_FLOAT)
568 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
570 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
573 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
574 type_name[exprs[1]->vtype],
575 type_name[exprs[0]->vtype]);
582 if (exprs[1]->vtype != TYPE_FLOAT) {
583 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
584 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
585 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
588 if (!(out = fold_op(parser->fold, op, exprs))) {
589 if (exprs[0]->vtype == TYPE_FLOAT)
590 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
592 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
593 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
594 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]);
606 } else if (!(out = fold_op(parser->fold, op, exprs))) {
607 /* generate a call to __builtin_mod */
608 ast_expression *mod = intrin_func(parser->intrin, "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 if (!(out = fold_op(parser->fold, op, exprs)))
633 out = (ast_expression*)ast_binary_new(ctx,
634 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
639 * Okay lets designate what the hell is an acceptable use
640 * of the ^ operator. In many vector processing units, XOR
641 * is allowed to be used on vectors, but only if the first
642 * operand is a vector, the second operand can be a float
643 * or vector. It's never legal for the first operand to be
644 * a float, and then the following operand to be a vector.
645 * Further more, the only time it is legal to do XOR otherwise
646 * is when both operand are floats. This nicely crafted if
647 * statement catches them all.
649 * In the event that the first operand is a vector, two
650 * possible situations can arise, thus, each element of
651 * vector A (operand A) is exclusive-ORed with the corresponding
652 * element of vector B (operand B), If B is scalar, the
653 * scalar value is first replicated for each element.
655 * The QCVM itself lacks a BITXOR instruction. Thus emulating
656 * the mathematics of it is required. The following equation
657 * is used: (LHS | RHS) & ~(LHS & RHS). However, due to the
658 * QCVM also lacking a BITNEG instruction, we need to emulate
659 * ~FOO with -1 - FOO, the whole process becoming this nicely
660 * crafted expression: (LHS | RHS) & (-1 - (LHS & RHS)).
662 * When A is not scalar, this process is repeated for all
663 * components of vector A with the value in operand B,
664 * only if operand B is scalar. When A is not scalar, and B
665 * is also not scalar, this process is repeated for all
666 * components of the vector A with the components of vector B.
667 * Finally when A is scalar and B is scalar, this process is
668 * simply used once for A and B being LHS and RHS respectfully.
670 * Yes the semantics are a bit strange (no pun intended).
671 * But then again BITXOR is strange itself, consdering it's
672 * commutative, assocative, and elements of the BITXOR operation
673 * are their own inverse.
675 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
676 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
677 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
679 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
680 type_name[exprs[0]->vtype],
681 type_name[exprs[1]->vtype]);
685 if (!(out = fold_op(parser->fold, op, exprs))) {
687 * IF the first expression is float, the following will be too
688 * since scalar ^ vector is not allowed.
690 if (exprs[0]->vtype == TYPE_FLOAT) {
691 ast_binary *expr = ast_binary_new(
694 (ast_expression*)parser->fold->imm_float[2],
695 (ast_expression*)ast_binary_new(
702 expr->refs = AST_REF_NONE;
704 out = (ast_expression*)
708 (ast_expression*)ast_binary_new(
714 (ast_expression*)expr
718 * The first is a vector: vector is allowed to xor with vector and
719 * with scalar, branch here for the second operand.
721 if (exprs[1]->vtype == TYPE_VECTOR) {
723 * Xor all the values of the vector components against the
724 * vectors components in question.
726 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against vector");
729 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against float");
738 case opid3('<','<','='):
739 case opid3('>','>','='):
740 if(!(out = fold_op(parser->fold, op, exprs))) {
741 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
746 generated_op += 1; /* INSTR_OR */
748 generated_op += INSTR_AND;
749 if (!(out = fold_op(parser->fold, op, exprs))) {
750 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
751 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
752 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
753 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
756 for (i = 0; i < 2; ++i) {
757 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
758 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
760 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
762 exprs[i] = out; out = NULL;
763 if (OPTS_FLAG(PERL_LOGIC)) {
764 /* here we want to keep the right expressions' type */
768 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
769 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
771 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
773 exprs[i] = out; out = NULL;
774 if (OPTS_FLAG(PERL_LOGIC)) {
775 /* here we want to keep the right expressions' type */
780 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
785 if (vec_last(sy->paren) != PAREN_TERNARY2) {
786 compile_error(ctx, "mismatched parenthesis/ternary");
790 if (!ast_compare_type(exprs[1], exprs[2])) {
791 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
792 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
793 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
796 if (!(out = fold_op(parser->fold, op, exprs)))
797 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
800 case opid2('*', '*'):
801 if (NotSameType(TYPE_FLOAT)) {
802 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
803 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
804 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
809 if (!(out = fold_op(parser->fold, op, exprs))) {
810 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser->intrin, "pow"));
811 vec_push(gencall->params, exprs[0]);
812 vec_push(gencall->params, exprs[1]);
813 out = (ast_expression*)gencall;
817 case opid3('<','=','>'): /* -1, 0, or 1 */
818 if (NotSameType(TYPE_FLOAT)) {
819 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
820 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
821 compile_error(ctx, "invalid types used in comparision: %s and %s",
827 if (!(out = fold_op(parser->fold, op, exprs))) {
828 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
830 eq->refs = AST_REF_NONE;
833 out = (ast_expression*)ast_ternary_new(ctx,
834 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
836 (ast_expression*)parser->fold->imm_float[2],
839 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
841 (ast_expression*)parser->fold->imm_float[0],
844 (ast_expression*)parser->fold->imm_float[1]
854 generated_op += 1; /* INSTR_GT */
856 generated_op += 1; /* INSTR_LT */
857 case opid2('>', '='):
858 generated_op += 1; /* INSTR_GE */
859 case opid2('<', '='):
860 generated_op += INSTR_LE;
861 if (NotSameType(TYPE_FLOAT)) {
862 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
863 type_name[exprs[0]->vtype],
864 type_name[exprs[1]->vtype]);
867 if (!(out = fold_op(parser->fold, op, exprs)))
868 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
870 case opid2('!', '='):
871 if (exprs[0]->vtype != exprs[1]->vtype) {
872 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
873 type_name[exprs[0]->vtype],
874 type_name[exprs[1]->vtype]);
877 if (!(out = fold_op(parser->fold, op, exprs)))
878 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
880 case opid2('=', '='):
881 if (exprs[0]->vtype != exprs[1]->vtype) {
882 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
883 type_name[exprs[0]->vtype],
884 type_name[exprs[1]->vtype]);
887 if (!(out = fold_op(parser->fold, op, exprs)))
888 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
892 if (ast_istype(exprs[0], ast_entfield)) {
893 ast_expression *field = ((ast_entfield*)exprs[0])->field;
894 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
895 exprs[0]->vtype == TYPE_FIELD &&
896 exprs[0]->next->vtype == TYPE_VECTOR)
898 assignop = type_storep_instr[TYPE_VECTOR];
901 assignop = type_storep_instr[exprs[0]->vtype];
902 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
904 ast_type_to_string(field->next, ty1, sizeof(ty1));
905 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
906 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
907 field->next->vtype == TYPE_FUNCTION &&
908 exprs[1]->vtype == TYPE_FUNCTION)
910 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
911 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
914 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
919 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
920 exprs[0]->vtype == TYPE_FIELD &&
921 exprs[0]->next->vtype == TYPE_VECTOR)
923 assignop = type_store_instr[TYPE_VECTOR];
926 assignop = type_store_instr[exprs[0]->vtype];
929 if (assignop == VINSTR_END) {
930 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
931 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
932 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
934 else if (!ast_compare_type(exprs[0], exprs[1]))
936 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
937 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
938 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
939 exprs[0]->vtype == TYPE_FUNCTION &&
940 exprs[1]->vtype == TYPE_FUNCTION)
942 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
943 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
946 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
949 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
950 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
952 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
954 case opid3('+','+','P'):
955 case opid3('-','-','P'):
957 if (exprs[0]->vtype != TYPE_FLOAT) {
958 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
959 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
962 if (op->id == opid3('+','+','P'))
966 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
967 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
969 if (ast_istype(exprs[0], ast_entfield)) {
970 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
972 (ast_expression*)parser->fold->imm_float[1]);
974 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
976 (ast_expression*)parser->fold->imm_float[1]);
979 case opid3('S','+','+'):
980 case opid3('S','-','-'):
982 if (exprs[0]->vtype != TYPE_FLOAT) {
983 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
984 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
987 if (op->id == opid3('S','+','+')) {
994 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
995 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
997 if (ast_istype(exprs[0], ast_entfield)) {
998 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1000 (ast_expression*)parser->fold->imm_float[1]);
1002 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1004 (ast_expression*)parser->fold->imm_float[1]);
1008 out = (ast_expression*)ast_binary_new(ctx, subop,
1010 (ast_expression*)parser->fold->imm_float[1]);
1012 case opid2('+','='):
1013 case opid2('-','='):
1014 if (exprs[0]->vtype != exprs[1]->vtype ||
1015 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1017 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1018 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1019 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1023 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1024 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1026 if (ast_istype(exprs[0], ast_entfield))
1027 assignop = type_storep_instr[exprs[0]->vtype];
1029 assignop = type_store_instr[exprs[0]->vtype];
1030 switch (exprs[0]->vtype) {
1032 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1033 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1034 exprs[0], exprs[1]);
1037 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1038 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1039 exprs[0], exprs[1]);
1042 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1043 type_name[exprs[0]->vtype],
1044 type_name[exprs[1]->vtype]);
1048 case opid2('*','='):
1049 case opid2('/','='):
1050 if (exprs[1]->vtype != TYPE_FLOAT ||
1051 !(exprs[0]->vtype == TYPE_FLOAT ||
1052 exprs[0]->vtype == TYPE_VECTOR))
1054 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1055 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1056 compile_error(ctx, "invalid types used in expression: %s and %s",
1060 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1061 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1063 if (ast_istype(exprs[0], ast_entfield))
1064 assignop = type_storep_instr[exprs[0]->vtype];
1066 assignop = type_store_instr[exprs[0]->vtype];
1067 switch (exprs[0]->vtype) {
1069 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1070 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1071 exprs[0], exprs[1]);
1074 if (op->id == opid2('*','=')) {
1075 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1076 exprs[0], exprs[1]);
1078 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1079 (ast_expression*)parser->fold->imm_float[1],
1082 compile_error(ctx, "internal error: failed to generate division");
1085 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1090 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1091 type_name[exprs[0]->vtype],
1092 type_name[exprs[1]->vtype]);
1096 case opid2('&','='):
1097 case opid2('|','='):
1098 if (NotSameType(TYPE_FLOAT)) {
1099 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1100 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1101 compile_error(ctx, "invalid types used in expression: %s and %s",
1105 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1106 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1108 if (ast_istype(exprs[0], ast_entfield))
1109 assignop = type_storep_instr[exprs[0]->vtype];
1111 assignop = type_store_instr[exprs[0]->vtype];
1112 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1113 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1114 exprs[0], exprs[1]);
1116 case opid3('&','~','='):
1117 /* This is like: a &= ~(b);
1118 * But QC has no bitwise-not, so we implement it as
1121 if (NotSameType(TYPE_FLOAT)) {
1122 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1123 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1124 compile_error(ctx, "invalid types used in expression: %s and %s",
1128 if (ast_istype(exprs[0], ast_entfield))
1129 assignop = type_storep_instr[exprs[0]->vtype];
1131 assignop = type_store_instr[exprs[0]->vtype];
1132 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1135 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1136 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1138 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1139 asbinstore->keep_dest = true;
1140 out = (ast_expression*)asbinstore;
1143 case opid2('~', 'P'):
1144 if (exprs[0]->vtype != TYPE_FLOAT) {
1145 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1146 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1149 if (!(out = fold_op(parser->fold, op, exprs)))
1150 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1155 compile_error(ctx, "failed to apply operator %s", op->op);
1159 vec_push(sy->out, syexp(ctx, out));
1163 static bool parser_close_call(parser_t *parser, shunt *sy)
1165 /* was a function call */
1166 ast_expression *fun;
1167 ast_value *funval = NULL;
1171 size_t paramcount, i;
1173 fid = vec_last(sy->ops).off;
1174 vec_shrinkby(sy->ops, 1);
1176 /* out[fid] is the function
1177 * everything above is parameters...
1179 if (!vec_size(sy->argc)) {
1180 parseerror(parser, "internal error: no argument counter available");
1184 paramcount = vec_last(sy->argc);
1187 if (vec_size(sy->out) < fid) {
1188 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1189 (unsigned long)vec_size(sy->out),
1191 (unsigned long)paramcount);
1196 * TODO handle this at the intrinsic level with an ast_intrinsic
1199 if ((fun = sy->out[fid].out) == intrin_debug_typestring(parser->intrin)) {
1201 if (fid+2 != vec_size(sy->out) ||
1202 vec_last(sy->out).block)
1204 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1207 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1208 ast_unref(vec_last(sy->out).out);
1209 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1210 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1211 vec_shrinkby(sy->out, 1);
1214 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1219 if (fid+1 < vec_size(sy->out))
1222 if (fid+1 + paramcount != vec_size(sy->out)) {
1223 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1224 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1228 for (i = 0; i < paramcount; ++i)
1229 vec_push(call->params, sy->out[fid+1 + i].out);
1230 vec_shrinkby(sy->out, paramcount);
1231 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1232 if (parser->max_param_count < paramcount)
1233 parser->max_param_count = paramcount;
1235 if (ast_istype(fun, ast_value)) {
1236 funval = (ast_value*)fun;
1237 if ((fun->flags & AST_FLAG_VARIADIC) &&
1238 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1240 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1244 /* overwrite fid, the function, with a call */
1245 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1247 if (fun->vtype != TYPE_FUNCTION) {
1248 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1253 parseerror(parser, "could not determine function return type");
1256 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1258 if (fun->flags & AST_FLAG_DEPRECATED) {
1260 return !parsewarning(parser, WARN_DEPRECATED,
1261 "call to function (which is marked deprecated)\n",
1262 "-> it has been declared here: %s:%i",
1263 ast_ctx(fun).file, ast_ctx(fun).line);
1266 return !parsewarning(parser, WARN_DEPRECATED,
1267 "call to `%s` (which is marked deprecated)\n"
1268 "-> `%s` declared here: %s:%i",
1269 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1271 return !parsewarning(parser, WARN_DEPRECATED,
1272 "call to `%s` (deprecated: %s)\n"
1273 "-> `%s` declared here: %s:%i",
1274 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1278 if (vec_size(fun->params) != paramcount &&
1279 !((fun->flags & AST_FLAG_VARIADIC) &&
1280 vec_size(fun->params) < paramcount))
1282 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1284 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1285 "too %s parameters for call to %s: expected %i, got %i\n"
1286 " -> `%s` has been declared here: %s:%i",
1287 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1288 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1290 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1291 "too %s parameters for function call: expected %i, got %i\n"
1292 " -> it has been declared here: %s:%i",
1293 fewmany, (int)vec_size(fun->params), (int)paramcount,
1294 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1301 static bool parser_close_paren(parser_t *parser, shunt *sy)
1303 if (!vec_size(sy->ops)) {
1304 parseerror(parser, "unmatched closing paren");
1308 while (vec_size(sy->ops)) {
1309 if (vec_last(sy->ops).isparen) {
1310 if (vec_last(sy->paren) == PAREN_FUNC) {
1312 if (!parser_close_call(parser, sy))
1316 if (vec_last(sy->paren) == PAREN_EXPR) {
1318 if (!vec_size(sy->out)) {
1319 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1320 vec_shrinkby(sy->ops, 1);
1323 vec_shrinkby(sy->ops, 1);
1326 if (vec_last(sy->paren) == PAREN_INDEX) {
1328 /* pop off the parenthesis */
1329 vec_shrinkby(sy->ops, 1);
1330 /* then apply the index operator */
1331 if (!parser_sy_apply_operator(parser, sy))
1335 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1336 vec_last(sy->paren) = PAREN_TERNARY2;
1337 /* pop off the parenthesis */
1338 vec_shrinkby(sy->ops, 1);
1341 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1344 if (!parser_sy_apply_operator(parser, sy))
1350 static void parser_reclassify_token(parser_t *parser)
1353 if (parser->tok >= TOKEN_START)
1355 for (i = 0; i < operator_count; ++i) {
1356 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1357 parser->tok = TOKEN_OPERATOR;
1363 static ast_expression* parse_vararg_do(parser_t *parser)
1365 ast_expression *idx, *out;
1367 ast_value *funtype = parser->function->vtype;
1368 lex_ctx_t ctx = parser_ctx(parser);
1370 if (!parser->function->varargs) {
1371 parseerror(parser, "function has no variable argument list");
1375 if (!parser_next(parser) || parser->tok != '(') {
1376 parseerror(parser, "expected parameter index and type in parenthesis");
1379 if (!parser_next(parser)) {
1380 parseerror(parser, "error parsing parameter index");
1384 idx = parse_expression_leave(parser, true, false, false);
1388 if (parser->tok != ',') {
1389 if (parser->tok != ')') {
1391 parseerror(parser, "expected comma after parameter index");
1394 /* vararg piping: ...(start) */
1395 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1399 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1401 parseerror(parser, "expected typename for vararg");
1405 typevar = parse_typename(parser, NULL, NULL);
1411 if (parser->tok != ')') {
1413 ast_delete(typevar);
1414 parseerror(parser, "expected closing paren");
1418 if (funtype->expression.varparam &&
1419 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1423 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1424 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1425 compile_error(ast_ctx(typevar),
1426 "function was declared to take varargs of type `%s`, requested type is: %s",
1430 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1431 ast_type_adopt(out, typevar);
1432 ast_delete(typevar);
1436 static ast_expression* parse_vararg(parser_t *parser)
1438 bool old_noops = parser->lex->flags.noops;
1440 ast_expression *out;
1442 parser->lex->flags.noops = true;
1443 out = parse_vararg_do(parser);
1445 parser->lex->flags.noops = old_noops;
1449 /* not to be exposed */
1450 extern bool ftepp_predef_exists(const char *name);
1452 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1454 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1455 parser->tok == TOKEN_IDENT &&
1456 !strcmp(parser_tokval(parser), "_"))
1458 /* a translatable string */
1461 parser->lex->flags.noops = true;
1462 if (!parser_next(parser) || parser->tok != '(') {
1463 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1466 parser->lex->flags.noops = false;
1467 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1468 parseerror(parser, "expected a constant string in translatable-string extension");
1471 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1474 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1476 if (!parser_next(parser) || parser->tok != ')') {
1477 parseerror(parser, "expected closing paren after translatable string");
1482 else if (parser->tok == TOKEN_DOTS)
1485 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1486 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1489 va = parse_vararg(parser);
1492 vec_push(sy->out, syexp(parser_ctx(parser), va));
1495 else if (parser->tok == TOKEN_FLOATCONST) {
1496 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1499 vec_push(sy->out, syexp(parser_ctx(parser), val));
1502 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1503 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1506 vec_push(sy->out, syexp(parser_ctx(parser), val));
1509 else if (parser->tok == TOKEN_STRINGCONST) {
1510 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1513 vec_push(sy->out, syexp(parser_ctx(parser), val));
1516 else if (parser->tok == TOKEN_VECTORCONST) {
1517 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1520 vec_push(sy->out, syexp(parser_ctx(parser), val));
1523 else if (parser->tok == TOKEN_IDENT)
1525 const char *ctoken = parser_tokval(parser);
1526 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1527 ast_expression *var;
1528 /* a_vector.{x,y,z} */
1529 if (!vec_size(sy->ops) ||
1530 !vec_last(sy->ops).etype ||
1531 operators[vec_last(sy->ops).etype-1].id != opid1('.'))
1533 /* When adding more intrinsics, fix the above condition */
1536 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1538 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1540 var = parser_find_var(parser, parser_tokval(parser));
1542 var = parser_find_field(parser, parser_tokval(parser));
1544 if (!var && with_labels) {
1545 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1547 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1548 var = (ast_expression*)lbl;
1549 vec_push(parser->labels, lbl);
1552 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1553 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1556 * now we try for the real intrinsic hashtable. If the string
1557 * begins with __builtin, we simply skip past it, otherwise we
1558 * use the identifier as is.
1560 if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1561 var = intrin_func(parser->intrin, parser_tokval(parser));
1565 char *correct = NULL;
1569 * sometimes people use preprocessing predefs without enabling them
1570 * i've done this thousands of times already myself. Lets check for
1571 * it in the predef table. And diagnose it better :)
1573 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1574 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1579 * TODO: determine the best score for the identifier: be it
1580 * a variable, a field.
1582 * We should also consider adding correction tables for
1583 * other things as well.
1585 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1587 correct_init(&corr);
1589 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1590 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1591 if (strcmp(correct, parser_tokval(parser))) {
1598 correct_free(&corr);
1601 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1606 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1612 if (ast_istype(var, ast_value)) {
1613 ((ast_value*)var)->uses++;
1615 else if (ast_istype(var, ast_member)) {
1616 ast_member *mem = (ast_member*)var;
1617 if (ast_istype(mem->owner, ast_value))
1618 ((ast_value*)(mem->owner))->uses++;
1621 vec_push(sy->out, syexp(parser_ctx(parser), var));
1624 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1628 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1630 ast_expression *expr = NULL;
1633 bool wantop = false;
1634 /* only warn once about an assignment in a truth value because the current code
1635 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1637 bool warn_truthvalue = true;
1639 /* count the parens because an if starts with one, so the
1640 * end of a condition is an unmatched closing paren
1644 memset(&sy, 0, sizeof(sy));
1646 parser->lex->flags.noops = false;
1648 parser_reclassify_token(parser);
1652 if (parser->tok == TOKEN_TYPENAME) {
1653 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1657 if (parser->tok == TOKEN_OPERATOR)
1659 /* classify the operator */
1660 const oper_info *op;
1661 const oper_info *olast = NULL;
1663 for (o = 0; o < operator_count; ++o) {
1664 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1665 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1666 !strcmp(parser_tokval(parser), operators[o].op))
1671 if (o == operator_count) {
1672 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1675 /* found an operator */
1678 /* when declaring variables, a comma starts a new variable */
1679 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1680 /* fixup the token */
1685 /* a colon without a pervious question mark cannot be a ternary */
1686 if (!ternaries && op->id == opid2(':','?')) {
1691 if (op->id == opid1(',')) {
1692 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1693 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1697 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1698 olast = &operators[vec_last(sy.ops).etype-1];
1700 #define IsAssignOp(x) (\
1701 (x) == opid1('=') || \
1702 (x) == opid2('+','=') || \
1703 (x) == opid2('-','=') || \
1704 (x) == opid2('*','=') || \
1705 (x) == opid2('/','=') || \
1706 (x) == opid2('%','=') || \
1707 (x) == opid2('&','=') || \
1708 (x) == opid2('|','=') || \
1709 (x) == opid3('&','~','=') \
1711 if (warn_truthvalue) {
1712 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1713 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1714 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1717 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1718 warn_truthvalue = false;
1723 (op->prec < olast->prec) ||
1724 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1726 if (!parser_sy_apply_operator(parser, &sy))
1728 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1729 olast = &operators[vec_last(sy.ops).etype-1];
1734 if (op->id == opid1('(')) {
1736 size_t sycount = vec_size(sy.out);
1737 /* we expected an operator, this is the function-call operator */
1738 vec_push(sy.paren, PAREN_FUNC);
1739 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1740 vec_push(sy.argc, 0);
1742 vec_push(sy.paren, PAREN_EXPR);
1743 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1746 } else if (op->id == opid1('[')) {
1748 parseerror(parser, "unexpected array subscript");
1751 vec_push(sy.paren, PAREN_INDEX);
1752 /* push both the operator and the paren, this makes life easier */
1753 vec_push(sy.ops, syop(parser_ctx(parser), op));
1754 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1756 } else if (op->id == opid2('?',':')) {
1757 vec_push(sy.ops, syop(parser_ctx(parser), op));
1758 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1761 vec_push(sy.paren, PAREN_TERNARY1);
1762 } else if (op->id == opid2(':','?')) {
1763 if (!vec_size(sy.paren)) {
1764 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1767 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1768 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1771 if (!parser_close_paren(parser, &sy))
1773 vec_push(sy.ops, syop(parser_ctx(parser), op));
1777 vec_push(sy.ops, syop(parser_ctx(parser), op));
1778 wantop = !!(op->flags & OP_SUFFIX);
1781 else if (parser->tok == ')') {
1782 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1783 if (!parser_sy_apply_operator(parser, &sy))
1786 if (!vec_size(sy.paren))
1789 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1790 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1793 if (!parser_close_paren(parser, &sy))
1796 /* must be a function call without parameters */
1797 if (vec_last(sy.paren) != PAREN_FUNC) {
1798 parseerror(parser, "closing paren in invalid position");
1801 if (!parser_close_paren(parser, &sy))
1806 else if (parser->tok == '(') {
1807 parseerror(parser, "internal error: '(' should be classified as operator");
1810 else if (parser->tok == '[') {
1811 parseerror(parser, "internal error: '[' should be classified as operator");
1814 else if (parser->tok == ']') {
1815 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1816 if (!parser_sy_apply_operator(parser, &sy))
1819 if (!vec_size(sy.paren))
1821 if (vec_last(sy.paren) != PAREN_INDEX) {
1822 parseerror(parser, "mismatched parentheses, unexpected ']'");
1825 if (!parser_close_paren(parser, &sy))
1830 if (!parse_sya_operand(parser, &sy, with_labels))
1833 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1834 vec_last(sy.argc)++;
1839 /* in this case we might want to allow constant string concatenation */
1840 bool concatenated = false;
1841 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1842 ast_expression *lexpr = vec_last(sy.out).out;
1843 if (ast_istype(lexpr, ast_value)) {
1844 ast_value *last = (ast_value*)lexpr;
1845 if (last->isimm == true && last->cvq == CV_CONST &&
1846 last->hasvalue && last->expression.vtype == TYPE_STRING)
1848 char *newstr = NULL;
1849 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1850 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1852 concatenated = true;
1856 if (!concatenated) {
1857 parseerror(parser, "expected operator or end of statement");
1862 if (!parser_next(parser)) {
1865 if (parser->tok == ';' ||
1866 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1867 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1873 while (vec_size(sy.ops)) {
1874 if (!parser_sy_apply_operator(parser, &sy))
1878 parser->lex->flags.noops = true;
1879 if (vec_size(sy.out) != 1) {
1880 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
1883 expr = sy.out[0].out;
1886 if (vec_size(sy.paren)) {
1887 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1895 parser->lex->flags.noops = true;
1896 for (i = 0; i < vec_size(sy.out); ++i) {
1898 ast_unref(sy.out[i].out);
1907 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1909 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1912 if (parser->tok != ';') {
1913 parseerror(parser, "semicolon expected after expression");
1917 if (!parser_next(parser)) {
1924 static void parser_enterblock(parser_t *parser)
1926 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1927 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1928 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1929 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1930 vec_push(parser->_block_ctx, parser_ctx(parser));
1933 vec_push(parser->correct_variables, correct_trie_new());
1934 vec_push(parser->correct_variables_score, NULL);
1937 static bool parser_leaveblock(parser_t *parser)
1940 size_t locals, typedefs;
1942 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1943 parseerror(parser, "internal error: parser_leaveblock with no block");
1947 util_htdel(vec_last(parser->variables));
1948 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1950 vec_pop(parser->variables);
1951 vec_pop(parser->correct_variables);
1952 vec_pop(parser->correct_variables_score);
1953 if (!vec_size(parser->_blocklocals)) {
1954 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1958 locals = vec_last(parser->_blocklocals);
1959 vec_pop(parser->_blocklocals);
1960 while (vec_size(parser->_locals) != locals) {
1961 ast_expression *e = vec_last(parser->_locals);
1962 ast_value *v = (ast_value*)e;
1963 vec_pop(parser->_locals);
1964 if (ast_istype(e, ast_value) && !v->uses) {
1965 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1970 typedefs = vec_last(parser->_blocktypedefs);
1971 while (vec_size(parser->_typedefs) != typedefs) {
1972 ast_delete(vec_last(parser->_typedefs));
1973 vec_pop(parser->_typedefs);
1975 util_htdel(vec_last(parser->typedefs));
1976 vec_pop(parser->typedefs);
1978 vec_pop(parser->_block_ctx);
1983 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1985 vec_push(parser->_locals, e);
1986 util_htset(vec_last(parser->variables), name, (void*)e);
1990 vec_last(parser->correct_variables),
1991 &vec_last(parser->correct_variables_score),
1996 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
1998 vec_push(parser->globals, e);
1999 util_htset(parser->htglobals, name, e);
2003 parser->correct_variables[0],
2004 &parser->correct_variables_score[0],
2009 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2013 ast_expression *prev;
2015 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2017 ast_type_to_string(cond, ty, sizeof(ty));
2018 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2021 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2024 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2027 parseerror(parser, "internal error: failed to process condition");
2032 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2034 /* vector types need to be cast to true booleans */
2035 ast_binary *bin = (ast_binary*)cond;
2036 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2038 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2040 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2043 parseerror(parser, "internal error: failed to process condition");
2050 unary = (ast_unary*)cond;
2051 /* ast_istype dereferences cond, should test here for safety */
2052 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2054 cond = unary->operand;
2055 unary->operand = NULL;
2058 unary = (ast_unary*)cond;
2062 parseerror(parser, "internal error: failed to process condition");
2064 if (ifnot) *_ifnot = !*_ifnot;
2068 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2071 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2074 lex_ctx_t ctx = parser_ctx(parser);
2076 (void)block; /* not touching */
2078 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2079 if (!parser_next(parser)) {
2080 parseerror(parser, "expected condition or 'not'");
2083 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2085 if (!parser_next(parser)) {
2086 parseerror(parser, "expected condition in parenthesis");
2090 if (parser->tok != '(') {
2091 parseerror(parser, "expected 'if' condition in parenthesis");
2094 /* parse into the expression */
2095 if (!parser_next(parser)) {
2096 parseerror(parser, "expected 'if' condition after opening paren");
2099 /* parse the condition */
2100 cond = parse_expression_leave(parser, false, true, false);
2104 if (parser->tok != ')') {
2105 parseerror(parser, "expected closing paren after 'if' condition");
2109 /* parse into the 'then' branch */
2110 if (!parser_next(parser)) {
2111 parseerror(parser, "expected statement for on-true branch of 'if'");
2115 if (!parse_statement_or_block(parser, &ontrue)) {
2120 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2121 /* check for an else */
2122 if (!strcmp(parser_tokval(parser), "else")) {
2123 /* parse into the 'else' branch */
2124 if (!parser_next(parser)) {
2125 parseerror(parser, "expected on-false branch after 'else'");
2130 if (!parse_statement_or_block(parser, &onfalse)) {
2137 cond = process_condition(parser, cond, &ifnot);
2139 if (ontrue) ast_delete(ontrue);
2140 if (onfalse) ast_delete(onfalse);
2145 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2147 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2148 *out = (ast_expression*)ifthen;
2152 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2153 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2158 /* skip the 'while' and get the body */
2159 if (!parser_next(parser)) {
2160 if (OPTS_FLAG(LOOP_LABELS))
2161 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2163 parseerror(parser, "expected 'while' condition in parenthesis");
2167 if (parser->tok == ':') {
2168 if (!OPTS_FLAG(LOOP_LABELS))
2169 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2170 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2171 parseerror(parser, "expected loop label");
2174 label = util_strdup(parser_tokval(parser));
2175 if (!parser_next(parser)) {
2177 parseerror(parser, "expected 'while' condition in parenthesis");
2182 if (parser->tok != '(') {
2183 parseerror(parser, "expected 'while' condition in parenthesis");
2187 vec_push(parser->breaks, label);
2188 vec_push(parser->continues, label);
2190 rv = parse_while_go(parser, block, out);
2193 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2194 parseerror(parser, "internal error: label stack corrupted");
2200 vec_pop(parser->breaks);
2201 vec_pop(parser->continues);
2206 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2209 ast_expression *cond, *ontrue;
2213 lex_ctx_t ctx = parser_ctx(parser);
2215 (void)block; /* not touching */
2217 /* parse into the expression */
2218 if (!parser_next(parser)) {
2219 parseerror(parser, "expected 'while' condition after opening paren");
2222 /* parse the condition */
2223 cond = parse_expression_leave(parser, false, true, false);
2227 if (parser->tok != ')') {
2228 parseerror(parser, "expected closing paren after 'while' condition");
2232 /* parse into the 'then' branch */
2233 if (!parser_next(parser)) {
2234 parseerror(parser, "expected while-loop body");
2238 if (!parse_statement_or_block(parser, &ontrue)) {
2243 cond = process_condition(parser, cond, &ifnot);
2248 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2249 *out = (ast_expression*)aloop;
2253 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2254 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2259 /* skip the 'do' and get the body */
2260 if (!parser_next(parser)) {
2261 if (OPTS_FLAG(LOOP_LABELS))
2262 parseerror(parser, "expected loop label or body");
2264 parseerror(parser, "expected loop body");
2268 if (parser->tok == ':') {
2269 if (!OPTS_FLAG(LOOP_LABELS))
2270 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2271 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2272 parseerror(parser, "expected loop label");
2275 label = util_strdup(parser_tokval(parser));
2276 if (!parser_next(parser)) {
2278 parseerror(parser, "expected loop body");
2283 vec_push(parser->breaks, label);
2284 vec_push(parser->continues, label);
2286 rv = parse_dowhile_go(parser, block, out);
2289 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2290 parseerror(parser, "internal error: label stack corrupted");
2293 * Test for NULL otherwise ast_delete dereferences null pointer
2301 vec_pop(parser->breaks);
2302 vec_pop(parser->continues);
2307 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2310 ast_expression *cond, *ontrue;
2314 lex_ctx_t ctx = parser_ctx(parser);
2316 (void)block; /* not touching */
2318 if (!parse_statement_or_block(parser, &ontrue))
2321 /* expect the "while" */
2322 if (parser->tok != TOKEN_KEYWORD ||
2323 strcmp(parser_tokval(parser), "while"))
2325 parseerror(parser, "expected 'while' and condition");
2330 /* skip the 'while' and check for opening paren */
2331 if (!parser_next(parser) || parser->tok != '(') {
2332 parseerror(parser, "expected 'while' condition in parenthesis");
2336 /* parse into the expression */
2337 if (!parser_next(parser)) {
2338 parseerror(parser, "expected 'while' condition after opening paren");
2342 /* parse the condition */
2343 cond = parse_expression_leave(parser, false, true, false);
2347 if (parser->tok != ')') {
2348 parseerror(parser, "expected closing paren after 'while' condition");
2354 if (!parser_next(parser) || parser->tok != ';') {
2355 parseerror(parser, "expected semicolon after condition");
2361 if (!parser_next(parser)) {
2362 parseerror(parser, "parse error");
2368 cond = process_condition(parser, cond, &ifnot);
2373 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2374 *out = (ast_expression*)aloop;
2378 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2379 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2384 /* skip the 'for' and check for opening paren */
2385 if (!parser_next(parser)) {
2386 if (OPTS_FLAG(LOOP_LABELS))
2387 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2389 parseerror(parser, "expected 'for' expressions in parenthesis");
2393 if (parser->tok == ':') {
2394 if (!OPTS_FLAG(LOOP_LABELS))
2395 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2396 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2397 parseerror(parser, "expected loop label");
2400 label = util_strdup(parser_tokval(parser));
2401 if (!parser_next(parser)) {
2403 parseerror(parser, "expected 'for' expressions in parenthesis");
2408 if (parser->tok != '(') {
2409 parseerror(parser, "expected 'for' expressions in parenthesis");
2413 vec_push(parser->breaks, label);
2414 vec_push(parser->continues, label);
2416 rv = parse_for_go(parser, block, out);
2419 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2420 parseerror(parser, "internal error: label stack corrupted");
2426 vec_pop(parser->breaks);
2427 vec_pop(parser->continues);
2431 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2434 ast_expression *initexpr, *cond, *increment, *ontrue;
2439 lex_ctx_t ctx = parser_ctx(parser);
2441 parser_enterblock(parser);
2448 /* parse into the expression */
2449 if (!parser_next(parser)) {
2450 parseerror(parser, "expected 'for' initializer after opening paren");
2455 if (parser->tok == TOKEN_IDENT)
2456 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2458 if (typevar || parser->tok == TOKEN_TYPENAME) {
2460 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2461 if (parsewarning(parser, WARN_EXTENSIONS,
2462 "current standard does not allow variable declarations in for-loop initializers"))
2466 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2469 else if (parser->tok != ';')
2471 initexpr = parse_expression_leave(parser, false, false, false);
2476 /* move on to condition */
2477 if (parser->tok != ';') {
2478 parseerror(parser, "expected semicolon after for-loop initializer");
2481 if (!parser_next(parser)) {
2482 parseerror(parser, "expected for-loop condition");
2486 /* parse the condition */
2487 if (parser->tok != ';') {
2488 cond = parse_expression_leave(parser, false, true, false);
2493 /* move on to incrementor */
2494 if (parser->tok != ';') {
2495 parseerror(parser, "expected semicolon after for-loop initializer");
2498 if (!parser_next(parser)) {
2499 parseerror(parser, "expected for-loop condition");
2503 /* parse the incrementor */
2504 if (parser->tok != ')') {
2505 lex_ctx_t condctx = parser_ctx(parser);
2506 increment = parse_expression_leave(parser, false, false, false);
2509 if (!ast_side_effects(increment)) {
2510 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2516 if (parser->tok != ')') {
2517 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2520 /* parse into the 'then' branch */
2521 if (!parser_next(parser)) {
2522 parseerror(parser, "expected for-loop body");
2525 if (!parse_statement_or_block(parser, &ontrue))
2529 cond = process_condition(parser, cond, &ifnot);
2533 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2534 *out = (ast_expression*)aloop;
2536 if (!parser_leaveblock(parser)) {
2542 if (initexpr) ast_unref(initexpr);
2543 if (cond) ast_unref(cond);
2544 if (increment) ast_unref(increment);
2545 (void)!parser_leaveblock(parser);
2549 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2551 ast_expression *exp = NULL;
2552 ast_expression *var = NULL;
2553 ast_return *ret = NULL;
2554 ast_value *retval = parser->function->return_value;
2555 ast_value *expected = parser->function->vtype;
2557 lex_ctx_t ctx = parser_ctx(parser);
2559 (void)block; /* not touching */
2561 if (!parser_next(parser)) {
2562 parseerror(parser, "expected return expression");
2566 /* return assignments */
2567 if (parser->tok == '=') {
2568 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2569 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2573 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2575 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2576 parseerror(parser, "invalid return type: `%s'", ty1);
2580 if (!parser_next(parser)) {
2581 parseerror(parser, "expected return assignment expression");
2585 if (!(exp = parse_expression_leave(parser, false, false, false)))
2588 /* prepare the return value */
2590 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2591 ast_type_adopt(retval, expected->expression.next);
2592 parser->function->return_value = retval;
2595 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2596 char ty1[1024], ty2[1024];
2597 ast_type_to_string(exp, ty1, sizeof(ty1));
2598 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2599 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2602 /* store to 'return' local variable */
2603 var = (ast_expression*)ast_store_new(
2605 type_store_instr[expected->expression.next->vtype],
2606 (ast_expression*)retval, exp);
2613 if (parser->tok != ';')
2614 parseerror(parser, "missing semicolon after return assignment");
2615 else if (!parser_next(parser))
2616 parseerror(parser, "parse error after return assignment");
2622 if (parser->tok != ';') {
2623 exp = parse_expression(parser, false, false);
2627 if (exp->vtype != TYPE_NIL &&
2628 exp->vtype != ((ast_expression*)expected)->next->vtype)
2630 parseerror(parser, "return with invalid expression");
2633 ret = ast_return_new(ctx, exp);
2639 if (!parser_next(parser))
2640 parseerror(parser, "parse error");
2642 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2644 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2646 ret = ast_return_new(ctx, (ast_expression*)retval);
2648 *out = (ast_expression*)ret;
2652 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2655 unsigned int levels = 0;
2656 lex_ctx_t ctx = parser_ctx(parser);
2657 const char **loops = (is_continue ? parser->continues : parser->breaks);
2659 (void)block; /* not touching */
2660 if (!parser_next(parser)) {
2661 parseerror(parser, "expected semicolon or loop label");
2665 if (!vec_size(loops)) {
2667 parseerror(parser, "`continue` can only be used inside loops");
2669 parseerror(parser, "`break` can only be used inside loops or switches");
2672 if (parser->tok == TOKEN_IDENT) {
2673 if (!OPTS_FLAG(LOOP_LABELS))
2674 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2675 i = vec_size(loops);
2677 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2680 parseerror(parser, "no such loop to %s: `%s`",
2681 (is_continue ? "continue" : "break out of"),
2682 parser_tokval(parser));
2687 if (!parser_next(parser)) {
2688 parseerror(parser, "expected semicolon");
2693 if (parser->tok != ';') {
2694 parseerror(parser, "expected semicolon");
2698 if (!parser_next(parser))
2699 parseerror(parser, "parse error");
2701 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2705 /* returns true when it was a variable qualifier, false otherwise!
2706 * on error, cvq is set to CV_WRONG
2708 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2710 bool had_const = false;
2711 bool had_var = false;
2712 bool had_noref = false;
2713 bool had_attrib = false;
2714 bool had_static = false;
2719 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2721 /* parse an attribute */
2722 if (!parser_next(parser)) {
2723 parseerror(parser, "expected attribute after `[[`");
2727 if (!strcmp(parser_tokval(parser), "noreturn")) {
2728 flags |= AST_FLAG_NORETURN;
2729 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2730 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2735 else if (!strcmp(parser_tokval(parser), "noref")) {
2737 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2738 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2743 else if (!strcmp(parser_tokval(parser), "inline")) {
2744 flags |= AST_FLAG_INLINE;
2745 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2746 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2751 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2752 flags |= AST_FLAG_ALIAS;
2755 if (!parser_next(parser)) {
2756 parseerror(parser, "parse error in attribute");
2760 if (parser->tok == '(') {
2761 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2762 parseerror(parser, "`alias` attribute missing parameter");
2766 *message = util_strdup(parser_tokval(parser));
2768 if (!parser_next(parser)) {
2769 parseerror(parser, "parse error in attribute");
2773 if (parser->tok != ')') {
2774 parseerror(parser, "`alias` attribute expected `)` after parameter");
2778 if (!parser_next(parser)) {
2779 parseerror(parser, "parse error in attribute");
2784 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2785 parseerror(parser, "`alias` attribute expected `]]`");
2789 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2790 flags |= AST_FLAG_DEPRECATED;
2793 if (!parser_next(parser)) {
2794 parseerror(parser, "parse error in attribute");
2798 if (parser->tok == '(') {
2799 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2800 parseerror(parser, "`deprecated` attribute missing parameter");
2804 *message = util_strdup(parser_tokval(parser));
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "parse error in attribute");
2811 if(parser->tok != ')') {
2812 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2816 if (!parser_next(parser)) {
2817 parseerror(parser, "parse error in attribute");
2822 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2823 parseerror(parser, "`deprecated` attribute expected `]]`");
2826 if (*message) mem_d(*message);
2834 /* Skip tokens until we hit a ]] */
2835 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2836 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2837 if (!parser_next(parser)) {
2838 parseerror(parser, "error inside attribute");
2845 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2847 else if (!strcmp(parser_tokval(parser), "const"))
2849 else if (!strcmp(parser_tokval(parser), "var"))
2851 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2853 else if (!strcmp(parser_tokval(parser), "noref"))
2855 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2860 if (!parser_next(parser))
2870 *is_static = had_static;
2874 parseerror(parser, "parse error after variable qualifier");
2879 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2880 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2885 /* skip the 'while' and get the body */
2886 if (!parser_next(parser)) {
2887 if (OPTS_FLAG(LOOP_LABELS))
2888 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2890 parseerror(parser, "expected 'switch' operand in parenthesis");
2894 if (parser->tok == ':') {
2895 if (!OPTS_FLAG(LOOP_LABELS))
2896 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2897 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2898 parseerror(parser, "expected loop label");
2901 label = util_strdup(parser_tokval(parser));
2902 if (!parser_next(parser)) {
2904 parseerror(parser, "expected 'switch' operand in parenthesis");
2909 if (parser->tok != '(') {
2910 parseerror(parser, "expected 'switch' operand in parenthesis");
2914 vec_push(parser->breaks, label);
2916 rv = parse_switch_go(parser, block, out);
2919 if (vec_last(parser->breaks) != label) {
2920 parseerror(parser, "internal error: label stack corrupted");
2926 vec_pop(parser->breaks);
2931 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2933 ast_expression *operand;
2936 ast_switch *switchnode;
2937 ast_switch_case swcase;
2940 bool noref, is_static;
2941 uint32_t qflags = 0;
2943 lex_ctx_t ctx = parser_ctx(parser);
2945 (void)block; /* not touching */
2948 /* parse into the expression */
2949 if (!parser_next(parser)) {
2950 parseerror(parser, "expected switch operand");
2953 /* parse the operand */
2954 operand = parse_expression_leave(parser, false, false, false);
2958 switchnode = ast_switch_new(ctx, operand);
2961 if (parser->tok != ')') {
2962 ast_delete(switchnode);
2963 parseerror(parser, "expected closing paren after 'switch' operand");
2967 /* parse over the opening paren */
2968 if (!parser_next(parser) || parser->tok != '{') {
2969 ast_delete(switchnode);
2970 parseerror(parser, "expected list of cases");
2974 if (!parser_next(parser)) {
2975 ast_delete(switchnode);
2976 parseerror(parser, "expected 'case' or 'default'");
2980 /* new block; allow some variables to be declared here */
2981 parser_enterblock(parser);
2984 if (parser->tok == TOKEN_IDENT)
2985 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2986 if (typevar || parser->tok == TOKEN_TYPENAME) {
2987 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
2988 ast_delete(switchnode);
2993 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
2995 if (cvq == CV_WRONG) {
2996 ast_delete(switchnode);
2999 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3000 ast_delete(switchnode);
3009 while (parser->tok != '}') {
3010 ast_block *caseblock;
3012 if (!strcmp(parser_tokval(parser), "case")) {
3013 if (!parser_next(parser)) {
3014 ast_delete(switchnode);
3015 parseerror(parser, "expected expression for case");
3018 swcase.value = parse_expression_leave(parser, false, false, false);
3019 if (!swcase.value) {
3020 ast_delete(switchnode);
3021 parseerror(parser, "expected expression for case");
3024 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3025 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3026 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3032 else if (!strcmp(parser_tokval(parser), "default")) {
3033 swcase.value = NULL;
3034 if (!parser_next(parser)) {
3035 ast_delete(switchnode);
3036 parseerror(parser, "expected colon");
3041 ast_delete(switchnode);
3042 parseerror(parser, "expected 'case' or 'default'");
3046 /* Now the colon and body */
3047 if (parser->tok != ':') {
3048 if (swcase.value) ast_unref(swcase.value);
3049 ast_delete(switchnode);
3050 parseerror(parser, "expected colon");
3054 if (!parser_next(parser)) {
3055 if (swcase.value) ast_unref(swcase.value);
3056 ast_delete(switchnode);
3057 parseerror(parser, "expected statements or case");
3060 caseblock = ast_block_new(parser_ctx(parser));
3062 if (swcase.value) ast_unref(swcase.value);
3063 ast_delete(switchnode);
3066 swcase.code = (ast_expression*)caseblock;
3067 vec_push(switchnode->cases, swcase);
3069 ast_expression *expr;
3070 if (parser->tok == '}')
3072 if (parser->tok == TOKEN_KEYWORD) {
3073 if (!strcmp(parser_tokval(parser), "case") ||
3074 !strcmp(parser_tokval(parser), "default"))
3079 if (!parse_statement(parser, caseblock, &expr, true)) {
3080 ast_delete(switchnode);
3085 if (!ast_block_add_expr(caseblock, expr)) {
3086 ast_delete(switchnode);
3092 parser_leaveblock(parser);
3095 if (parser->tok != '}') {
3096 ast_delete(switchnode);
3097 parseerror(parser, "expected closing paren of case list");
3100 if (!parser_next(parser)) {
3101 ast_delete(switchnode);
3102 parseerror(parser, "parse error after switch");
3105 *out = (ast_expression*)switchnode;
3109 /* parse computed goto sides */
3110 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3111 ast_expression *on_true;
3112 ast_expression *on_false;
3113 ast_expression *cond;
3118 if (ast_istype(*side, ast_ternary)) {
3119 ast_ternary *tern = (ast_ternary*)*side;
3120 on_true = parse_goto_computed(parser, &tern->on_true);
3121 on_false = parse_goto_computed(parser, &tern->on_false);
3123 if (!on_true || !on_false) {
3124 parseerror(parser, "expected label or expression in ternary");
3125 if (on_true) ast_unref(on_true);
3126 if (on_false) ast_unref(on_false);
3134 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3135 } else if (ast_istype(*side, ast_label)) {
3136 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3137 ast_goto_set_label(gt, ((ast_label*)*side));
3139 return (ast_expression*)gt;
3144 static bool parse_goto(parser_t *parser, ast_expression **out)
3146 ast_goto *gt = NULL;
3147 ast_expression *lbl;
3149 if (!parser_next(parser))
3152 if (parser->tok != TOKEN_IDENT) {
3153 ast_expression *expression;
3155 /* could be an expression i.e computed goto :-) */
3156 if (parser->tok != '(') {
3157 parseerror(parser, "expected label name after `goto`");
3161 /* failed to parse expression for goto */
3162 if (!(expression = parse_expression(parser, false, true)) ||
3163 !(*out = parse_goto_computed(parser, &expression))) {
3164 parseerror(parser, "invalid goto expression");
3166 ast_unref(expression);
3173 /* not computed goto */
3174 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3175 lbl = parser_find_label(parser, gt->name);
3177 if (!ast_istype(lbl, ast_label)) {
3178 parseerror(parser, "internal error: label is not an ast_label");
3182 ast_goto_set_label(gt, (ast_label*)lbl);
3185 vec_push(parser->gotos, gt);
3187 if (!parser_next(parser) || parser->tok != ';') {
3188 parseerror(parser, "semicolon expected after goto label");
3191 if (!parser_next(parser)) {
3192 parseerror(parser, "parse error after goto");
3196 *out = (ast_expression*)gt;
3200 static bool parse_skipwhite(parser_t *parser)
3203 if (!parser_next(parser))
3205 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3206 return parser->tok < TOKEN_ERROR;
3209 static bool parse_eol(parser_t *parser)
3211 if (!parse_skipwhite(parser))
3213 return parser->tok == TOKEN_EOL;
3216 static bool parse_pragma_do(parser_t *parser)
3218 if (!parser_next(parser) ||
3219 parser->tok != TOKEN_IDENT ||
3220 strcmp(parser_tokval(parser), "pragma"))
3222 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3225 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3226 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3230 if (!strcmp(parser_tokval(parser), "noref")) {
3231 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3232 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3235 parser->noref = !!parser_token(parser)->constval.i;
3236 if (!parse_eol(parser)) {
3237 parseerror(parser, "parse error after `noref` pragma");
3243 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3250 static bool parse_pragma(parser_t *parser)
3253 parser->lex->flags.preprocessing = true;
3254 parser->lex->flags.mergelines = true;
3255 rv = parse_pragma_do(parser);
3256 if (parser->tok != TOKEN_EOL) {
3257 parseerror(parser, "junk after pragma");
3260 parser->lex->flags.preprocessing = false;
3261 parser->lex->flags.mergelines = false;
3262 if (!parser_next(parser)) {
3263 parseerror(parser, "parse error after pragma");
3269 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3271 bool noref, is_static;
3273 uint32_t qflags = 0;
3274 ast_value *typevar = NULL;
3275 char *vstring = NULL;
3279 if (parser->tok == TOKEN_IDENT)
3280 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3282 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3284 /* local variable */
3286 parseerror(parser, "cannot declare a variable from here");
3289 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3290 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3293 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3297 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3299 if (cvq == CV_WRONG)
3301 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3303 else if (parser->tok == TOKEN_KEYWORD)
3305 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3310 if (!parser_next(parser)) {
3311 parseerror(parser, "parse error after __builtin_debug_printtype");
3315 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3317 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3318 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3319 if (!parser_next(parser)) {
3320 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3326 if (!parse_statement(parser, block, out, allow_cases))
3329 con_out("__builtin_debug_printtype: got no output node\n");
3332 ast_type_to_string(*out, ty, sizeof(ty));
3333 con_out("__builtin_debug_printtype: `%s`\n", ty);
3338 else if (!strcmp(parser_tokval(parser), "return"))
3340 return parse_return(parser, block, out);
3342 else if (!strcmp(parser_tokval(parser), "if"))
3344 return parse_if(parser, block, out);
3346 else if (!strcmp(parser_tokval(parser), "while"))
3348 return parse_while(parser, block, out);
3350 else if (!strcmp(parser_tokval(parser), "do"))
3352 return parse_dowhile(parser, block, out);
3354 else if (!strcmp(parser_tokval(parser), "for"))
3356 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3357 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3360 return parse_for(parser, block, out);
3362 else if (!strcmp(parser_tokval(parser), "break"))
3364 return parse_break_continue(parser, block, out, false);
3366 else if (!strcmp(parser_tokval(parser), "continue"))
3368 return parse_break_continue(parser, block, out, true);
3370 else if (!strcmp(parser_tokval(parser), "switch"))
3372 return parse_switch(parser, block, out);
3374 else if (!strcmp(parser_tokval(parser), "case") ||
3375 !strcmp(parser_tokval(parser), "default"))
3378 parseerror(parser, "unexpected 'case' label");
3383 else if (!strcmp(parser_tokval(parser), "goto"))
3385 return parse_goto(parser, out);
3387 else if (!strcmp(parser_tokval(parser), "typedef"))
3389 if (!parser_next(parser)) {
3390 parseerror(parser, "expected type definition after 'typedef'");
3393 return parse_typedef(parser);
3395 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3398 else if (parser->tok == '{')
3401 inner = parse_block(parser);
3404 *out = (ast_expression*)inner;
3407 else if (parser->tok == ':')
3411 if (!parser_next(parser)) {
3412 parseerror(parser, "expected label name");
3415 if (parser->tok != TOKEN_IDENT) {
3416 parseerror(parser, "label must be an identifier");
3419 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3421 if (!label->undefined) {
3422 parseerror(parser, "label `%s` already defined", label->name);
3425 label->undefined = false;
3428 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3429 vec_push(parser->labels, label);
3431 *out = (ast_expression*)label;
3432 if (!parser_next(parser)) {
3433 parseerror(parser, "parse error after label");
3436 for (i = 0; i < vec_size(parser->gotos); ++i) {
3437 if (!strcmp(parser->gotos[i]->name, label->name)) {
3438 ast_goto_set_label(parser->gotos[i], label);
3439 vec_remove(parser->gotos, i, 1);
3445 else if (parser->tok == ';')
3447 if (!parser_next(parser)) {
3448 parseerror(parser, "parse error after empty statement");
3455 lex_ctx_t ctx = parser_ctx(parser);
3456 ast_expression *exp = parse_expression(parser, false, false);
3460 if (!ast_side_effects(exp)) {
3461 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3468 static bool parse_enum(parser_t *parser)
3471 bool reverse = false;
3473 ast_value **values = NULL;
3474 ast_value *var = NULL;
3477 ast_expression *old;
3479 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3480 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3484 /* enumeration attributes (can add more later) */
3485 if (parser->tok == ':') {
3486 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3487 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3492 if (!strcmp(parser_tokval(parser), "flag")) {
3496 else if (!strcmp(parser_tokval(parser), "reverse")) {
3500 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3504 if (!parser_next(parser) || parser->tok != '{') {
3505 parseerror(parser, "expected `{` after enum attribute ");
3511 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3512 if (parser->tok == '}') {
3513 /* allow an empty enum */
3516 parseerror(parser, "expected identifier or `}`");
3520 old = parser_find_field(parser, parser_tokval(parser));
3522 old = parser_find_global(parser, parser_tokval(parser));
3524 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3525 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3529 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3530 vec_push(values, var);
3531 var->cvq = CV_CONST;
3532 var->hasvalue = true;
3534 /* for flagged enumerations increment in POTs of TWO */
3535 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3536 parser_addglobal(parser, var->name, (ast_expression*)var);
3538 if (!parser_next(parser)) {
3539 parseerror(parser, "expected `=`, `}` or comma after identifier");
3543 if (parser->tok == ',')
3545 if (parser->tok == '}')
3547 if (parser->tok != '=') {
3548 parseerror(parser, "expected `=`, `}` or comma after identifier");
3552 if (!parser_next(parser)) {
3553 parseerror(parser, "expected expression after `=`");
3557 /* We got a value! */
3558 old = parse_expression_leave(parser, true, false, false);
3559 asvalue = (ast_value*)old;
3560 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3561 compile_error(ast_ctx(var), "constant value or expression expected");
3564 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3566 if (parser->tok == '}')
3568 if (parser->tok != ',') {
3569 parseerror(parser, "expected `}` or comma after expression");
3574 /* patch them all (for reversed attribute) */
3577 for (i = 0; i < vec_size(values); i++)
3578 values[i]->constval.vfloat = vec_size(values) - i - 1;
3581 if (parser->tok != '}') {
3582 parseerror(parser, "internal error: breaking without `}`");
3586 if (!parser_next(parser) || parser->tok != ';') {
3587 parseerror(parser, "expected semicolon after enumeration");
3591 if (!parser_next(parser)) {
3592 parseerror(parser, "parse error after enumeration");
3604 static bool parse_block_into(parser_t *parser, ast_block *block)
3608 parser_enterblock(parser);
3610 if (!parser_next(parser)) { /* skip the '{' */
3611 parseerror(parser, "expected function body");
3615 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3617 ast_expression *expr = NULL;
3618 if (parser->tok == '}')
3621 if (!parse_statement(parser, block, &expr, false)) {
3622 /* parseerror(parser, "parse error"); */
3628 if (!ast_block_add_expr(block, expr)) {
3635 if (parser->tok != '}') {
3638 (void)parser_next(parser);
3642 if (!parser_leaveblock(parser))
3644 return retval && !!block;
3647 static ast_block* parse_block(parser_t *parser)
3650 block = ast_block_new(parser_ctx(parser));
3653 if (!parse_block_into(parser, block)) {
3654 ast_block_delete(block);
3660 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3662 if (parser->tok == '{') {
3663 *out = (ast_expression*)parse_block(parser);
3666 return parse_statement(parser, NULL, out, false);
3669 static bool create_vector_members(ast_value *var, ast_member **me)
3672 size_t len = strlen(var->name);
3674 for (i = 0; i < 3; ++i) {
3675 char *name = (char*)mem_a(len+3);
3676 memcpy(name, var->name, len);
3678 name[len+1] = 'x'+i;
3680 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3689 do { ast_member_delete(me[--i]); } while(i);
3693 static bool parse_function_body(parser_t *parser, ast_value *var)
3695 ast_block *block = NULL;
3700 ast_expression *framenum = NULL;
3701 ast_expression *nextthink = NULL;
3702 /* None of the following have to be deleted */
3703 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3704 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3705 bool has_frame_think;
3709 has_frame_think = false;
3710 old = parser->function;
3712 if (var->expression.flags & AST_FLAG_ALIAS) {
3713 parseerror(parser, "function aliases cannot have bodies");
3717 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3718 parseerror(parser, "gotos/labels leaking");
3722 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3723 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3724 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3730 if (parser->tok == '[') {
3731 /* got a frame definition: [ framenum, nextthink ]
3732 * this translates to:
3733 * self.frame = framenum;
3734 * self.nextthink = time + 0.1;
3735 * self.think = nextthink;
3739 fld_think = parser_find_field(parser, "think");
3740 fld_nextthink = parser_find_field(parser, "nextthink");
3741 fld_frame = parser_find_field(parser, "frame");
3742 if (!fld_think || !fld_nextthink || !fld_frame) {
3743 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3744 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3747 gbl_time = parser_find_global(parser, "time");
3748 gbl_self = parser_find_global(parser, "self");
3749 if (!gbl_time || !gbl_self) {
3750 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3751 parseerror(parser, "please declare the following globals: `time`, `self`");
3755 if (!parser_next(parser))
3758 framenum = parse_expression_leave(parser, true, false, false);
3760 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3763 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3764 ast_unref(framenum);
3765 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3769 if (parser->tok != ',') {
3770 ast_unref(framenum);
3771 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3772 parseerror(parser, "Got a %i\n", parser->tok);
3776 if (!parser_next(parser)) {
3777 ast_unref(framenum);
3781 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3783 /* qc allows the use of not-yet-declared functions here
3784 * - this automatically creates a prototype */
3785 ast_value *thinkfunc;
3786 ast_expression *functype = fld_think->next;
3788 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3789 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3790 ast_unref(framenum);
3791 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3794 ast_type_adopt(thinkfunc, functype);
3796 if (!parser_next(parser)) {
3797 ast_unref(framenum);
3798 ast_delete(thinkfunc);
3802 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3804 nextthink = (ast_expression*)thinkfunc;
3807 nextthink = parse_expression_leave(parser, true, false, false);
3809 ast_unref(framenum);
3810 parseerror(parser, "expected a think-function in [frame,think] notation");
3815 if (!ast_istype(nextthink, ast_value)) {
3816 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3820 if (retval && parser->tok != ']') {
3821 parseerror(parser, "expected closing `]` for [frame,think] notation");
3825 if (retval && !parser_next(parser)) {
3829 if (retval && parser->tok != '{') {
3830 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3835 ast_unref(nextthink);
3836 ast_unref(framenum);
3840 has_frame_think = true;
3843 block = ast_block_new(parser_ctx(parser));
3845 parseerror(parser, "failed to allocate block");
3846 if (has_frame_think) {
3847 ast_unref(nextthink);
3848 ast_unref(framenum);
3853 if (has_frame_think) {
3855 ast_expression *self_frame;
3856 ast_expression *self_nextthink;
3857 ast_expression *self_think;
3858 ast_expression *time_plus_1;
3859 ast_store *store_frame;
3860 ast_store *store_nextthink;
3861 ast_store *store_think;
3863 ctx = parser_ctx(parser);
3864 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3865 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3866 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3868 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3869 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1));
3871 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3872 if (self_frame) ast_delete(self_frame);
3873 if (self_nextthink) ast_delete(self_nextthink);
3874 if (self_think) ast_delete(self_think);
3875 if (time_plus_1) ast_delete(time_plus_1);
3881 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3882 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3883 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3886 ast_delete(self_frame);
3889 if (!store_nextthink) {
3890 ast_delete(self_nextthink);
3894 ast_delete(self_think);
3898 if (store_frame) ast_delete(store_frame);
3899 if (store_nextthink) ast_delete(store_nextthink);
3900 if (store_think) ast_delete(store_think);
3903 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3904 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3905 !ast_block_add_expr(block, (ast_expression*)store_think))
3912 parseerror(parser, "failed to generate code for [frame,think]");
3913 ast_unref(nextthink);
3914 ast_unref(framenum);
3920 if (var->hasvalue) {
3921 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3922 ast_block_delete(block);
3926 func = ast_function_new(ast_ctx(var), var->name, var);
3928 parseerror(parser, "failed to allocate function for `%s`", var->name);
3929 ast_block_delete(block);
3932 vec_push(parser->functions, func);
3934 parser_enterblock(parser);
3936 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3938 ast_value *param = var->expression.params[parami];
3941 if (param->expression.vtype != TYPE_VECTOR &&
3942 (param->expression.vtype != TYPE_FIELD ||
3943 param->expression.next->vtype != TYPE_VECTOR))
3948 if (!create_vector_members(param, me)) {
3949 ast_block_delete(block);
3953 for (e = 0; e < 3; ++e) {
3954 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3955 ast_block_collect(block, (ast_expression*)me[e]);
3959 if (var->argcounter) {
3960 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3961 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3965 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3967 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3968 varargs->expression.flags |= AST_FLAG_IS_VARARG;
3969 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3970 varargs->expression.count = 0;
3971 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
3972 if (!parser_create_array_setter_proto(parser, varargs, name)) {
3973 ast_delete(varargs);
3974 ast_block_delete(block);
3977 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
3978 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
3979 ast_delete(varargs);
3980 ast_block_delete(block);
3983 func->varargs = varargs;
3984 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
3987 parser->function = func;
3988 if (!parse_block_into(parser, block)) {
3989 ast_block_delete(block);
3993 vec_push(func->blocks, block);
3996 parser->function = old;
3997 if (!parser_leaveblock(parser))
3999 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4000 parseerror(parser, "internal error: local scopes left");
4004 if (parser->tok == ';')
4005 return parser_next(parser);
4006 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4007 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4011 (void)!parser_leaveblock(parser);
4012 vec_pop(parser->functions);
4013 ast_function_delete(func);
4014 var->constval.vfunc = NULL;
4017 parser->function = old;
4021 static ast_expression *array_accessor_split(
4026 ast_expression *left,
4027 ast_expression *right
4033 lex_ctx_t ctx = ast_ctx(array);
4035 if (!left || !right) {
4036 if (left) ast_delete(left);
4037 if (right) ast_delete(right);
4041 cmp = ast_binary_new(ctx, INSTR_LT,
4042 (ast_expression*)index,
4043 (ast_expression*)fold_constgen_float(parser->fold, middle));
4047 parseerror(parser, "internal error: failed to create comparison for array setter");
4051 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4053 ast_delete(cmp); /* will delete left and right */
4054 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4058 return (ast_expression*)ifthen;
4061 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4063 lex_ctx_t ctx = ast_ctx(array);
4065 if (from+1 == afterend) {
4066 /* set this value */
4069 ast_array_index *subscript;
4071 int assignop = type_store_instr[value->expression.vtype];
4073 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4074 assignop = INSTR_STORE_V;
4076 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4080 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4082 ast_delete(subscript);
4086 block = ast_block_new(ctx);
4092 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4097 ret = ast_return_new(ctx, NULL);
4103 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4108 return (ast_expression*)block;
4110 ast_expression *left, *right;
4111 size_t diff = afterend - from;
4112 size_t middle = from + diff/2;
4113 left = array_setter_node(parser, array, index, value, from, middle);
4114 right = array_setter_node(parser, array, index, value, middle, afterend);
4115 return array_accessor_split(parser, array, index, middle, left, right);
4119 static ast_expression *array_field_setter_node(
4128 lex_ctx_t ctx = ast_ctx(array);
4130 if (from+1 == afterend) {
4131 /* set this value */
4134 ast_entfield *entfield;
4135 ast_array_index *subscript;
4137 int assignop = type_storep_instr[value->expression.vtype];
4139 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4140 assignop = INSTR_STOREP_V;
4142 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4146 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4147 subscript->expression.vtype = TYPE_FIELD;
4149 entfield = ast_entfield_new_force(ctx,
4150 (ast_expression*)entity,
4151 (ast_expression*)subscript,
4152 (ast_expression*)subscript);
4154 ast_delete(subscript);
4158 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4160 ast_delete(entfield);
4164 block = ast_block_new(ctx);
4170 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4175 ret = ast_return_new(ctx, NULL);
4181 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4186 return (ast_expression*)block;
4188 ast_expression *left, *right;
4189 size_t diff = afterend - from;
4190 size_t middle = from + diff/2;
4191 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4192 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4193 return array_accessor_split(parser, array, index, middle, left, right);
4197 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4199 lex_ctx_t ctx = ast_ctx(array);
4201 if (from+1 == afterend) {
4203 ast_array_index *subscript;
4205 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4209 ret = ast_return_new(ctx, (ast_expression*)subscript);
4211 ast_delete(subscript);
4215 return (ast_expression*)ret;
4217 ast_expression *left, *right;
4218 size_t diff = afterend - from;
4219 size_t middle = from + diff/2;
4220 left = array_getter_node(parser, array, index, from, middle);
4221 right = array_getter_node(parser, array, index, middle, afterend);
4222 return array_accessor_split(parser, array, index, middle, left, right);
4226 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4228 ast_function *func = NULL;
4229 ast_value *fval = NULL;
4230 ast_block *body = NULL;
4232 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4234 parseerror(parser, "failed to create accessor function value");
4238 func = ast_function_new(ast_ctx(array), funcname, fval);
4241 parseerror(parser, "failed to create accessor function node");
4245 body = ast_block_new(ast_ctx(array));
4247 parseerror(parser, "failed to create block for array accessor");
4253 vec_push(func->blocks, body);
4256 vec_push(parser->accessors, fval);
4261 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4263 ast_value *index = NULL;
4264 ast_value *value = NULL;
4268 if (!ast_istype(array->expression.next, ast_value)) {
4269 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4273 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4275 func = fval->constval.vfunc;
4276 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4278 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4279 value = ast_value_copy((ast_value*)array->expression.next);
4281 if (!index || !value) {
4282 parseerror(parser, "failed to create locals for array accessor");
4285 (void)!ast_value_set_name(value, "value"); /* not important */
4286 vec_push(fval->expression.params, index);
4287 vec_push(fval->expression.params, value);
4289 array->setter = fval;
4292 if (index) ast_delete(index);
4293 if (value) ast_delete(value);
4299 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4301 ast_expression *root = NULL;
4302 root = array_setter_node(parser, array,
4303 array->setter->expression.params[0],
4304 array->setter->expression.params[1],
4305 0, array->expression.count);
4307 parseerror(parser, "failed to build accessor search tree");
4310 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4317 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4319 if (!parser_create_array_setter_proto(parser, array, funcname))
4321 return parser_create_array_setter_impl(parser, array);
4324 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4326 ast_expression *root = NULL;
4327 ast_value *entity = NULL;
4328 ast_value *index = NULL;
4329 ast_value *value = NULL;
4333 if (!ast_istype(array->expression.next, ast_value)) {
4334 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4338 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4340 func = fval->constval.vfunc;
4341 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4343 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4344 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4345 value = ast_value_copy((ast_value*)array->expression.next);
4346 if (!entity || !index || !value) {
4347 parseerror(parser, "failed to create locals for array accessor");
4350 (void)!ast_value_set_name(value, "value"); /* not important */
4351 vec_push(fval->expression.params, entity);
4352 vec_push(fval->expression.params, index);
4353 vec_push(fval->expression.params, value);
4355 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4357 parseerror(parser, "failed to build accessor search tree");
4361 array->setter = fval;
4362 return ast_block_add_expr(func->blocks[0], root);
4364 if (entity) ast_delete(entity);
4365 if (index) ast_delete(index);
4366 if (value) ast_delete(value);
4367 if (root) ast_delete(root);
4373 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4375 ast_value *index = NULL;
4379 /* NOTE: checking array->expression.next rather than elemtype since
4380 * for fields elemtype is a temporary fieldtype.
4382 if (!ast_istype(array->expression.next, ast_value)) {
4383 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4387 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4389 func = fval->constval.vfunc;
4390 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4392 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4395 parseerror(parser, "failed to create locals for array accessor");
4398 vec_push(fval->expression.params, index);
4400 array->getter = fval;
4403 if (index) ast_delete(index);
4409 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4411 ast_expression *root = NULL;
4413 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4415 parseerror(parser, "failed to build accessor search tree");
4418 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4425 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4427 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4429 return parser_create_array_getter_impl(parser, array);
4432 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4433 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4441 bool variadic = false;
4442 ast_value *varparam = NULL;
4443 char *argcounter = NULL;
4445 ctx = parser_ctx(parser);
4447 /* for the sake of less code we parse-in in this function */
4448 if (!parser_next(parser)) {
4450 parseerror(parser, "expected parameter list");
4456 /* parse variables until we hit a closing paren */
4457 while (parser->tok != ')') {
4459 /* there must be commas between them */
4460 if (parser->tok != ',') {
4461 parseerror(parser, "expected comma or end of parameter list");
4464 if (!parser_next(parser)) {
4465 parseerror(parser, "expected parameter");
4471 if (parser->tok == TOKEN_DOTS) {
4472 /* '...' indicates a varargs function */
4474 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4475 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4478 if (parser->tok == TOKEN_IDENT) {
4479 argcounter = util_strdup(parser_tokval(parser));
4480 if (!parser_next(parser) || parser->tok != ')') {
4481 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4488 /* for anything else just parse a typename */
4489 param = parse_typename(parser, NULL, NULL);
4492 vec_push(params, param);
4493 if (param->expression.vtype >= TYPE_VARIANT) {
4494 char tname[1024]; /* typename is reserved in C++ */
4495 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4496 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4499 /* type-restricted varargs */
4500 if (parser->tok == TOKEN_DOTS) {
4502 varparam = vec_last(params);
4504 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4505 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4508 if (parser->tok == TOKEN_IDENT) {
4509 argcounter = util_strdup(parser_tokval(parser));
4510 if (!parser_next(parser) || parser->tok != ')') {
4511 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4519 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4523 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4524 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4527 if (!parser_next(parser)) {
4528 parseerror(parser, "parse error after typename");
4532 /* now turn 'var' into a function type */
4533 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4534 fval->expression.next = (ast_expression*)var;
4536 fval->expression.flags |= AST_FLAG_VARIADIC;
4539 var->expression.params = params;
4540 var->expression.varparam = (ast_expression*)varparam;
4541 var->argcounter = argcounter;
4550 ast_delete(varparam);
4552 for (i = 0; i < vec_size(params); ++i)
4553 ast_delete(params[i]);
4558 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4560 ast_expression *cexp;
4561 ast_value *cval, *tmp;
4564 ctx = parser_ctx(parser);
4566 if (!parser_next(parser)) {
4568 parseerror(parser, "expected array-size");
4572 if (parser->tok != ']') {
4573 cexp = parse_expression_leave(parser, true, false, false);
4575 if (!cexp || !ast_istype(cexp, ast_value)) {
4579 parseerror(parser, "expected array-size as constant positive integer");
4582 cval = (ast_value*)cexp;
4589 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4590 tmp->expression.next = (ast_expression*)var;
4594 if (cval->expression.vtype == TYPE_INTEGER)
4595 tmp->expression.count = cval->constval.vint;
4596 else if (cval->expression.vtype == TYPE_FLOAT)
4597 tmp->expression.count = cval->constval.vfloat;
4601 parseerror(parser, "array-size must be a positive integer constant");
4607 var->expression.count = -1;
4608 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4611 if (parser->tok != ']') {
4613 parseerror(parser, "expected ']' after array-size");
4616 if (!parser_next(parser)) {
4618 parseerror(parser, "error after parsing array size");
4624 /* Parse a complete typename.
4625 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4626 * but when parsing variables separated by comma
4627 * 'storebase' should point to where the base-type should be kept.
4628 * The base type makes up every bit of type information which comes *before* the
4631 * The following will be parsed in its entirety:
4633 * The 'basetype' in this case is 'void()'
4634 * and if there's a comma after it, say:
4636 * then the type-information 'void()' can be stored in 'storebase'
4638 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4640 ast_value *var, *tmp;
4643 const char *name = NULL;
4644 bool isfield = false;
4645 bool wasarray = false;
4646 size_t morefields = 0;
4648 ctx = parser_ctx(parser);
4650 /* types may start with a dot */
4651 if (parser->tok == '.') {
4653 /* if we parsed a dot we need a typename now */
4654 if (!parser_next(parser)) {
4655 parseerror(parser, "expected typename for field definition");
4659 /* Further dots are handled seperately because they won't be part of the
4662 while (parser->tok == '.') {
4664 if (!parser_next(parser)) {
4665 parseerror(parser, "expected typename for field definition");
4670 if (parser->tok == TOKEN_IDENT)
4671 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4672 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4673 parseerror(parser, "expected typename");
4677 /* generate the basic type value */
4678 if (cached_typedef) {
4679 var = ast_value_copy(cached_typedef);
4680 ast_value_set_name(var, "<type(from_def)>");
4682 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4684 for (; morefields; --morefields) {
4685 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4686 tmp->expression.next = (ast_expression*)var;
4690 /* do not yet turn into a field - remember:
4691 * .void() foo; is a field too
4692 * .void()() foo; is a function
4696 if (!parser_next(parser)) {
4698 parseerror(parser, "parse error after typename");
4702 /* an opening paren now starts the parameter-list of a function
4703 * this is where original-QC has parameter lists.
4704 * We allow a single parameter list here.
4705 * Much like fteqcc we don't allow `float()() x`
4707 if (parser->tok == '(') {
4708 var = parse_parameter_list(parser, var);
4713 /* store the base if requested */
4715 *storebase = ast_value_copy(var);
4717 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4718 tmp->expression.next = (ast_expression*)*storebase;
4723 /* there may be a name now */
4724 if (parser->tok == TOKEN_IDENT) {
4725 name = util_strdup(parser_tokval(parser));
4727 if (!parser_next(parser)) {
4730 parseerror(parser, "error after variable or field declaration");
4735 /* now this may be an array */
4736 if (parser->tok == '[') {
4738 var = parse_arraysize(parser, var);
4740 if (name) mem_d(name);
4745 /* This is the point where we can turn it into a field */
4747 /* turn it into a field if desired */
4748 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4749 tmp->expression.next = (ast_expression*)var;
4753 /* now there may be function parens again */
4754 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4755 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4756 if (parser->tok == '(' && wasarray)
4757 parseerror(parser, "arrays as part of a return type is not supported");
4758 while (parser->tok == '(') {
4759 var = parse_parameter_list(parser, var);
4761 if (name) mem_d(name);
4766 /* finally name it */
4768 if (!ast_value_set_name(var, name)) {
4771 parseerror(parser, "internal error: failed to set name");
4774 /* free the name, ast_value_set_name duplicates */
4781 static bool parse_typedef(parser_t *parser)
4783 ast_value *typevar, *oldtype;
4784 ast_expression *old;
4786 typevar = parse_typename(parser, NULL, NULL);
4791 if ( (old = parser_find_var(parser, typevar->name)) ) {
4792 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4793 " -> `%s` has been declared here: %s:%i",
4794 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4795 ast_delete(typevar);
4799 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4800 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4801 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4802 ast_delete(typevar);
4806 vec_push(parser->_typedefs, typevar);
4807 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4809 if (parser->tok != ';') {
4810 parseerror(parser, "expected semicolon after typedef");
4813 if (!parser_next(parser)) {
4814 parseerror(parser, "parse error after typedef");
4821 static const char *cvq_to_str(int cvq) {
4823 case CV_NONE: return "none";
4824 case CV_VAR: return "`var`";
4825 case CV_CONST: return "`const`";
4826 default: return "<INVALID>";
4830 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4833 if (proto->cvq != var->cvq) {
4834 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4835 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4836 parser->tok == '='))
4838 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4839 "`%s` declared with different qualifiers: %s\n"
4840 " -> previous declaration here: %s:%i uses %s",
4841 var->name, cvq_to_str(var->cvq),
4842 ast_ctx(proto).file, ast_ctx(proto).line,
4843 cvq_to_str(proto->cvq));
4846 av = (var ->expression.flags & AST_FLAG_NORETURN);
4847 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4849 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4850 "`%s` declared with different attributes%s\n"
4851 " -> previous declaration here: %s:%i",
4852 var->name, (av ? ": noreturn" : ""),
4853 ast_ctx(proto).file, ast_ctx(proto).line,
4854 (ao ? ": noreturn" : ""));
4859 static bool create_array_accessors(parser_t *parser, ast_value *var)
4862 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4863 if (!parser_create_array_setter(parser, var, name))
4865 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4866 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4871 static bool parse_array(parser_t *parser, ast_value *array)
4874 if (array->initlist) {
4875 parseerror(parser, "array already initialized elsewhere");
4878 if (!parser_next(parser)) {
4879 parseerror(parser, "parse error in array initializer");
4883 while (parser->tok != '}') {
4884 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4887 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4889 parseerror(parser, "initializing element must be a compile time constant");
4892 vec_push(array->initlist, v->constval);
4893 if (v->expression.vtype == TYPE_STRING) {
4894 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4898 if (parser->tok == '}')
4900 if (parser->tok != ',' || !parser_next(parser)) {
4901 parseerror(parser, "expected comma or '}' in element list");
4905 if (!parser_next(parser) || parser->tok != ';') {
4906 parseerror(parser, "expected semicolon after initializer, got %s");
4910 if (!parser_next(parser)) {
4911 parseerror(parser, "parse error after initializer");
4916 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4917 if (array->expression.count != (size_t)-1) {
4918 parseerror(parser, "array `%s' has already been initialized with %u elements",
4919 array->name, (unsigned)array->expression.count);
4921 array->expression.count = vec_size(array->initlist);
4922 if (!create_array_accessors(parser, array))
4928 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)
4932 ast_expression *old;
4936 ast_value *basetype = NULL;
4938 bool isparam = false;
4939 bool isvector = false;
4940 bool cleanvar = true;
4941 bool wasarray = false;
4943 ast_member *me[3] = { NULL, NULL, NULL };
4945 if (!localblock && is_static)
4946 parseerror(parser, "`static` qualifier is not supported in global scope");
4948 /* get the first complete variable */
4949 var = parse_typename(parser, &basetype, cached_typedef);
4952 ast_delete(basetype);
4960 /* Part 0: finish the type */
4961 if (parser->tok == '(') {
4962 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4963 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4964 var = parse_parameter_list(parser, var);
4970 /* we only allow 1-dimensional arrays */
4971 if (parser->tok == '[') {
4973 var = parse_arraysize(parser, var);
4979 if (parser->tok == '(' && wasarray) {
4980 parseerror(parser, "arrays as part of a return type is not supported");
4981 /* we'll still parse the type completely for now */
4983 /* for functions returning functions */
4984 while (parser->tok == '(') {
4985 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4986 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4987 var = parse_parameter_list(parser, var);
4994 var->cvq = qualifier;
4995 var->expression.flags |= qflags;
4998 * store the vstring back to var for alias and
4999 * deprecation messages.
5001 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5002 var->expression.flags & AST_FLAG_ALIAS)
5003 var->desc = vstring;
5006 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5007 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5008 * is then filled with the previous definition and the parameter-names replaced.
5010 if (!strcmp(var->name, "nil")) {
5011 if (OPTS_FLAG(UNTYPED_NIL)) {
5012 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5013 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5015 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5018 /* Deal with end_sys_ vars */
5020 if (!strcmp(var->name, "end_sys_globals")) {
5022 parser->crc_globals = vec_size(parser->globals);
5025 else if (!strcmp(var->name, "end_sys_fields")) {
5027 parser->crc_fields = vec_size(parser->fields);
5030 if (was_end && var->expression.vtype == TYPE_FIELD) {
5031 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5032 "global '%s' hint should not be a field",
5033 parser_tokval(parser)))
5040 if (!nofields && var->expression.vtype == TYPE_FIELD)
5042 /* deal with field declarations */
5043 old = parser_find_field(parser, var->name);
5045 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5046 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5055 parseerror(parser, "field `%s` already declared here: %s:%i",
5056 var->name, ast_ctx(old).file, ast_ctx(old).line);
5061 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5062 (old = parser_find_global(parser, var->name)))
5064 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5065 parseerror(parser, "field `%s` already declared here: %s:%i",
5066 var->name, ast_ctx(old).file, ast_ctx(old).line);
5073 /* deal with other globals */
5074 old = parser_find_global(parser, var->name);
5075 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5077 /* This is a function which had a prototype */
5078 if (!ast_istype(old, ast_value)) {
5079 parseerror(parser, "internal error: prototype is not an ast_value");
5083 proto = (ast_value*)old;
5084 proto->desc = var->desc;
5085 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5086 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5088 ast_ctx(proto).file, ast_ctx(proto).line);
5092 /* we need the new parameter-names */
5093 for (i = 0; i < vec_size(proto->expression.params); ++i)
5094 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5095 if (!parser_check_qualifiers(parser, var, proto)) {
5102 proto->expression.flags |= var->expression.flags;
5110 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5111 "global `%s` already declared here: %s:%i",
5112 var->name, ast_ctx(old).file, ast_ctx(old).line))
5117 proto = (ast_value*)old;
5118 if (!ast_istype(old, ast_value)) {
5119 parseerror(parser, "internal error: not an ast_value");
5124 if (!parser_check_qualifiers(parser, var, proto)) {
5129 proto->expression.flags |= var->expression.flags;
5133 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5134 (old = parser_find_field(parser, var->name)))
5136 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5137 parseerror(parser, "global `%s` already declared here: %s:%i",
5138 var->name, ast_ctx(old).file, ast_ctx(old).line);
5145 else /* it's not a global */
5147 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5148 if (old && !isparam) {
5149 parseerror(parser, "local `%s` already declared here: %s:%i",
5150 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5154 old = parser_find_local(parser, var->name, 0, &isparam);
5155 if (old && isparam) {
5156 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5157 "local `%s` is shadowing a parameter", var->name))
5159 parseerror(parser, "local `%s` already declared here: %s:%i",
5160 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5164 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5172 /* in a noref section we simply bump the usecount */
5173 if (noref || parser->noref)
5177 * Create the global/local, and deal with vector types.
5180 if (var->expression.vtype == TYPE_VECTOR)
5182 else if (var->expression.vtype == TYPE_FIELD &&
5183 var->expression.next->vtype == TYPE_VECTOR)
5187 if (!create_vector_members(var, me)) {
5194 /* deal with global variables, fields, functions */
5195 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5196 var->isfield = true;
5197 vec_push(parser->fields, (ast_expression*)var);
5198 util_htset(parser->htfields, var->name, var);
5200 for (i = 0; i < 3; ++i) {
5201 vec_push(parser->fields, (ast_expression*)me[i]);
5202 util_htset(parser->htfields, me[i]->name, me[i]);
5207 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5208 parser_addglobal(parser, var->name, (ast_expression*)var);
5210 for (i = 0; i < 3; ++i) {
5211 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5215 ast_expression *find = parser_find_global(parser, var->desc);
5218 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5222 if (var->expression.vtype != find->vtype) {
5226 ast_type_to_string(find, ty1, sizeof(ty1));
5227 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5229 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5236 * add alias to aliases table and to corrector
5237 * so corrections can apply for aliases as well.
5239 util_htset(parser->aliases, var->name, find);
5242 * add to corrector so corrections can work
5243 * even for aliases too.
5246 vec_last(parser->correct_variables),
5247 &vec_last(parser->correct_variables_score),
5251 /* generate aliases for vector components */
5255 util_asprintf(&buffer[0], "%s_x", var->desc);
5256 util_asprintf(&buffer[1], "%s_y", var->desc);
5257 util_asprintf(&buffer[2], "%s_z", var->desc);
5259 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5260 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5261 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5268 * add to corrector so corrections can work
5269 * even for aliases too.
5272 vec_last(parser->correct_variables),
5273 &vec_last(parser->correct_variables_score),
5277 vec_last(parser->correct_variables),
5278 &vec_last(parser->correct_variables_score),
5282 vec_last(parser->correct_variables),
5283 &vec_last(parser->correct_variables_score),
5291 /* a static adds itself to be generated like any other global
5292 * but is added to the local namespace instead
5294 char *defname = NULL;
5295 size_t prefix_len, ln;
5297 ln = strlen(parser->function->name);
5298 vec_append(defname, ln, parser->function->name);
5300 vec_append(defname, 2, "::");
5301 /* remember the length up to here */
5302 prefix_len = vec_size(defname);
5304 /* Add it to the local scope */
5305 util_htset(vec_last(parser->variables), var->name, (void*)var);
5309 vec_last(parser->correct_variables),
5310 &vec_last(parser->correct_variables_score),
5314 /* now rename the global */
5315 ln = strlen(var->name);
5316 vec_append(defname, ln, var->name);
5317 ast_value_set_name(var, defname);
5319 /* push it to the to-be-generated globals */
5320 vec_push(parser->globals, (ast_expression*)var);
5322 /* same game for the vector members */
5324 for (i = 0; i < 3; ++i) {
5325 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5329 vec_last(parser->correct_variables),
5330 &vec_last(parser->correct_variables_score),
5334 vec_shrinkto(defname, prefix_len);
5335 ln = strlen(me[i]->name);
5336 vec_append(defname, ln, me[i]->name);
5337 ast_member_set_name(me[i], defname);
5339 vec_push(parser->globals, (ast_expression*)me[i]);
5344 vec_push(localblock->locals, var);
5345 parser_addlocal(parser, var->name, (ast_expression*)var);
5347 for (i = 0; i < 3; ++i) {
5348 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5349 ast_block_collect(localblock, (ast_expression*)me[i]);
5355 me[0] = me[1] = me[2] = NULL;
5360 if (var->expression.vtype == TYPE_ARRAY) {
5361 if (var->expression.count != (size_t)-1) {
5362 if (!create_array_accessors(parser, var))
5366 else if (!localblock && !nofields &&
5367 var->expression.vtype == TYPE_FIELD &&
5368 var->expression.next->vtype == TYPE_ARRAY)
5371 ast_expression *telem;
5373 ast_value *array = (ast_value*)var->expression.next;
5375 if (!ast_istype(var->expression.next, ast_value)) {
5376 parseerror(parser, "internal error: field element type must be an ast_value");
5380 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5381 if (!parser_create_array_field_setter(parser, array, name))
5384 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5385 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5386 tfield->expression.next = telem;
5387 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5388 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5396 if (parser->tok == ';') {
5397 ast_delete(basetype);
5398 if (!parser_next(parser)) {
5399 parseerror(parser, "error after variable declaration");
5405 if (parser->tok == ',')
5409 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5412 parseerror(parser, "missing comma or semicolon while parsing variables");
5416 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5417 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5418 "initializing expression turns variable `%s` into a constant in this standard",
5425 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5426 if (parser->tok != '=') {
5427 if (!strcmp(parser_tokval(parser), "break")) {
5428 if (!parser_next(parser)) {
5429 parseerror(parser, "error parsing break definition");
5432 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5434 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5439 if (!parser_next(parser)) {
5440 parseerror(parser, "error parsing initializer");
5444 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5445 parseerror(parser, "expected '=' before function body in this standard");
5448 if (parser->tok == '#') {
5449 ast_function *func = NULL;
5450 ast_value *number = NULL;
5456 parseerror(parser, "cannot declare builtins within functions");
5459 if (var->expression.vtype != TYPE_FUNCTION) {
5460 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5463 if (!parser_next(parser)) {
5464 parseerror(parser, "expected builtin number");
5468 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5469 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5471 parseerror(parser, "builtin number expected");
5474 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5477 parseerror(parser, "builtin number must be a compile time constant");
5480 if (number->expression.vtype == TYPE_INTEGER)
5481 builtin_num = number->constval.vint;
5482 else if (number->expression.vtype == TYPE_FLOAT)
5483 builtin_num = number->constval.vfloat;
5486 parseerror(parser, "builtin number must be an integer constant");
5491 fractional = modff(builtin_num, &integral);
5492 if (builtin_num < 0 || fractional != 0) {
5493 parseerror(parser, "builtin number must be an integer greater than zero");
5497 /* we only want the integral part anyways */
5498 builtin_num = integral;
5499 } else if (parser->tok == TOKEN_INTCONST) {
5500 builtin_num = parser_token(parser)->constval.i;
5502 parseerror(parser, "builtin number must be a compile time constant");
5506 if (var->hasvalue) {
5507 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5508 "builtin `%s` has already been defined\n"
5509 " -> previous declaration here: %s:%i",
5510 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5514 func = ast_function_new(ast_ctx(var), var->name, var);
5516 parseerror(parser, "failed to allocate function for `%s`", var->name);
5519 vec_push(parser->functions, func);
5521 func->builtin = -builtin_num-1;
5524 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5525 ? (parser->tok != ',' && parser->tok != ';')
5526 : (!parser_next(parser)))
5528 parseerror(parser, "expected comma or semicolon");
5530 ast_function_delete(func);
5531 var->constval.vfunc = NULL;
5535 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5538 /* Note that fteqcc and most others don't even *have*
5539 * local arrays, so this is not a high priority.
5541 parseerror(parser, "TODO: initializers for local arrays");
5545 var->hasvalue = true;
5546 if (!parse_array(parser, var))
5549 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5552 parseerror(parser, "cannot declare functions within functions");
5557 ast_ctx(proto) = parser_ctx(parser);
5559 if (!parse_function_body(parser, var))
5561 ast_delete(basetype);
5562 for (i = 0; i < vec_size(parser->gotos); ++i)
5563 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5564 vec_free(parser->gotos);
5565 vec_free(parser->labels);
5568 ast_expression *cexp;
5571 cexp = parse_expression_leave(parser, true, false, false);
5576 cval = (ast_value*)cexp;
5577 if (cval != parser->nil &&
5578 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5581 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5585 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5586 qualifier != CV_VAR)
5588 var->cvq = CV_CONST;
5590 if (cval == parser->nil)
5591 var->expression.flags |= AST_FLAG_INITIALIZED;
5594 var->hasvalue = true;
5595 if (cval->expression.vtype == TYPE_STRING)
5596 var->constval.vstring = parser_strdup(cval->constval.vstring);
5597 else if (cval->expression.vtype == TYPE_FIELD)
5598 var->constval.vfield = cval;
5600 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5606 shunt sy = { NULL, NULL, NULL, NULL };
5609 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5610 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5611 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5612 if (!parser_sy_apply_operator(parser, &sy))
5615 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5616 parseerror(parser, "internal error: leaked operands");
5617 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5628 if (parser->tok == ',') {
5629 if (!parser_next(parser)) {
5630 parseerror(parser, "expected another variable");
5634 if (parser->tok != TOKEN_IDENT) {
5635 parseerror(parser, "expected another variable");
5638 var = ast_value_copy(basetype);
5640 ast_value_set_name(var, parser_tokval(parser));
5641 if (!parser_next(parser)) {
5642 parseerror(parser, "error parsing variable declaration");
5648 if (parser->tok != ';') {
5649 parseerror(parser, "missing semicolon after variables");
5653 if (!parser_next(parser)) {
5654 parseerror(parser, "parse error after variable declaration");
5658 ast_delete(basetype);
5662 if (cleanvar && var)
5664 ast_delete(basetype);
5668 ast_delete(basetype);
5669 if (cleanvar && var)
5671 if (me[0]) ast_member_delete(me[0]);
5672 if (me[1]) ast_member_delete(me[1]);
5673 if (me[2]) ast_member_delete(me[2]);
5677 static bool parser_global_statement(parser_t *parser)
5681 bool is_static = false;
5682 uint32_t qflags = 0;
5683 ast_value *istype = NULL;
5684 char *vstring = NULL;
5686 if (parser->tok == TOKEN_IDENT)
5687 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5689 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5691 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5693 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5695 if (cvq == CV_WRONG)
5697 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5699 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5701 return parse_enum(parser);
5703 else if (parser->tok == TOKEN_KEYWORD)
5705 if (!strcmp(parser_tokval(parser), "typedef")) {
5706 if (!parser_next(parser)) {
5707 parseerror(parser, "expected type definition after 'typedef'");
5710 return parse_typedef(parser);
5712 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5715 else if (parser->tok == '#')
5717 return parse_pragma(parser);
5719 else if (parser->tok == '$')
5721 if (!parser_next(parser)) {
5722 parseerror(parser, "parse error");
5728 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5734 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5736 return util_crc16(old, str, strlen(str));
5739 static void progdefs_crc_file(const char *str)
5741 /* write to progdefs.h here */
5745 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5747 old = progdefs_crc_sum(old, str);
5748 progdefs_crc_file(str);
5752 static void generate_checksum(parser_t *parser, ir_builder *ir)
5754 uint16_t crc = 0xFFFF;
5758 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5759 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5761 progdefs_crc_file("\tint\tpad;\n");
5762 progdefs_crc_file("\tint\tofs_return[3];\n");
5763 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5764 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5765 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5766 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5767 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5768 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5769 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5770 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5772 for (i = 0; i < parser->crc_globals; ++i) {
5773 if (!ast_istype(parser->globals[i], ast_value))
5775 value = (ast_value*)(parser->globals[i]);
5776 switch (value->expression.vtype) {
5777 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5778 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5779 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5780 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5782 crc = progdefs_crc_both(crc, "\tint\t");
5785 crc = progdefs_crc_both(crc, value->name);
5786 crc = progdefs_crc_both(crc, ";\n");
5788 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5789 for (i = 0; i < parser->crc_fields; ++i) {
5790 if (!ast_istype(parser->fields[i], ast_value))
5792 value = (ast_value*)(parser->fields[i]);
5793 switch (value->expression.next->vtype) {
5794 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5795 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5796 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5797 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5799 crc = progdefs_crc_both(crc, "\tint\t");
5802 crc = progdefs_crc_both(crc, value->name);
5803 crc = progdefs_crc_both(crc, ";\n");
5805 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5806 ir->code->crc = crc;
5809 parser_t *parser_create()
5812 lex_ctx_t empty_ctx;
5815 parser = (parser_t*)mem_a(sizeof(parser_t));
5819 memset(parser, 0, sizeof(*parser));
5821 for (i = 0; i < operator_count; ++i) {
5822 if (operators[i].id == opid1('=')) {
5823 parser->assign_op = operators+i;
5827 if (!parser->assign_op) {
5828 printf("internal error: initializing parser: failed to find assign operator\n");
5833 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5834 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5835 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5836 vec_push(parser->_blocktypedefs, 0);
5838 parser->aliases = util_htnew(PARSER_HT_SIZE);
5841 vec_push(parser->correct_variables, correct_trie_new());
5842 vec_push(parser->correct_variables_score, NULL);
5844 empty_ctx.file = "<internal>";
5846 empty_ctx.column = 0;
5847 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5848 parser->nil->cvq = CV_CONST;
5849 if (OPTS_FLAG(UNTYPED_NIL))
5850 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5852 parser->max_param_count = 1;
5854 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5855 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5856 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5858 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5859 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5860 parser->reserved_version->cvq = CV_CONST;
5861 parser->reserved_version->hasvalue = true;
5862 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5863 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5865 parser->reserved_version = NULL;
5868 parser->fold = fold_init (parser);
5869 parser->intrin = intrin_init(parser);
5873 static bool parser_compile(parser_t *parser)
5875 /* initial lexer/parser state */
5876 parser->lex->flags.noops = true;
5878 if (parser_next(parser))
5880 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5882 if (!parser_global_statement(parser)) {
5883 if (parser->tok == TOKEN_EOF)
5884 parseerror(parser, "unexpected end of file");
5885 else if (compile_errors)
5886 parseerror(parser, "there have been errors, bailing out");
5887 lex_close(parser->lex);
5893 parseerror(parser, "parse error");
5894 lex_close(parser->lex);
5899 lex_close(parser->lex);
5902 return !compile_errors;
5905 bool parser_compile_file(parser_t *parser, const char *filename)
5907 parser->lex = lex_open(filename);
5909 con_err("failed to open file \"%s\"\n", filename);
5912 return parser_compile(parser);
5915 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5917 parser->lex = lex_open_string(str, len, name);
5919 con_err("failed to create lexer for string \"%s\"\n", name);
5922 return parser_compile(parser);
5925 static void parser_remove_ast(parser_t *parser)
5928 if (parser->ast_cleaned)
5930 parser->ast_cleaned = true;
5931 for (i = 0; i < vec_size(parser->accessors); ++i) {
5932 ast_delete(parser->accessors[i]->constval.vfunc);
5933 parser->accessors[i]->constval.vfunc = NULL;
5934 ast_delete(parser->accessors[i]);
5936 for (i = 0; i < vec_size(parser->functions); ++i) {
5937 ast_delete(parser->functions[i]);
5939 for (i = 0; i < vec_size(parser->fields); ++i) {
5940 ast_delete(parser->fields[i]);
5942 for (i = 0; i < vec_size(parser->globals); ++i) {
5943 ast_delete(parser->globals[i]);
5945 vec_free(parser->accessors);
5946 vec_free(parser->functions);
5947 vec_free(parser->globals);
5948 vec_free(parser->fields);
5950 for (i = 0; i < vec_size(parser->variables); ++i)
5951 util_htdel(parser->variables[i]);
5952 vec_free(parser->variables);
5953 vec_free(parser->_blocklocals);
5954 vec_free(parser->_locals);
5957 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5958 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5960 vec_free(parser->correct_variables);
5961 vec_free(parser->correct_variables_score);
5963 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5964 ast_delete(parser->_typedefs[i]);
5965 vec_free(parser->_typedefs);
5966 for (i = 0; i < vec_size(parser->typedefs); ++i)
5967 util_htdel(parser->typedefs[i]);
5968 vec_free(parser->typedefs);
5969 vec_free(parser->_blocktypedefs);
5971 vec_free(parser->_block_ctx);
5973 vec_free(parser->labels);
5974 vec_free(parser->gotos);
5975 vec_free(parser->breaks);
5976 vec_free(parser->continues);
5978 ast_value_delete(parser->nil);
5980 ast_value_delete(parser->const_vec[0]);
5981 ast_value_delete(parser->const_vec[1]);
5982 ast_value_delete(parser->const_vec[2]);
5984 if (parser->reserved_version)
5985 ast_value_delete(parser->reserved_version);
5987 util_htdel(parser->aliases);
5988 fold_cleanup(parser->fold);
5989 intrin_cleanup(parser->intrin);
5992 void parser_cleanup(parser_t *parser)
5994 parser_remove_ast(parser);
5998 bool parser_finish(parser_t *parser, const char *output)
6004 if (compile_errors) {
6005 con_out("*** there were compile errors\n");
6009 ir = ir_builder_new("gmqcc_out");
6011 con_out("failed to allocate builder\n");
6015 for (i = 0; i < vec_size(parser->fields); ++i) {
6018 if (!ast_istype(parser->fields[i], ast_value))
6020 field = (ast_value*)parser->fields[i];
6021 hasvalue = field->hasvalue;
6022 field->hasvalue = false;
6023 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6024 con_out("failed to generate field %s\n", field->name);
6025 ir_builder_delete(ir);
6030 ast_expression *subtype;
6031 field->hasvalue = true;
6032 subtype = field->expression.next;
6033 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6034 if (subtype->vtype == TYPE_FIELD)
6035 ifld->fieldtype = subtype->next->vtype;
6036 else if (subtype->vtype == TYPE_FUNCTION)
6037 ifld->outtype = subtype->next->vtype;
6038 (void)!ir_value_set_field(field->ir_v, ifld);
6041 for (i = 0; i < vec_size(parser->globals); ++i) {
6043 if (!ast_istype(parser->globals[i], ast_value))
6045 asvalue = (ast_value*)(parser->globals[i]);
6046 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6047 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6048 "unused global: `%s`", asvalue->name);
6050 if (!ast_global_codegen(asvalue, ir, false)) {
6051 con_out("failed to generate global %s\n", asvalue->name);
6052 ir_builder_delete(ir);
6056 /* Build function vararg accessor ast tree now before generating
6057 * immediates, because the accessors may add new immediates
6059 for (i = 0; i < vec_size(parser->functions); ++i) {
6060 ast_function *f = parser->functions[i];
6062 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6063 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6064 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6065 con_out("failed to generate vararg setter for %s\n", f->name);
6066 ir_builder_delete(ir);
6069 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6070 con_out("failed to generate vararg getter for %s\n", f->name);
6071 ir_builder_delete(ir);
6075 ast_delete(f->varargs);
6080 /* Now we can generate immediates */
6081 if (!fold_generate(parser->fold, ir))
6084 for (i = 0; i < vec_size(parser->globals); ++i) {
6086 if (!ast_istype(parser->globals[i], ast_value))
6088 asvalue = (ast_value*)(parser->globals[i]);
6089 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6091 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6092 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6093 "uninitialized constant: `%s`",
6095 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6096 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6097 "uninitialized global: `%s`",
6100 if (!ast_generate_accessors(asvalue, ir)) {
6101 ir_builder_delete(ir);
6105 for (i = 0; i < vec_size(parser->fields); ++i) {
6107 asvalue = (ast_value*)(parser->fields[i]->next);
6109 if (!ast_istype((ast_expression*)asvalue, ast_value))
6111 if (asvalue->expression.vtype != TYPE_ARRAY)
6113 if (!ast_generate_accessors(asvalue, ir)) {
6114 ir_builder_delete(ir);
6118 if (parser->reserved_version &&
6119 !ast_global_codegen(parser->reserved_version, ir, false))
6121 con_out("failed to generate reserved::version");
6122 ir_builder_delete(ir);
6125 for (i = 0; i < vec_size(parser->functions); ++i) {
6126 ast_function *f = parser->functions[i];
6127 if (!ast_function_codegen(f, ir)) {
6128 con_out("failed to generate function %s\n", f->name);
6129 ir_builder_delete(ir);
6134 generate_checksum(parser, ir);
6136 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6137 ir_builder_dump(ir, con_out);
6138 for (i = 0; i < vec_size(parser->functions); ++i) {
6139 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6140 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6141 ir_builder_delete(ir);
6145 parser_remove_ast(parser);
6147 if (compile_Werrors) {
6148 con_out("*** there were warnings treated as errors\n");
6149 compile_show_werrors();
6154 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6155 ir_builder_dump(ir, con_out);
6157 if (!ir_builder_generate(ir, output)) {
6158 con_out("*** failed to generate output file\n");
6159 ir_builder_delete(ir);
6163 ir_builder_delete(ir);