2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 #define PARSER_HT_LOCALS 2
29 #define PARSER_HT_SIZE 512
30 #define TYPEDEF_HT_SIZE 512
32 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
34 static void parser_enterblock(parser_t *parser);
35 static bool parser_leaveblock(parser_t *parser);
36 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
37 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
38 static bool parse_typedef(parser_t *parser);
39 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool is_static, uint32_t qflags, char *vstring);
40 static ast_block* parse_block(parser_t *parser);
41 static bool parse_block_into(parser_t *parser, ast_block *block);
42 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
43 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
44 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
45 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
46 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
47 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
48 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
50 static void parseerror(parser_t *parser, const char *fmt, ...)
54 vcompile_error(parser->lex->tok.ctx, fmt, ap);
58 /* returns true if it counts as an error */
59 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
64 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
69 /**********************************************************************
73 static bool parser_next(parser_t *parser)
75 /* lex_do kills the previous token */
76 parser->tok = lex_do(parser->lex);
77 if (parser->tok == TOKEN_EOF)
79 if (parser->tok >= TOKEN_ERROR) {
80 parseerror(parser, "lex error");
86 #define parser_tokval(p) ((p)->lex->tok.value)
87 #define parser_token(p) (&((p)->lex->tok))
89 char *parser_strdup(const char *str)
92 /* actually dup empty strings */
93 char *out = (char*)mem_a(1);
97 return util_strdup(str);
100 static ast_expression* parser_find_field(parser_t *parser, const char *name)
102 return ( ast_expression*)util_htget(parser->htfields, name);
105 static ast_expression* parser_find_label(parser_t *parser, const char *name)
108 for(i = 0; i < vec_size(parser->labels); i++)
109 if (!strcmp(parser->labels[i]->name, name))
110 return (ast_expression*)parser->labels[i];
114 static ast_expression* parser_find_global(parser_t *parser, const char *name)
116 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
119 return (ast_expression*)util_htget(parser->htglobals, name);
122 static ast_expression* parser_find_param(parser_t *parser, const char *name)
126 if (!parser->function)
128 fun = parser->function->vtype;
129 for (i = 0; i < vec_size(fun->expression.params); ++i) {
130 if (!strcmp(fun->expression.params[i]->name, name))
131 return (ast_expression*)(fun->expression.params[i]);
136 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
141 hash = util_hthash(parser->htglobals, name);
144 for (i = vec_size(parser->variables); i > upto;) {
146 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
150 return parser_find_param(parser, name);
153 static ast_expression* parser_find_var(parser_t *parser, const char *name)
157 v = parser_find_local(parser, name, 0, &dummy);
158 if (!v) v = parser_find_global(parser, name);
162 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
166 hash = util_hthash(parser->typedefs[0], name);
168 for (i = vec_size(parser->typedefs); i > upto;) {
170 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
176 /* include intrinsics */
181 size_t etype; /* 0 = expression, others are operators */
185 ast_block *block; /* for commas and function calls */
204 static sy_elem syexp(lex_ctx_t ctx, ast_expression *v) {
215 static sy_elem syblock(lex_ctx_t ctx, ast_block *v) {
219 e.out = (ast_expression*)v;
226 static sy_elem syop(lex_ctx_t ctx, const oper_info *op) {
228 e.etype = 1 + (op - operators);
237 static sy_elem syparen(lex_ctx_t ctx, size_t off) {
248 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
249 * so we need to rotate it to become ent.(foo[n]).
251 static bool rotate_entfield_array_index_nodes(ast_expression **out)
253 ast_array_index *index, *oldindex;
254 ast_entfield *entfield;
258 ast_expression *entity;
260 lex_ctx_t ctx = ast_ctx(*out);
262 if (!ast_istype(*out, ast_array_index))
264 index = (ast_array_index*)*out;
266 if (!ast_istype(index->array, ast_entfield))
268 entfield = (ast_entfield*)index->array;
270 if (!ast_istype(entfield->field, ast_value))
272 field = (ast_value*)entfield->field;
275 entity = entfield->entity;
279 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
280 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
281 *out = (ast_expression*)entfield;
283 oldindex->array = NULL;
284 oldindex->index = NULL;
285 ast_delete(oldindex);
290 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
294 ast_expression *out = NULL;
295 ast_expression *exprs[3];
296 ast_block *blocks[3];
297 ast_value *asvalue[3];
298 ast_binstore *asbinstore;
299 size_t i, assignop, addop, subop;
300 qcint_t generated_op = 0;
305 if (!vec_size(sy->ops)) {
306 parseerror(parser, "internal error: missing operator");
310 if (vec_last(sy->ops).isparen) {
311 parseerror(parser, "unmatched parenthesis");
315 op = &operators[vec_last(sy->ops).etype - 1];
316 ctx = vec_last(sy->ops).ctx;
318 if (vec_size(sy->out) < op->operands) {
319 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
320 op->op, (int)op->id);
324 vec_shrinkby(sy->ops, 1);
326 /* op(:?) has no input and no output */
330 vec_shrinkby(sy->out, op->operands);
331 for (i = 0; i < op->operands; ++i) {
332 exprs[i] = sy->out[vec_size(sy->out)+i].out;
333 blocks[i] = sy->out[vec_size(sy->out)+i].block;
334 asvalue[i] = (ast_value*)exprs[i];
336 if (exprs[i]->vtype == TYPE_NOEXPR &&
337 !(i != 0 && op->id == opid2('?',':')) &&
338 !(i == 1 && op->id == opid1('.')))
340 if (ast_istype(exprs[i], ast_label))
341 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
343 compile_error(ast_ctx(exprs[i]), "not an expression");
344 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
348 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
349 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
353 #define NotSameType(T) \
354 (exprs[0]->vtype != exprs[1]->vtype || \
355 exprs[0]->vtype != T)
357 /* preform any constant folding on operator usage first */
358 /*if ((out = fold_op(parser->fold, op, exprs)))*/
364 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
368 if (exprs[0]->vtype == TYPE_VECTOR &&
369 exprs[1]->vtype == TYPE_NOEXPR)
371 if (exprs[1] == (ast_expression*)parser->const_vec[0])
372 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
373 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
374 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
375 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
376 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
378 compile_error(ctx, "access to invalid vector component");
382 else if (exprs[0]->vtype == TYPE_ENTITY) {
383 if (exprs[1]->vtype != TYPE_FIELD) {
384 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
387 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
389 else if (exprs[0]->vtype == TYPE_VECTOR) {
390 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
394 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
400 if (exprs[0]->vtype != TYPE_ARRAY &&
401 !(exprs[0]->vtype == TYPE_FIELD &&
402 exprs[0]->next->vtype == TYPE_ARRAY))
404 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
405 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
408 if (exprs[1]->vtype != TYPE_FLOAT) {
409 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
410 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
413 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
414 if (rotate_entfield_array_index_nodes(&out))
417 /* This is not broken in fteqcc anymore */
418 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
419 /* this error doesn't need to make us bail out */
420 (void)!parsewarning(parser, WARN_EXTENSIONS,
421 "accessing array-field members of an entity without parenthesis\n"
422 " -> this is an extension from -std=gmqcc");
429 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
430 vec_push(sy->out, syexp(ctx, exprs[0]));
431 vec_push(sy->out, syexp(ctx, exprs[1]));
432 vec_last(sy->argc)++;
436 if (!ast_block_add_expr(blocks[0], exprs[1]))
439 blocks[0] = ast_block_new(ctx);
440 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
441 !ast_block_add_expr(blocks[0], exprs[1]))
446 ast_block_set_type(blocks[0], exprs[1]);
448 vec_push(sy->out, syblock(ctx, blocks[0]));
455 if (!(out = fold_op(parser->fold, op, exprs))) {
456 switch (exprs[0]->vtype) {
458 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
459 (ast_expression*)parser->fold->imm_float[0],
463 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
464 (ast_expression*)parser->fold->imm_vector[0],
468 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
469 type_name[exprs[0]->vtype]);
476 if (!(out = fold_op(parser->fold, op, exprs))) {
477 switch (exprs[0]->vtype) {
479 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
482 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
485 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
486 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
488 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
490 /* we don't constant-fold NOT for these types */
492 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
495 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
498 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
499 type_name[exprs[0]->vtype]);
506 if (exprs[0]->vtype != exprs[1]->vtype ||
507 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
509 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
510 type_name[exprs[0]->vtype],
511 type_name[exprs[1]->vtype]);
514 if (!(out = fold_op(parser->fold, op, exprs))) {
515 switch (exprs[0]->vtype) {
517 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
520 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
523 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
524 type_name[exprs[0]->vtype],
525 type_name[exprs[1]->vtype]);
531 if (exprs[0]->vtype != exprs[1]->vtype ||
532 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT))
534 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
535 type_name[exprs[1]->vtype],
536 type_name[exprs[0]->vtype]);
539 if (!(out = fold_op(parser->fold, op, exprs))) {
540 switch (exprs[0]->vtype) {
542 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
545 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
548 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
549 type_name[exprs[1]->vtype],
550 type_name[exprs[0]->vtype]);
556 if (exprs[0]->vtype != exprs[1]->vtype &&
557 !(exprs[0]->vtype == TYPE_VECTOR &&
558 exprs[1]->vtype == TYPE_FLOAT) &&
559 !(exprs[1]->vtype == TYPE_VECTOR &&
560 exprs[0]->vtype == TYPE_FLOAT)
563 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
564 type_name[exprs[1]->vtype],
565 type_name[exprs[0]->vtype]);
568 if (!(out = fold_op(parser->fold, op, exprs))) {
569 switch (exprs[0]->vtype) {
571 if (exprs[1]->vtype == TYPE_VECTOR)
572 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
574 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
577 if (exprs[1]->vtype == TYPE_FLOAT)
578 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
580 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
583 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
584 type_name[exprs[1]->vtype],
585 type_name[exprs[0]->vtype]);
591 if (exprs[1]->vtype != TYPE_FLOAT) {
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);
597 if (!(out = fold_op(parser->fold, op, exprs))) {
598 if (exprs[0]->vtype == TYPE_FLOAT)
599 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
600 else if (exprs[0]->vtype == TYPE_VECTOR) {
601 out = (ast_expression*)ast_binary_new (
605 (ast_expression*)ast_binary_new(
608 (ast_expression*)parser->fold->imm_float[1],
613 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
614 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
615 compile_error(ctx, "invalid types used in expression: cannot divide types %s and %s", ty1, ty2);
622 if (NotSameType(TYPE_FLOAT)) {
623 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
624 type_name[exprs[0]->vtype],
625 type_name[exprs[1]->vtype]);
627 } else if (!(out = fold_op(parser->fold, op, exprs))) {
628 /* generate a call to __builtin_mod */
629 ast_expression *mod = intrin_func(parser, "mod");
630 ast_call *call = NULL;
631 if (!mod) return false; /* can return null for missing floor */
633 call = ast_call_new(parser_ctx(parser), mod);
634 vec_push(call->params, exprs[0]);
635 vec_push(call->params, exprs[1]);
637 out = (ast_expression*)call;
642 compile_error(ctx, "%= is unimplemented");
647 if (NotSameType(TYPE_FLOAT)) {
648 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
649 type_name[exprs[0]->vtype],
650 type_name[exprs[1]->vtype]);
653 if (!(out = fold_op(parser->fold, op, exprs)))
654 out = (ast_expression*)ast_binary_new(ctx,
655 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
660 * Okay lets designate what the hell is an acceptable use
661 * of the ^ operator. In many vector processing units, XOR
662 * is allowed to be used on vectors, but only if the first
663 * operand is a vector, the second operand can be a float
664 * or vector. It's never legal for the first operand to be
665 * a float, and then the following operand to be a vector.
666 * Further more, the only time it is legal to do XOR otherwise
667 * is when both operand are floats. This nicely crafted if
668 * statement catches them all.
670 * In the event that the first operand is a vector, two
671 * possible situations can arise, thus, each element of
672 * vector A (operand A) is exclusive-ORed with the corresponding
673 * element of vector B (operand B), If B is scalar, the
674 * scalar value is first replicated for each element.
676 * The QCVM itself lacks a BITXOR instruction. Thus emulating
677 * the mathematics of it is required. The following equation
678 * is used: (LHS | RHS) & ~(LHS & RHS). However, due to the
679 * QCVM also lacking a BITNEG instruction, we need to emulate
680 * ~FOO with -1 - FOO, the whole process becoming this nicely
681 * crafted expression: (LHS | RHS) & (-1 - (LHS & RHS)).
683 * When A is not scalar, this process is repeated for all
684 * components of vector A with the value in operand B,
685 * only if operand B is scalar. When A is not scalar, and B
686 * is also not scalar, this process is repeated for all
687 * components of the vector A with the components of vector B.
688 * Finally when A is scalar and B is scalar, this process is
689 * simply used once for A and B being LHS and RHS respectfully.
691 * Yes the semantics are a bit strange (no pun intended).
692 * But then again BITXOR is strange itself, consdering it's
693 * commutative, assocative, and elements of the BITXOR operation
694 * are their own inverse.
696 if ( !(exprs[0]->vtype == TYPE_FLOAT && exprs[1]->vtype == TYPE_FLOAT) &&
697 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_FLOAT) &&
698 !(exprs[0]->vtype == TYPE_VECTOR && exprs[1]->vtype == TYPE_VECTOR))
700 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
701 type_name[exprs[0]->vtype],
702 type_name[exprs[1]->vtype]);
706 if (!(out = fold_op(parser->fold, op, exprs))) {
708 * IF the first expression is float, the following will be too
709 * since scalar ^ vector is not allowed.
711 if (exprs[0]->vtype == TYPE_FLOAT) {
712 ast_binary *expr = ast_binary_new(
715 (ast_expression*)parser->fold->imm_float[2],
716 (ast_expression*)ast_binary_new(
723 expr->refs = AST_REF_NONE;
725 out = (ast_expression*)
729 (ast_expression*)ast_binary_new(
735 (ast_expression*)expr
739 * The first is a vector: vector is allowed to xor with vector and
740 * with scalar, branch here for the second operand.
742 if (exprs[1]->vtype == TYPE_VECTOR) {
744 * Xor all the values of the vector components against the
745 * vectors components in question.
747 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against vector");
750 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor for vector against float");
759 case opid3('<','<','='):
760 case opid3('>','>','='):
761 if(!(out = fold_op(parser->fold, op, exprs))) {
762 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
767 generated_op += 1; /* INSTR_OR */
769 generated_op += INSTR_AND;
770 if (!(out = fold_op(parser->fold, op, exprs))) {
771 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
772 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
773 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
774 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
777 for (i = 0; i < 2; ++i) {
778 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
779 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
781 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
783 exprs[i] = out; out = NULL;
784 if (OPTS_FLAG(PERL_LOGIC)) {
785 /* here we want to keep the right expressions' type */
789 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
790 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
792 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
794 exprs[i] = out; out = NULL;
795 if (OPTS_FLAG(PERL_LOGIC)) {
796 /* here we want to keep the right expressions' type */
801 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
806 if (vec_last(sy->paren) != PAREN_TERNARY2) {
807 compile_error(ctx, "mismatched parenthesis/ternary");
811 if (!ast_compare_type(exprs[1], exprs[2])) {
812 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
813 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
814 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
817 if (!(out = fold_op(parser->fold, op, exprs)))
818 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
821 case opid2('*', '*'):
822 if (NotSameType(TYPE_FLOAT)) {
823 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
824 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
825 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
830 if (!(out = fold_op(parser->fold, op, exprs))) {
831 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
832 vec_push(gencall->params, exprs[0]);
833 vec_push(gencall->params, exprs[1]);
834 out = (ast_expression*)gencall;
838 case opid3('<','=','>'): /* -1, 0, or 1 */
839 if (NotSameType(TYPE_FLOAT)) {
840 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
841 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
842 compile_error(ctx, "invalid types used in comparision: %s and %s",
848 if (!(out = fold_op(parser->fold, op, exprs))) {
849 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
851 eq->refs = AST_REF_NONE;
854 out = (ast_expression*)ast_ternary_new(ctx,
855 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
857 (ast_expression*)parser->fold->imm_float[2],
860 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
862 (ast_expression*)parser->fold->imm_float[0],
865 (ast_expression*)parser->fold->imm_float[1]
875 generated_op += 1; /* INSTR_GT */
877 generated_op += 1; /* INSTR_LT */
878 case opid2('>', '='):
879 generated_op += 1; /* INSTR_GE */
880 case opid2('<', '='):
881 generated_op += INSTR_LE;
882 if (NotSameType(TYPE_FLOAT)) {
883 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
884 type_name[exprs[0]->vtype],
885 type_name[exprs[1]->vtype]);
888 if (!(out = fold_op(parser->fold, op, exprs)))
889 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
891 case opid2('!', '='):
892 if (exprs[0]->vtype != exprs[1]->vtype) {
893 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
894 type_name[exprs[0]->vtype],
895 type_name[exprs[1]->vtype]);
898 if (!(out = fold_op(parser->fold, op, exprs)))
899 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
901 case opid2('=', '='):
902 if (exprs[0]->vtype != exprs[1]->vtype) {
903 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
904 type_name[exprs[0]->vtype],
905 type_name[exprs[1]->vtype]);
908 if (!(out = fold_op(parser->fold, op, exprs)))
909 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
913 if (ast_istype(exprs[0], ast_entfield)) {
914 ast_expression *field = ((ast_entfield*)exprs[0])->field;
915 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
916 exprs[0]->vtype == TYPE_FIELD &&
917 exprs[0]->next->vtype == TYPE_VECTOR)
919 assignop = type_storep_instr[TYPE_VECTOR];
922 assignop = type_storep_instr[exprs[0]->vtype];
923 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
925 ast_type_to_string(field->next, ty1, sizeof(ty1));
926 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
927 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
928 field->next->vtype == TYPE_FUNCTION &&
929 exprs[1]->vtype == TYPE_FUNCTION)
931 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
932 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
935 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
940 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
941 exprs[0]->vtype == TYPE_FIELD &&
942 exprs[0]->next->vtype == TYPE_VECTOR)
944 assignop = type_store_instr[TYPE_VECTOR];
947 assignop = type_store_instr[exprs[0]->vtype];
950 if (assignop == VINSTR_END) {
951 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
952 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
953 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
955 else if (!ast_compare_type(exprs[0], exprs[1]))
957 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
958 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
959 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
960 exprs[0]->vtype == TYPE_FUNCTION &&
961 exprs[1]->vtype == TYPE_FUNCTION)
963 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
964 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
967 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
970 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
971 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
973 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
975 case opid3('+','+','P'):
976 case opid3('-','-','P'):
978 if (exprs[0]->vtype != TYPE_FLOAT) {
979 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
980 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
983 if (op->id == opid3('+','+','P'))
987 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
988 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
990 if (ast_istype(exprs[0], ast_entfield)) {
991 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
993 (ast_expression*)parser->fold->imm_float[1]);
995 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
997 (ast_expression*)parser->fold->imm_float[1]);
1000 case opid3('S','+','+'):
1001 case opid3('S','-','-'):
1003 if (exprs[0]->vtype != TYPE_FLOAT) {
1004 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1005 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1008 if (op->id == opid3('S','+','+')) {
1009 addop = INSTR_ADD_F;
1010 subop = INSTR_SUB_F;
1012 addop = INSTR_SUB_F;
1013 subop = INSTR_ADD_F;
1015 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1016 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1018 if (ast_istype(exprs[0], ast_entfield)) {
1019 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1021 (ast_expression*)parser->fold->imm_float[1]);
1023 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1025 (ast_expression*)parser->fold->imm_float[1]);
1029 out = (ast_expression*)ast_binary_new(ctx, subop,
1031 (ast_expression*)parser->fold->imm_float[1]);
1033 case opid2('+','='):
1034 case opid2('-','='):
1035 if (exprs[0]->vtype != exprs[1]->vtype ||
1036 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1038 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1039 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1040 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1044 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1045 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1047 if (ast_istype(exprs[0], ast_entfield))
1048 assignop = type_storep_instr[exprs[0]->vtype];
1050 assignop = type_store_instr[exprs[0]->vtype];
1051 switch (exprs[0]->vtype) {
1053 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1054 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1055 exprs[0], exprs[1]);
1058 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1059 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1060 exprs[0], exprs[1]);
1063 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1064 type_name[exprs[0]->vtype],
1065 type_name[exprs[1]->vtype]);
1069 case opid2('*','='):
1070 case opid2('/','='):
1071 if (exprs[1]->vtype != TYPE_FLOAT ||
1072 !(exprs[0]->vtype == TYPE_FLOAT ||
1073 exprs[0]->vtype == TYPE_VECTOR))
1075 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1076 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1077 compile_error(ctx, "invalid types used in expression: %s and %s",
1081 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1082 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1084 if (ast_istype(exprs[0], ast_entfield))
1085 assignop = type_storep_instr[exprs[0]->vtype];
1087 assignop = type_store_instr[exprs[0]->vtype];
1088 switch (exprs[0]->vtype) {
1090 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1091 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1092 exprs[0], exprs[1]);
1095 if (op->id == opid2('*','=')) {
1096 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1097 exprs[0], exprs[1]);
1099 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1100 (ast_expression*)parser->fold->imm_float[1],
1103 compile_error(ctx, "internal error: failed to generate division");
1106 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1111 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1112 type_name[exprs[0]->vtype],
1113 type_name[exprs[1]->vtype]);
1117 case opid2('&','='):
1118 case opid2('|','='):
1119 if (NotSameType(TYPE_FLOAT)) {
1120 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1121 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1122 compile_error(ctx, "invalid types used in expression: %s and %s",
1126 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1127 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1129 if (ast_istype(exprs[0], ast_entfield))
1130 assignop = type_storep_instr[exprs[0]->vtype];
1132 assignop = type_store_instr[exprs[0]->vtype];
1133 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1134 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1135 exprs[0], exprs[1]);
1137 case opid3('&','~','='):
1138 /* This is like: a &= ~(b);
1139 * But QC has no bitwise-not, so we implement it as
1142 if (NotSameType(TYPE_FLOAT)) {
1143 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1144 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1145 compile_error(ctx, "invalid types used in expression: %s and %s",
1149 if (ast_istype(exprs[0], ast_entfield))
1150 assignop = type_storep_instr[exprs[0]->vtype];
1152 assignop = type_store_instr[exprs[0]->vtype];
1153 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1156 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1157 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1159 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1160 asbinstore->keep_dest = true;
1161 out = (ast_expression*)asbinstore;
1164 case opid2('~', 'P'):
1165 if (exprs[0]->vtype != TYPE_FLOAT) {
1166 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1167 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1170 if (!(out = fold_op(parser->fold, op, exprs)))
1171 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser->fold->imm_float[2], exprs[0]);
1177 compile_error(ctx, "failed to apply operator %s", op->op);
1181 vec_push(sy->out, syexp(ctx, out));
1185 static bool parser_close_call(parser_t *parser, shunt *sy)
1187 /* was a function call */
1188 ast_expression *fun;
1189 ast_value *funval = NULL;
1193 size_t paramcount, i;
1195 fid = vec_last(sy->ops).off;
1196 vec_shrinkby(sy->ops, 1);
1198 /* out[fid] is the function
1199 * everything above is parameters...
1201 if (!vec_size(sy->argc)) {
1202 parseerror(parser, "internal error: no argument counter available");
1206 paramcount = vec_last(sy->argc);
1209 if (vec_size(sy->out) < fid) {
1210 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1211 (unsigned long)vec_size(sy->out),
1213 (unsigned long)paramcount);
1217 fun = sy->out[fid].out;
1219 if (fun == intrinsic_debug_typestring) {
1221 if (fid+2 != vec_size(sy->out) ||
1222 vec_last(sy->out).block)
1224 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1227 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1228 ast_unref(vec_last(sy->out).out);
1229 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1230 (ast_expression*)fold_constgen_string(parser->fold, ty, false));
1231 vec_shrinkby(sy->out, 1);
1235 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1239 if (fid+1 < vec_size(sy->out))
1242 if (fid+1 + paramcount != vec_size(sy->out)) {
1243 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1244 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1248 for (i = 0; i < paramcount; ++i)
1249 vec_push(call->params, sy->out[fid+1 + i].out);
1250 vec_shrinkby(sy->out, paramcount);
1251 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1252 if (parser->max_param_count < paramcount)
1253 parser->max_param_count = paramcount;
1255 if (ast_istype(fun, ast_value)) {
1256 funval = (ast_value*)fun;
1257 if ((fun->flags & AST_FLAG_VARIADIC) &&
1258 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1260 call->va_count = (ast_expression*)fold_constgen_float(parser->fold, (qcfloat_t)paramcount);
1264 /* overwrite fid, the function, with a call */
1265 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1267 if (fun->vtype != TYPE_FUNCTION) {
1268 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1273 parseerror(parser, "could not determine function return type");
1276 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1278 if (fun->flags & AST_FLAG_DEPRECATED) {
1280 return !parsewarning(parser, WARN_DEPRECATED,
1281 "call to function (which is marked deprecated)\n",
1282 "-> it has been declared here: %s:%i",
1283 ast_ctx(fun).file, ast_ctx(fun).line);
1286 return !parsewarning(parser, WARN_DEPRECATED,
1287 "call to `%s` (which is marked deprecated)\n"
1288 "-> `%s` declared here: %s:%i",
1289 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1291 return !parsewarning(parser, WARN_DEPRECATED,
1292 "call to `%s` (deprecated: %s)\n"
1293 "-> `%s` declared here: %s:%i",
1294 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1298 if (vec_size(fun->params) != paramcount &&
1299 !((fun->flags & AST_FLAG_VARIADIC) &&
1300 vec_size(fun->params) < paramcount))
1302 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1304 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1305 "too %s parameters for call to %s: expected %i, got %i\n"
1306 " -> `%s` has been declared here: %s:%i",
1307 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1308 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1310 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1311 "too %s parameters for function call: expected %i, got %i\n"
1312 " -> it has been declared here: %s:%i",
1313 fewmany, (int)vec_size(fun->params), (int)paramcount,
1314 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1321 static bool parser_close_paren(parser_t *parser, shunt *sy)
1323 if (!vec_size(sy->ops)) {
1324 parseerror(parser, "unmatched closing paren");
1328 while (vec_size(sy->ops)) {
1329 if (vec_last(sy->ops).isparen) {
1330 if (vec_last(sy->paren) == PAREN_FUNC) {
1332 if (!parser_close_call(parser, sy))
1336 if (vec_last(sy->paren) == PAREN_EXPR) {
1338 if (!vec_size(sy->out)) {
1339 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1340 vec_shrinkby(sy->ops, 1);
1343 vec_shrinkby(sy->ops, 1);
1346 if (vec_last(sy->paren) == PAREN_INDEX) {
1348 /* pop off the parenthesis */
1349 vec_shrinkby(sy->ops, 1);
1350 /* then apply the index operator */
1351 if (!parser_sy_apply_operator(parser, sy))
1355 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1356 vec_last(sy->paren) = PAREN_TERNARY2;
1357 /* pop off the parenthesis */
1358 vec_shrinkby(sy->ops, 1);
1361 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1364 if (!parser_sy_apply_operator(parser, sy))
1370 static void parser_reclassify_token(parser_t *parser)
1373 if (parser->tok >= TOKEN_START)
1375 for (i = 0; i < operator_count; ++i) {
1376 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1377 parser->tok = TOKEN_OPERATOR;
1383 static ast_expression* parse_vararg_do(parser_t *parser)
1385 ast_expression *idx, *out;
1387 ast_value *funtype = parser->function->vtype;
1388 lex_ctx_t ctx = parser_ctx(parser);
1390 if (!parser->function->varargs) {
1391 parseerror(parser, "function has no variable argument list");
1395 if (!parser_next(parser) || parser->tok != '(') {
1396 parseerror(parser, "expected parameter index and type in parenthesis");
1399 if (!parser_next(parser)) {
1400 parseerror(parser, "error parsing parameter index");
1404 idx = parse_expression_leave(parser, true, false, false);
1408 if (parser->tok != ',') {
1409 if (parser->tok != ')') {
1411 parseerror(parser, "expected comma after parameter index");
1414 /* vararg piping: ...(start) */
1415 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1419 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1421 parseerror(parser, "expected typename for vararg");
1425 typevar = parse_typename(parser, NULL, NULL);
1431 if (parser->tok != ')') {
1433 ast_delete(typevar);
1434 parseerror(parser, "expected closing paren");
1438 if (funtype->expression.varparam &&
1439 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1443 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1444 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1445 compile_error(ast_ctx(typevar),
1446 "function was declared to take varargs of type `%s`, requested type is: %s",
1450 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1451 ast_type_adopt(out, typevar);
1452 ast_delete(typevar);
1456 static ast_expression* parse_vararg(parser_t *parser)
1458 bool old_noops = parser->lex->flags.noops;
1460 ast_expression *out;
1462 parser->lex->flags.noops = true;
1463 out = parse_vararg_do(parser);
1465 parser->lex->flags.noops = old_noops;
1469 /* not to be exposed */
1470 extern bool ftepp_predef_exists(const char *name);
1472 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1474 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1475 parser->tok == TOKEN_IDENT &&
1476 !strcmp(parser_tokval(parser), "_"))
1478 /* a translatable string */
1481 parser->lex->flags.noops = true;
1482 if (!parser_next(parser) || parser->tok != '(') {
1483 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1486 parser->lex->flags.noops = false;
1487 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1488 parseerror(parser, "expected a constant string in translatable-string extension");
1491 val = (ast_value*)fold_constgen_string(parser->fold, parser_tokval(parser), true);
1494 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1496 if (!parser_next(parser) || parser->tok != ')') {
1497 parseerror(parser, "expected closing paren after translatable string");
1502 else if (parser->tok == TOKEN_DOTS)
1505 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1506 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1509 va = parse_vararg(parser);
1512 vec_push(sy->out, syexp(parser_ctx(parser), va));
1515 else if (parser->tok == TOKEN_FLOATCONST) {
1516 ast_expression *val = fold_constgen_float(parser->fold, (parser_token(parser)->constval.f));
1519 vec_push(sy->out, syexp(parser_ctx(parser), val));
1522 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1523 ast_expression *val = fold_constgen_float(parser->fold, (qcfloat_t)(parser_token(parser)->constval.i));
1526 vec_push(sy->out, syexp(parser_ctx(parser), val));
1529 else if (parser->tok == TOKEN_STRINGCONST) {
1530 ast_expression *val = fold_constgen_string(parser->fold, parser_tokval(parser), false);
1533 vec_push(sy->out, syexp(parser_ctx(parser), val));
1536 else if (parser->tok == TOKEN_VECTORCONST) {
1537 ast_expression *val = fold_constgen_vector(parser->fold, parser_token(parser)->constval.v);
1540 vec_push(sy->out, syexp(parser_ctx(parser), val));
1543 else if (parser->tok == TOKEN_IDENT)
1545 const char *ctoken = parser_tokval(parser);
1546 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1547 ast_expression *var;
1548 /* a_vector.{x,y,z} */
1549 if (!vec_size(sy->ops) ||
1550 !vec_last(sy->ops).etype ||
1551 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1552 (prev >= intrinsic_debug_typestring &&
1553 prev <= intrinsic_debug_typestring))
1555 /* When adding more intrinsics, fix the above condition */
1558 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1560 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1562 var = parser_find_var(parser, parser_tokval(parser));
1564 var = parser_find_field(parser, parser_tokval(parser));
1566 if (!var && with_labels) {
1567 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1569 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1570 var = (ast_expression*)lbl;
1571 vec_push(parser->labels, lbl);
1574 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1575 var = (ast_expression*)fold_constgen_string(parser->fold, parser->function->name, false);
1578 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1579 var = (ast_expression*)intrinsic_debug_typestring;
1581 /* now we try for the real intrinsic hashtable. If the string
1582 * begins with __builtin, we simply skip past it, otherwise we
1583 * use the identifier as is.
1585 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1586 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1590 char *correct = NULL;
1594 * sometimes people use preprocessing predefs without enabling them
1595 * i've done this thousands of times already myself. Lets check for
1596 * it in the predef table. And diagnose it better :)
1598 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1599 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1604 * TODO: determine the best score for the identifier: be it
1605 * a variable, a field.
1607 * We should also consider adding correction tables for
1608 * other things as well.
1610 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1612 correct_init(&corr);
1614 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1615 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1616 if (strcmp(correct, parser_tokval(parser))) {
1623 correct_free(&corr);
1626 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1631 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
1637 if (ast_istype(var, ast_value)) {
1638 ((ast_value*)var)->uses++;
1640 else if (ast_istype(var, ast_member)) {
1641 ast_member *mem = (ast_member*)var;
1642 if (ast_istype(mem->owner, ast_value))
1643 ((ast_value*)(mem->owner))->uses++;
1646 vec_push(sy->out, syexp(parser_ctx(parser), var));
1649 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1653 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1655 ast_expression *expr = NULL;
1658 bool wantop = false;
1659 /* only warn once about an assignment in a truth value because the current code
1660 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1662 bool warn_truthvalue = true;
1664 /* count the parens because an if starts with one, so the
1665 * end of a condition is an unmatched closing paren
1669 memset(&sy, 0, sizeof(sy));
1671 parser->lex->flags.noops = false;
1673 parser_reclassify_token(parser);
1677 if (parser->tok == TOKEN_TYPENAME) {
1678 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
1682 if (parser->tok == TOKEN_OPERATOR)
1684 /* classify the operator */
1685 const oper_info *op;
1686 const oper_info *olast = NULL;
1688 for (o = 0; o < operator_count; ++o) {
1689 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1690 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1691 !strcmp(parser_tokval(parser), operators[o].op))
1696 if (o == operator_count) {
1697 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
1700 /* found an operator */
1703 /* when declaring variables, a comma starts a new variable */
1704 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1705 /* fixup the token */
1710 /* a colon without a pervious question mark cannot be a ternary */
1711 if (!ternaries && op->id == opid2(':','?')) {
1716 if (op->id == opid1(',')) {
1717 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1718 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1722 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1723 olast = &operators[vec_last(sy.ops).etype-1];
1725 #define IsAssignOp(x) (\
1726 (x) == opid1('=') || \
1727 (x) == opid2('+','=') || \
1728 (x) == opid2('-','=') || \
1729 (x) == opid2('*','=') || \
1730 (x) == opid2('/','=') || \
1731 (x) == opid2('%','=') || \
1732 (x) == opid2('&','=') || \
1733 (x) == opid2('|','=') || \
1734 (x) == opid3('&','~','=') \
1736 if (warn_truthvalue) {
1737 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1738 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1739 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1742 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1743 warn_truthvalue = false;
1748 (op->prec < olast->prec) ||
1749 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1751 if (!parser_sy_apply_operator(parser, &sy))
1753 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1754 olast = &operators[vec_last(sy.ops).etype-1];
1759 if (op->id == opid1('(')) {
1761 size_t sycount = vec_size(sy.out);
1762 /* we expected an operator, this is the function-call operator */
1763 vec_push(sy.paren, PAREN_FUNC);
1764 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1765 vec_push(sy.argc, 0);
1767 vec_push(sy.paren, PAREN_EXPR);
1768 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1771 } else if (op->id == opid1('[')) {
1773 parseerror(parser, "unexpected array subscript");
1776 vec_push(sy.paren, PAREN_INDEX);
1777 /* push both the operator and the paren, this makes life easier */
1778 vec_push(sy.ops, syop(parser_ctx(parser), op));
1779 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1781 } else if (op->id == opid2('?',':')) {
1782 vec_push(sy.ops, syop(parser_ctx(parser), op));
1783 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1786 vec_push(sy.paren, PAREN_TERNARY1);
1787 } else if (op->id == opid2(':','?')) {
1788 if (!vec_size(sy.paren)) {
1789 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1792 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1793 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1796 if (!parser_close_paren(parser, &sy))
1798 vec_push(sy.ops, syop(parser_ctx(parser), op));
1802 vec_push(sy.ops, syop(parser_ctx(parser), op));
1803 wantop = !!(op->flags & OP_SUFFIX);
1806 else if (parser->tok == ')') {
1807 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1808 if (!parser_sy_apply_operator(parser, &sy))
1811 if (!vec_size(sy.paren))
1814 if (vec_last(sy.paren) == PAREN_TERNARY1) {
1815 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
1818 if (!parser_close_paren(parser, &sy))
1821 /* must be a function call without parameters */
1822 if (vec_last(sy.paren) != PAREN_FUNC) {
1823 parseerror(parser, "closing paren in invalid position");
1826 if (!parser_close_paren(parser, &sy))
1831 else if (parser->tok == '(') {
1832 parseerror(parser, "internal error: '(' should be classified as operator");
1835 else if (parser->tok == '[') {
1836 parseerror(parser, "internal error: '[' should be classified as operator");
1839 else if (parser->tok == ']') {
1840 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1841 if (!parser_sy_apply_operator(parser, &sy))
1844 if (!vec_size(sy.paren))
1846 if (vec_last(sy.paren) != PAREN_INDEX) {
1847 parseerror(parser, "mismatched parentheses, unexpected ']'");
1850 if (!parser_close_paren(parser, &sy))
1855 if (!parse_sya_operand(parser, &sy, with_labels))
1858 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
1859 vec_last(sy.argc)++;
1864 /* in this case we might want to allow constant string concatenation */
1865 bool concatenated = false;
1866 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
1867 ast_expression *lexpr = vec_last(sy.out).out;
1868 if (ast_istype(lexpr, ast_value)) {
1869 ast_value *last = (ast_value*)lexpr;
1870 if (last->isimm == true && last->cvq == CV_CONST &&
1871 last->hasvalue && last->expression.vtype == TYPE_STRING)
1873 char *newstr = NULL;
1874 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
1875 vec_last(sy.out).out = (ast_expression*)fold_constgen_string(parser->fold, newstr, false);
1877 concatenated = true;
1881 if (!concatenated) {
1882 parseerror(parser, "expected operator or end of statement");
1887 if (!parser_next(parser)) {
1890 if (parser->tok == ';' ||
1891 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
1892 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
1898 while (vec_size(sy.ops)) {
1899 if (!parser_sy_apply_operator(parser, &sy))
1903 parser->lex->flags.noops = true;
1904 if (vec_size(sy.out) != 1) {
1905 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
1908 expr = sy.out[0].out;
1911 if (vec_size(sy.paren)) {
1912 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
1920 parser->lex->flags.noops = true;
1921 for (i = 0; i < vec_size(sy.out); ++i) {
1923 ast_unref(sy.out[i].out);
1932 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
1934 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
1937 if (parser->tok != ';') {
1938 parseerror(parser, "semicolon expected after expression");
1942 if (!parser_next(parser)) {
1949 static void parser_enterblock(parser_t *parser)
1951 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1952 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1953 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1954 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1955 vec_push(parser->_block_ctx, parser_ctx(parser));
1958 vec_push(parser->correct_variables, correct_trie_new());
1959 vec_push(parser->correct_variables_score, NULL);
1962 static bool parser_leaveblock(parser_t *parser)
1965 size_t locals, typedefs;
1967 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1968 parseerror(parser, "internal error: parser_leaveblock with no block");
1972 util_htdel(vec_last(parser->variables));
1973 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
1975 vec_pop(parser->variables);
1976 vec_pop(parser->correct_variables);
1977 vec_pop(parser->correct_variables_score);
1978 if (!vec_size(parser->_blocklocals)) {
1979 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1983 locals = vec_last(parser->_blocklocals);
1984 vec_pop(parser->_blocklocals);
1985 while (vec_size(parser->_locals) != locals) {
1986 ast_expression *e = vec_last(parser->_locals);
1987 ast_value *v = (ast_value*)e;
1988 vec_pop(parser->_locals);
1989 if (ast_istype(e, ast_value) && !v->uses) {
1990 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1995 typedefs = vec_last(parser->_blocktypedefs);
1996 while (vec_size(parser->_typedefs) != typedefs) {
1997 ast_delete(vec_last(parser->_typedefs));
1998 vec_pop(parser->_typedefs);
2000 util_htdel(vec_last(parser->typedefs));
2001 vec_pop(parser->typedefs);
2003 vec_pop(parser->_block_ctx);
2008 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2010 vec_push(parser->_locals, e);
2011 util_htset(vec_last(parser->variables), name, (void*)e);
2015 vec_last(parser->correct_variables),
2016 &vec_last(parser->correct_variables_score),
2021 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2023 vec_push(parser->globals, e);
2024 util_htset(parser->htglobals, name, e);
2028 parser->correct_variables[0],
2029 &parser->correct_variables_score[0],
2034 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2038 ast_expression *prev;
2040 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2042 ast_type_to_string(cond, ty, sizeof(ty));
2043 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2046 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2049 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2052 parseerror(parser, "internal error: failed to process condition");
2057 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2059 /* vector types need to be cast to true booleans */
2060 ast_binary *bin = (ast_binary*)cond;
2061 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2063 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2065 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2068 parseerror(parser, "internal error: failed to process condition");
2075 unary = (ast_unary*)cond;
2076 /* ast_istype dereferences cond, should test here for safety */
2077 while (cond && ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2079 cond = unary->operand;
2080 unary->operand = NULL;
2083 unary = (ast_unary*)cond;
2087 parseerror(parser, "internal error: failed to process condition");
2089 if (ifnot) *_ifnot = !*_ifnot;
2093 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2096 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2099 lex_ctx_t ctx = parser_ctx(parser);
2101 (void)block; /* not touching */
2103 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2104 if (!parser_next(parser)) {
2105 parseerror(parser, "expected condition or 'not'");
2108 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2110 if (!parser_next(parser)) {
2111 parseerror(parser, "expected condition in parenthesis");
2115 if (parser->tok != '(') {
2116 parseerror(parser, "expected 'if' condition in parenthesis");
2119 /* parse into the expression */
2120 if (!parser_next(parser)) {
2121 parseerror(parser, "expected 'if' condition after opening paren");
2124 /* parse the condition */
2125 cond = parse_expression_leave(parser, false, true, false);
2129 if (parser->tok != ')') {
2130 parseerror(parser, "expected closing paren after 'if' condition");
2134 /* parse into the 'then' branch */
2135 if (!parser_next(parser)) {
2136 parseerror(parser, "expected statement for on-true branch of 'if'");
2140 if (!parse_statement_or_block(parser, &ontrue)) {
2145 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2146 /* check for an else */
2147 if (!strcmp(parser_tokval(parser), "else")) {
2148 /* parse into the 'else' branch */
2149 if (!parser_next(parser)) {
2150 parseerror(parser, "expected on-false branch after 'else'");
2155 if (!parse_statement_or_block(parser, &onfalse)) {
2162 cond = process_condition(parser, cond, &ifnot);
2164 if (ontrue) ast_delete(ontrue);
2165 if (onfalse) ast_delete(onfalse);
2170 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2172 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2173 *out = (ast_expression*)ifthen;
2177 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2178 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2183 /* skip the 'while' and get the body */
2184 if (!parser_next(parser)) {
2185 if (OPTS_FLAG(LOOP_LABELS))
2186 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2188 parseerror(parser, "expected 'while' condition in parenthesis");
2192 if (parser->tok == ':') {
2193 if (!OPTS_FLAG(LOOP_LABELS))
2194 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2195 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2196 parseerror(parser, "expected loop label");
2199 label = util_strdup(parser_tokval(parser));
2200 if (!parser_next(parser)) {
2202 parseerror(parser, "expected 'while' condition in parenthesis");
2207 if (parser->tok != '(') {
2208 parseerror(parser, "expected 'while' condition in parenthesis");
2212 vec_push(parser->breaks, label);
2213 vec_push(parser->continues, label);
2215 rv = parse_while_go(parser, block, out);
2218 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2219 parseerror(parser, "internal error: label stack corrupted");
2225 vec_pop(parser->breaks);
2226 vec_pop(parser->continues);
2231 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2234 ast_expression *cond, *ontrue;
2238 lex_ctx_t ctx = parser_ctx(parser);
2240 (void)block; /* not touching */
2242 /* parse into the expression */
2243 if (!parser_next(parser)) {
2244 parseerror(parser, "expected 'while' condition after opening paren");
2247 /* parse the condition */
2248 cond = parse_expression_leave(parser, false, true, false);
2252 if (parser->tok != ')') {
2253 parseerror(parser, "expected closing paren after 'while' condition");
2257 /* parse into the 'then' branch */
2258 if (!parser_next(parser)) {
2259 parseerror(parser, "expected while-loop body");
2263 if (!parse_statement_or_block(parser, &ontrue)) {
2268 cond = process_condition(parser, cond, &ifnot);
2273 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2274 *out = (ast_expression*)aloop;
2278 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2279 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2284 /* skip the 'do' and get the body */
2285 if (!parser_next(parser)) {
2286 if (OPTS_FLAG(LOOP_LABELS))
2287 parseerror(parser, "expected loop label or body");
2289 parseerror(parser, "expected loop body");
2293 if (parser->tok == ':') {
2294 if (!OPTS_FLAG(LOOP_LABELS))
2295 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2296 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2297 parseerror(parser, "expected loop label");
2300 label = util_strdup(parser_tokval(parser));
2301 if (!parser_next(parser)) {
2303 parseerror(parser, "expected loop body");
2308 vec_push(parser->breaks, label);
2309 vec_push(parser->continues, label);
2311 rv = parse_dowhile_go(parser, block, out);
2314 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2315 parseerror(parser, "internal error: label stack corrupted");
2318 * Test for NULL otherwise ast_delete dereferences null pointer
2326 vec_pop(parser->breaks);
2327 vec_pop(parser->continues);
2332 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2335 ast_expression *cond, *ontrue;
2339 lex_ctx_t ctx = parser_ctx(parser);
2341 (void)block; /* not touching */
2343 if (!parse_statement_or_block(parser, &ontrue))
2346 /* expect the "while" */
2347 if (parser->tok != TOKEN_KEYWORD ||
2348 strcmp(parser_tokval(parser), "while"))
2350 parseerror(parser, "expected 'while' and condition");
2355 /* skip the 'while' and check for opening paren */
2356 if (!parser_next(parser) || parser->tok != '(') {
2357 parseerror(parser, "expected 'while' condition in parenthesis");
2361 /* parse into the expression */
2362 if (!parser_next(parser)) {
2363 parseerror(parser, "expected 'while' condition after opening paren");
2367 /* parse the condition */
2368 cond = parse_expression_leave(parser, false, true, false);
2372 if (parser->tok != ')') {
2373 parseerror(parser, "expected closing paren after 'while' condition");
2379 if (!parser_next(parser) || parser->tok != ';') {
2380 parseerror(parser, "expected semicolon after condition");
2386 if (!parser_next(parser)) {
2387 parseerror(parser, "parse error");
2393 cond = process_condition(parser, cond, &ifnot);
2398 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2399 *out = (ast_expression*)aloop;
2403 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2404 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2409 /* skip the 'for' and check for opening paren */
2410 if (!parser_next(parser)) {
2411 if (OPTS_FLAG(LOOP_LABELS))
2412 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2414 parseerror(parser, "expected 'for' expressions in parenthesis");
2418 if (parser->tok == ':') {
2419 if (!OPTS_FLAG(LOOP_LABELS))
2420 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2421 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2422 parseerror(parser, "expected loop label");
2425 label = util_strdup(parser_tokval(parser));
2426 if (!parser_next(parser)) {
2428 parseerror(parser, "expected 'for' expressions in parenthesis");
2433 if (parser->tok != '(') {
2434 parseerror(parser, "expected 'for' expressions in parenthesis");
2438 vec_push(parser->breaks, label);
2439 vec_push(parser->continues, label);
2441 rv = parse_for_go(parser, block, out);
2444 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2445 parseerror(parser, "internal error: label stack corrupted");
2451 vec_pop(parser->breaks);
2452 vec_pop(parser->continues);
2456 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2459 ast_expression *initexpr, *cond, *increment, *ontrue;
2464 lex_ctx_t ctx = parser_ctx(parser);
2466 parser_enterblock(parser);
2473 /* parse into the expression */
2474 if (!parser_next(parser)) {
2475 parseerror(parser, "expected 'for' initializer after opening paren");
2480 if (parser->tok == TOKEN_IDENT)
2481 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2483 if (typevar || parser->tok == TOKEN_TYPENAME) {
2485 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2486 if (parsewarning(parser, WARN_EXTENSIONS,
2487 "current standard does not allow variable declarations in for-loop initializers"))
2491 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2494 else if (parser->tok != ';')
2496 initexpr = parse_expression_leave(parser, false, false, false);
2501 /* move on to condition */
2502 if (parser->tok != ';') {
2503 parseerror(parser, "expected semicolon after for-loop initializer");
2506 if (!parser_next(parser)) {
2507 parseerror(parser, "expected for-loop condition");
2511 /* parse the condition */
2512 if (parser->tok != ';') {
2513 cond = parse_expression_leave(parser, false, true, false);
2518 /* move on to incrementor */
2519 if (parser->tok != ';') {
2520 parseerror(parser, "expected semicolon after for-loop initializer");
2523 if (!parser_next(parser)) {
2524 parseerror(parser, "expected for-loop condition");
2528 /* parse the incrementor */
2529 if (parser->tok != ')') {
2530 lex_ctx_t condctx = parser_ctx(parser);
2531 increment = parse_expression_leave(parser, false, false, false);
2534 if (!ast_side_effects(increment)) {
2535 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2541 if (parser->tok != ')') {
2542 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2545 /* parse into the 'then' branch */
2546 if (!parser_next(parser)) {
2547 parseerror(parser, "expected for-loop body");
2550 if (!parse_statement_or_block(parser, &ontrue))
2554 cond = process_condition(parser, cond, &ifnot);
2558 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2559 *out = (ast_expression*)aloop;
2561 if (!parser_leaveblock(parser)) {
2567 if (initexpr) ast_unref(initexpr);
2568 if (cond) ast_unref(cond);
2569 if (increment) ast_unref(increment);
2570 (void)!parser_leaveblock(parser);
2574 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2576 ast_expression *exp = NULL;
2577 ast_expression *var = NULL;
2578 ast_return *ret = NULL;
2579 ast_value *retval = parser->function->return_value;
2580 ast_value *expected = parser->function->vtype;
2582 lex_ctx_t ctx = parser_ctx(parser);
2584 (void)block; /* not touching */
2586 if (!parser_next(parser)) {
2587 parseerror(parser, "expected return expression");
2591 /* return assignments */
2592 if (parser->tok == '=') {
2593 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2594 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2598 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2600 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2601 parseerror(parser, "invalid return type: `%s'", ty1);
2605 if (!parser_next(parser)) {
2606 parseerror(parser, "expected return assignment expression");
2610 if (!(exp = parse_expression_leave(parser, false, false, false)))
2613 /* prepare the return value */
2615 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2616 ast_type_adopt(retval, expected->expression.next);
2617 parser->function->return_value = retval;
2620 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2621 char ty1[1024], ty2[1024];
2622 ast_type_to_string(exp, ty1, sizeof(ty1));
2623 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2624 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2627 /* store to 'return' local variable */
2628 var = (ast_expression*)ast_store_new(
2630 type_store_instr[expected->expression.next->vtype],
2631 (ast_expression*)retval, exp);
2638 if (parser->tok != ';')
2639 parseerror(parser, "missing semicolon after return assignment");
2640 else if (!parser_next(parser))
2641 parseerror(parser, "parse error after return assignment");
2647 if (parser->tok != ';') {
2648 exp = parse_expression(parser, false, false);
2652 if (exp->vtype != TYPE_NIL &&
2653 exp->vtype != ((ast_expression*)expected)->next->vtype)
2655 parseerror(parser, "return with invalid expression");
2658 ret = ast_return_new(ctx, exp);
2664 if (!parser_next(parser))
2665 parseerror(parser, "parse error");
2667 if (!retval && expected->expression.next->vtype != TYPE_VOID)
2669 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2671 ret = ast_return_new(ctx, (ast_expression*)retval);
2673 *out = (ast_expression*)ret;
2677 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2680 unsigned int levels = 0;
2681 lex_ctx_t ctx = parser_ctx(parser);
2682 const char **loops = (is_continue ? parser->continues : parser->breaks);
2684 (void)block; /* not touching */
2685 if (!parser_next(parser)) {
2686 parseerror(parser, "expected semicolon or loop label");
2690 if (!vec_size(loops)) {
2692 parseerror(parser, "`continue` can only be used inside loops");
2694 parseerror(parser, "`break` can only be used inside loops or switches");
2697 if (parser->tok == TOKEN_IDENT) {
2698 if (!OPTS_FLAG(LOOP_LABELS))
2699 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2700 i = vec_size(loops);
2702 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2705 parseerror(parser, "no such loop to %s: `%s`",
2706 (is_continue ? "continue" : "break out of"),
2707 parser_tokval(parser));
2712 if (!parser_next(parser)) {
2713 parseerror(parser, "expected semicolon");
2718 if (parser->tok != ';') {
2719 parseerror(parser, "expected semicolon");
2723 if (!parser_next(parser))
2724 parseerror(parser, "parse error");
2726 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2730 /* returns true when it was a variable qualifier, false otherwise!
2731 * on error, cvq is set to CV_WRONG
2733 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2735 bool had_const = false;
2736 bool had_var = false;
2737 bool had_noref = false;
2738 bool had_attrib = false;
2739 bool had_static = false;
2744 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2746 /* parse an attribute */
2747 if (!parser_next(parser)) {
2748 parseerror(parser, "expected attribute after `[[`");
2752 if (!strcmp(parser_tokval(parser), "noreturn")) {
2753 flags |= AST_FLAG_NORETURN;
2754 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2755 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2760 else if (!strcmp(parser_tokval(parser), "noref")) {
2762 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2763 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2768 else if (!strcmp(parser_tokval(parser), "inline")) {
2769 flags |= AST_FLAG_INLINE;
2770 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2771 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2776 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2777 flags |= AST_FLAG_ALIAS;
2780 if (!parser_next(parser)) {
2781 parseerror(parser, "parse error in attribute");
2785 if (parser->tok == '(') {
2786 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2787 parseerror(parser, "`alias` attribute missing parameter");
2791 *message = util_strdup(parser_tokval(parser));
2793 if (!parser_next(parser)) {
2794 parseerror(parser, "parse error in attribute");
2798 if (parser->tok != ')') {
2799 parseerror(parser, "`alias` attribute expected `)` after parameter");
2803 if (!parser_next(parser)) {
2804 parseerror(parser, "parse error in attribute");
2809 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2810 parseerror(parser, "`alias` attribute expected `]]`");
2814 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2815 flags |= AST_FLAG_DEPRECATED;
2818 if (!parser_next(parser)) {
2819 parseerror(parser, "parse error in attribute");
2823 if (parser->tok == '(') {
2824 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2825 parseerror(parser, "`deprecated` attribute missing parameter");
2829 *message = util_strdup(parser_tokval(parser));
2831 if (!parser_next(parser)) {
2832 parseerror(parser, "parse error in attribute");
2836 if(parser->tok != ')') {
2837 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "parse error in attribute");
2847 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2848 parseerror(parser, "`deprecated` attribute expected `]]`");
2851 if (*message) mem_d(*message);
2859 /* Skip tokens until we hit a ]] */
2860 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2861 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2862 if (!parser_next(parser)) {
2863 parseerror(parser, "error inside attribute");
2870 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2872 else if (!strcmp(parser_tokval(parser), "const"))
2874 else if (!strcmp(parser_tokval(parser), "var"))
2876 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2878 else if (!strcmp(parser_tokval(parser), "noref"))
2880 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2885 if (!parser_next(parser))
2895 *is_static = had_static;
2899 parseerror(parser, "parse error after variable qualifier");
2904 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2905 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2910 /* skip the 'while' and get the body */
2911 if (!parser_next(parser)) {
2912 if (OPTS_FLAG(LOOP_LABELS))
2913 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2915 parseerror(parser, "expected 'switch' operand in parenthesis");
2919 if (parser->tok == ':') {
2920 if (!OPTS_FLAG(LOOP_LABELS))
2921 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2922 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2923 parseerror(parser, "expected loop label");
2926 label = util_strdup(parser_tokval(parser));
2927 if (!parser_next(parser)) {
2929 parseerror(parser, "expected 'switch' operand in parenthesis");
2934 if (parser->tok != '(') {
2935 parseerror(parser, "expected 'switch' operand in parenthesis");
2939 vec_push(parser->breaks, label);
2941 rv = parse_switch_go(parser, block, out);
2944 if (vec_last(parser->breaks) != label) {
2945 parseerror(parser, "internal error: label stack corrupted");
2951 vec_pop(parser->breaks);
2956 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2958 ast_expression *operand;
2961 ast_switch *switchnode;
2962 ast_switch_case swcase;
2965 bool noref, is_static;
2966 uint32_t qflags = 0;
2968 lex_ctx_t ctx = parser_ctx(parser);
2970 (void)block; /* not touching */
2973 /* parse into the expression */
2974 if (!parser_next(parser)) {
2975 parseerror(parser, "expected switch operand");
2978 /* parse the operand */
2979 operand = parse_expression_leave(parser, false, false, false);
2983 switchnode = ast_switch_new(ctx, operand);
2986 if (parser->tok != ')') {
2987 ast_delete(switchnode);
2988 parseerror(parser, "expected closing paren after 'switch' operand");
2992 /* parse over the opening paren */
2993 if (!parser_next(parser) || parser->tok != '{') {
2994 ast_delete(switchnode);
2995 parseerror(parser, "expected list of cases");
2999 if (!parser_next(parser)) {
3000 ast_delete(switchnode);
3001 parseerror(parser, "expected 'case' or 'default'");
3005 /* new block; allow some variables to be declared here */
3006 parser_enterblock(parser);
3009 if (parser->tok == TOKEN_IDENT)
3010 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3011 if (typevar || parser->tok == TOKEN_TYPENAME) {
3012 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3013 ast_delete(switchnode);
3018 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3020 if (cvq == CV_WRONG) {
3021 ast_delete(switchnode);
3024 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3025 ast_delete(switchnode);
3034 while (parser->tok != '}') {
3035 ast_block *caseblock;
3037 if (!strcmp(parser_tokval(parser), "case")) {
3038 if (!parser_next(parser)) {
3039 ast_delete(switchnode);
3040 parseerror(parser, "expected expression for case");
3043 swcase.value = parse_expression_leave(parser, false, false, false);
3044 if (!swcase.value) {
3045 ast_delete(switchnode);
3046 parseerror(parser, "expected expression for case");
3049 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3050 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3051 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3057 else if (!strcmp(parser_tokval(parser), "default")) {
3058 swcase.value = NULL;
3059 if (!parser_next(parser)) {
3060 ast_delete(switchnode);
3061 parseerror(parser, "expected colon");
3066 ast_delete(switchnode);
3067 parseerror(parser, "expected 'case' or 'default'");
3071 /* Now the colon and body */
3072 if (parser->tok != ':') {
3073 if (swcase.value) ast_unref(swcase.value);
3074 ast_delete(switchnode);
3075 parseerror(parser, "expected colon");
3079 if (!parser_next(parser)) {
3080 if (swcase.value) ast_unref(swcase.value);
3081 ast_delete(switchnode);
3082 parseerror(parser, "expected statements or case");
3085 caseblock = ast_block_new(parser_ctx(parser));
3087 if (swcase.value) ast_unref(swcase.value);
3088 ast_delete(switchnode);
3091 swcase.code = (ast_expression*)caseblock;
3092 vec_push(switchnode->cases, swcase);
3094 ast_expression *expr;
3095 if (parser->tok == '}')
3097 if (parser->tok == TOKEN_KEYWORD) {
3098 if (!strcmp(parser_tokval(parser), "case") ||
3099 !strcmp(parser_tokval(parser), "default"))
3104 if (!parse_statement(parser, caseblock, &expr, true)) {
3105 ast_delete(switchnode);
3110 if (!ast_block_add_expr(caseblock, expr)) {
3111 ast_delete(switchnode);
3117 parser_leaveblock(parser);
3120 if (parser->tok != '}') {
3121 ast_delete(switchnode);
3122 parseerror(parser, "expected closing paren of case list");
3125 if (!parser_next(parser)) {
3126 ast_delete(switchnode);
3127 parseerror(parser, "parse error after switch");
3130 *out = (ast_expression*)switchnode;
3134 /* parse computed goto sides */
3135 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3136 ast_expression *on_true;
3137 ast_expression *on_false;
3138 ast_expression *cond;
3143 if (ast_istype(*side, ast_ternary)) {
3144 ast_ternary *tern = (ast_ternary*)*side;
3145 on_true = parse_goto_computed(parser, &tern->on_true);
3146 on_false = parse_goto_computed(parser, &tern->on_false);
3148 if (!on_true || !on_false) {
3149 parseerror(parser, "expected label or expression in ternary");
3150 if (on_true) ast_unref(on_true);
3151 if (on_false) ast_unref(on_false);
3159 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3160 } else if (ast_istype(*side, ast_label)) {
3161 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3162 ast_goto_set_label(gt, ((ast_label*)*side));
3164 return (ast_expression*)gt;
3169 static bool parse_goto(parser_t *parser, ast_expression **out)
3171 ast_goto *gt = NULL;
3172 ast_expression *lbl;
3174 if (!parser_next(parser))
3177 if (parser->tok != TOKEN_IDENT) {
3178 ast_expression *expression;
3180 /* could be an expression i.e computed goto :-) */
3181 if (parser->tok != '(') {
3182 parseerror(parser, "expected label name after `goto`");
3186 /* failed to parse expression for goto */
3187 if (!(expression = parse_expression(parser, false, true)) ||
3188 !(*out = parse_goto_computed(parser, &expression))) {
3189 parseerror(parser, "invalid goto expression");
3191 ast_unref(expression);
3198 /* not computed goto */
3199 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3200 lbl = parser_find_label(parser, gt->name);
3202 if (!ast_istype(lbl, ast_label)) {
3203 parseerror(parser, "internal error: label is not an ast_label");
3207 ast_goto_set_label(gt, (ast_label*)lbl);
3210 vec_push(parser->gotos, gt);
3212 if (!parser_next(parser) || parser->tok != ';') {
3213 parseerror(parser, "semicolon expected after goto label");
3216 if (!parser_next(parser)) {
3217 parseerror(parser, "parse error after goto");
3221 *out = (ast_expression*)gt;
3225 static bool parse_skipwhite(parser_t *parser)
3228 if (!parser_next(parser))
3230 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3231 return parser->tok < TOKEN_ERROR;
3234 static bool parse_eol(parser_t *parser)
3236 if (!parse_skipwhite(parser))
3238 return parser->tok == TOKEN_EOL;
3241 static bool parse_pragma_do(parser_t *parser)
3243 if (!parser_next(parser) ||
3244 parser->tok != TOKEN_IDENT ||
3245 strcmp(parser_tokval(parser), "pragma"))
3247 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3250 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3251 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3255 if (!strcmp(parser_tokval(parser), "noref")) {
3256 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3257 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3260 parser->noref = !!parser_token(parser)->constval.i;
3261 if (!parse_eol(parser)) {
3262 parseerror(parser, "parse error after `noref` pragma");
3268 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3275 static bool parse_pragma(parser_t *parser)
3278 parser->lex->flags.preprocessing = true;
3279 parser->lex->flags.mergelines = true;
3280 rv = parse_pragma_do(parser);
3281 if (parser->tok != TOKEN_EOL) {
3282 parseerror(parser, "junk after pragma");
3285 parser->lex->flags.preprocessing = false;
3286 parser->lex->flags.mergelines = false;
3287 if (!parser_next(parser)) {
3288 parseerror(parser, "parse error after pragma");
3294 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3296 bool noref, is_static;
3298 uint32_t qflags = 0;
3299 ast_value *typevar = NULL;
3300 char *vstring = NULL;
3304 if (parser->tok == TOKEN_IDENT)
3305 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3307 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3309 /* local variable */
3311 parseerror(parser, "cannot declare a variable from here");
3314 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3315 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3318 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3322 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3324 if (cvq == CV_WRONG)
3326 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3328 else if (parser->tok == TOKEN_KEYWORD)
3330 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3335 if (!parser_next(parser)) {
3336 parseerror(parser, "parse error after __builtin_debug_printtype");
3340 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3342 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3343 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3344 if (!parser_next(parser)) {
3345 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3351 if (!parse_statement(parser, block, out, allow_cases))
3354 con_out("__builtin_debug_printtype: got no output node\n");
3357 ast_type_to_string(*out, ty, sizeof(ty));
3358 con_out("__builtin_debug_printtype: `%s`\n", ty);
3363 else if (!strcmp(parser_tokval(parser), "return"))
3365 return parse_return(parser, block, out);
3367 else if (!strcmp(parser_tokval(parser), "if"))
3369 return parse_if(parser, block, out);
3371 else if (!strcmp(parser_tokval(parser), "while"))
3373 return parse_while(parser, block, out);
3375 else if (!strcmp(parser_tokval(parser), "do"))
3377 return parse_dowhile(parser, block, out);
3379 else if (!strcmp(parser_tokval(parser), "for"))
3381 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3382 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3385 return parse_for(parser, block, out);
3387 else if (!strcmp(parser_tokval(parser), "break"))
3389 return parse_break_continue(parser, block, out, false);
3391 else if (!strcmp(parser_tokval(parser), "continue"))
3393 return parse_break_continue(parser, block, out, true);
3395 else if (!strcmp(parser_tokval(parser), "switch"))
3397 return parse_switch(parser, block, out);
3399 else if (!strcmp(parser_tokval(parser), "case") ||
3400 !strcmp(parser_tokval(parser), "default"))
3403 parseerror(parser, "unexpected 'case' label");
3408 else if (!strcmp(parser_tokval(parser), "goto"))
3410 return parse_goto(parser, out);
3412 else if (!strcmp(parser_tokval(parser), "typedef"))
3414 if (!parser_next(parser)) {
3415 parseerror(parser, "expected type definition after 'typedef'");
3418 return parse_typedef(parser);
3420 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3423 else if (parser->tok == '{')
3426 inner = parse_block(parser);
3429 *out = (ast_expression*)inner;
3432 else if (parser->tok == ':')
3436 if (!parser_next(parser)) {
3437 parseerror(parser, "expected label name");
3440 if (parser->tok != TOKEN_IDENT) {
3441 parseerror(parser, "label must be an identifier");
3444 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3446 if (!label->undefined) {
3447 parseerror(parser, "label `%s` already defined", label->name);
3450 label->undefined = false;
3453 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3454 vec_push(parser->labels, label);
3456 *out = (ast_expression*)label;
3457 if (!parser_next(parser)) {
3458 parseerror(parser, "parse error after label");
3461 for (i = 0; i < vec_size(parser->gotos); ++i) {
3462 if (!strcmp(parser->gotos[i]->name, label->name)) {
3463 ast_goto_set_label(parser->gotos[i], label);
3464 vec_remove(parser->gotos, i, 1);
3470 else if (parser->tok == ';')
3472 if (!parser_next(parser)) {
3473 parseerror(parser, "parse error after empty statement");
3480 lex_ctx_t ctx = parser_ctx(parser);
3481 ast_expression *exp = parse_expression(parser, false, false);
3485 if (!ast_side_effects(exp)) {
3486 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3493 static bool parse_enum(parser_t *parser)
3496 bool reverse = false;
3498 ast_value **values = NULL;
3499 ast_value *var = NULL;
3502 ast_expression *old;
3504 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3505 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3509 /* enumeration attributes (can add more later) */
3510 if (parser->tok == ':') {
3511 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3512 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3517 if (!strcmp(parser_tokval(parser), "flag")) {
3521 else if (!strcmp(parser_tokval(parser), "reverse")) {
3525 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3529 if (!parser_next(parser) || parser->tok != '{') {
3530 parseerror(parser, "expected `{` after enum attribute ");
3536 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3537 if (parser->tok == '}') {
3538 /* allow an empty enum */
3541 parseerror(parser, "expected identifier or `}`");
3545 old = parser_find_field(parser, parser_tokval(parser));
3547 old = parser_find_global(parser, parser_tokval(parser));
3549 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3550 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3554 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3555 vec_push(values, var);
3556 var->cvq = CV_CONST;
3557 var->hasvalue = true;
3559 /* for flagged enumerations increment in POTs of TWO */
3560 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3561 parser_addglobal(parser, var->name, (ast_expression*)var);
3563 if (!parser_next(parser)) {
3564 parseerror(parser, "expected `=`, `}` or comma after identifier");
3568 if (parser->tok == ',')
3570 if (parser->tok == '}')
3572 if (parser->tok != '=') {
3573 parseerror(parser, "expected `=`, `}` or comma after identifier");
3577 if (!parser_next(parser)) {
3578 parseerror(parser, "expected expression after `=`");
3582 /* We got a value! */
3583 old = parse_expression_leave(parser, true, false, false);
3584 asvalue = (ast_value*)old;
3585 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3586 compile_error(ast_ctx(var), "constant value or expression expected");
3589 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3591 if (parser->tok == '}')
3593 if (parser->tok != ',') {
3594 parseerror(parser, "expected `}` or comma after expression");
3599 /* patch them all (for reversed attribute) */
3602 for (i = 0; i < vec_size(values); i++)
3603 values[i]->constval.vfloat = vec_size(values) - i - 1;
3606 if (parser->tok != '}') {
3607 parseerror(parser, "internal error: breaking without `}`");
3611 if (!parser_next(parser) || parser->tok != ';') {
3612 parseerror(parser, "expected semicolon after enumeration");
3616 if (!parser_next(parser)) {
3617 parseerror(parser, "parse error after enumeration");
3629 static bool parse_block_into(parser_t *parser, ast_block *block)
3633 parser_enterblock(parser);
3635 if (!parser_next(parser)) { /* skip the '{' */
3636 parseerror(parser, "expected function body");
3640 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3642 ast_expression *expr = NULL;
3643 if (parser->tok == '}')
3646 if (!parse_statement(parser, block, &expr, false)) {
3647 /* parseerror(parser, "parse error"); */
3653 if (!ast_block_add_expr(block, expr)) {
3660 if (parser->tok != '}') {
3663 (void)parser_next(parser);
3667 if (!parser_leaveblock(parser))
3669 return retval && !!block;
3672 static ast_block* parse_block(parser_t *parser)
3675 block = ast_block_new(parser_ctx(parser));
3678 if (!parse_block_into(parser, block)) {
3679 ast_block_delete(block);
3685 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3687 if (parser->tok == '{') {
3688 *out = (ast_expression*)parse_block(parser);
3691 return parse_statement(parser, NULL, out, false);
3694 static bool create_vector_members(ast_value *var, ast_member **me)
3697 size_t len = strlen(var->name);
3699 for (i = 0; i < 3; ++i) {
3700 char *name = (char*)mem_a(len+3);
3701 memcpy(name, var->name, len);
3703 name[len+1] = 'x'+i;
3705 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3714 do { ast_member_delete(me[--i]); } while(i);
3718 static bool parse_function_body(parser_t *parser, ast_value *var)
3720 ast_block *block = NULL;
3725 ast_expression *framenum = NULL;
3726 ast_expression *nextthink = NULL;
3727 /* None of the following have to be deleted */
3728 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3729 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3730 bool has_frame_think;
3734 has_frame_think = false;
3735 old = parser->function;
3737 if (var->expression.flags & AST_FLAG_ALIAS) {
3738 parseerror(parser, "function aliases cannot have bodies");
3742 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3743 parseerror(parser, "gotos/labels leaking");
3747 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3748 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3749 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3755 if (parser->tok == '[') {
3756 /* got a frame definition: [ framenum, nextthink ]
3757 * this translates to:
3758 * self.frame = framenum;
3759 * self.nextthink = time + 0.1;
3760 * self.think = nextthink;
3764 fld_think = parser_find_field(parser, "think");
3765 fld_nextthink = parser_find_field(parser, "nextthink");
3766 fld_frame = parser_find_field(parser, "frame");
3767 if (!fld_think || !fld_nextthink || !fld_frame) {
3768 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3769 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3772 gbl_time = parser_find_global(parser, "time");
3773 gbl_self = parser_find_global(parser, "self");
3774 if (!gbl_time || !gbl_self) {
3775 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3776 parseerror(parser, "please declare the following globals: `time`, `self`");
3780 if (!parser_next(parser))
3783 framenum = parse_expression_leave(parser, true, false, false);
3785 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3788 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3789 ast_unref(framenum);
3790 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3794 if (parser->tok != ',') {
3795 ast_unref(framenum);
3796 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3797 parseerror(parser, "Got a %i\n", parser->tok);
3801 if (!parser_next(parser)) {
3802 ast_unref(framenum);
3806 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3808 /* qc allows the use of not-yet-declared functions here
3809 * - this automatically creates a prototype */
3810 ast_value *thinkfunc;
3811 ast_expression *functype = fld_think->next;
3813 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
3814 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
3815 ast_unref(framenum);
3816 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3819 ast_type_adopt(thinkfunc, functype);
3821 if (!parser_next(parser)) {
3822 ast_unref(framenum);
3823 ast_delete(thinkfunc);
3827 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3829 nextthink = (ast_expression*)thinkfunc;
3832 nextthink = parse_expression_leave(parser, true, false, false);
3834 ast_unref(framenum);
3835 parseerror(parser, "expected a think-function in [frame,think] notation");
3840 if (!ast_istype(nextthink, ast_value)) {
3841 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3845 if (retval && parser->tok != ']') {
3846 parseerror(parser, "expected closing `]` for [frame,think] notation");
3850 if (retval && !parser_next(parser)) {
3854 if (retval && parser->tok != '{') {
3855 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3860 ast_unref(nextthink);
3861 ast_unref(framenum);
3865 has_frame_think = true;
3868 block = ast_block_new(parser_ctx(parser));
3870 parseerror(parser, "failed to allocate block");
3871 if (has_frame_think) {
3872 ast_unref(nextthink);
3873 ast_unref(framenum);
3878 if (has_frame_think) {
3880 ast_expression *self_frame;
3881 ast_expression *self_nextthink;
3882 ast_expression *self_think;
3883 ast_expression *time_plus_1;
3884 ast_store *store_frame;
3885 ast_store *store_nextthink;
3886 ast_store *store_think;
3888 ctx = parser_ctx(parser);
3889 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3890 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3891 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3893 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3894 gbl_time, (ast_expression*)fold_constgen_float(parser->fold, 0.1));
3896 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3897 if (self_frame) ast_delete(self_frame);
3898 if (self_nextthink) ast_delete(self_nextthink);
3899 if (self_think) ast_delete(self_think);
3900 if (time_plus_1) ast_delete(time_plus_1);
3906 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3907 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3908 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3911 ast_delete(self_frame);
3914 if (!store_nextthink) {
3915 ast_delete(self_nextthink);
3919 ast_delete(self_think);
3923 if (store_frame) ast_delete(store_frame);
3924 if (store_nextthink) ast_delete(store_nextthink);
3925 if (store_think) ast_delete(store_think);
3928 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3929 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3930 !ast_block_add_expr(block, (ast_expression*)store_think))
3937 parseerror(parser, "failed to generate code for [frame,think]");
3938 ast_unref(nextthink);
3939 ast_unref(framenum);
3945 if (var->hasvalue) {
3946 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
3947 ast_block_delete(block);
3951 func = ast_function_new(ast_ctx(var), var->name, var);
3953 parseerror(parser, "failed to allocate function for `%s`", var->name);
3954 ast_block_delete(block);
3957 vec_push(parser->functions, func);
3959 parser_enterblock(parser);
3961 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3963 ast_value *param = var->expression.params[parami];
3966 if (param->expression.vtype != TYPE_VECTOR &&
3967 (param->expression.vtype != TYPE_FIELD ||
3968 param->expression.next->vtype != TYPE_VECTOR))
3973 if (!create_vector_members(param, me)) {
3974 ast_block_delete(block);
3978 for (e = 0; e < 3; ++e) {
3979 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3980 ast_block_collect(block, (ast_expression*)me[e]);
3984 if (var->argcounter) {
3985 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3986 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3990 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3992 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
3993 varargs->expression.flags |= AST_FLAG_IS_VARARG;
3994 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
3995 varargs->expression.count = 0;
3996 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
3997 if (!parser_create_array_setter_proto(parser, varargs, name)) {
3998 ast_delete(varargs);
3999 ast_block_delete(block);
4002 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4003 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4004 ast_delete(varargs);
4005 ast_block_delete(block);
4008 func->varargs = varargs;
4009 func->fixedparams = (ast_value*)fold_constgen_float(parser->fold, vec_size(var->expression.params));
4012 parser->function = func;
4013 if (!parse_block_into(parser, block)) {
4014 ast_block_delete(block);
4018 vec_push(func->blocks, block);
4021 parser->function = old;
4022 if (!parser_leaveblock(parser))
4024 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4025 parseerror(parser, "internal error: local scopes left");
4029 if (parser->tok == ';')
4030 return parser_next(parser);
4031 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4032 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4036 (void)!parser_leaveblock(parser);
4037 vec_pop(parser->functions);
4038 ast_function_delete(func);
4039 var->constval.vfunc = NULL;
4042 parser->function = old;
4046 static ast_expression *array_accessor_split(
4051 ast_expression *left,
4052 ast_expression *right
4058 lex_ctx_t ctx = ast_ctx(array);
4060 if (!left || !right) {
4061 if (left) ast_delete(left);
4062 if (right) ast_delete(right);
4066 cmp = ast_binary_new(ctx, INSTR_LT,
4067 (ast_expression*)index,
4068 (ast_expression*)fold_constgen_float(parser->fold, middle));
4072 parseerror(parser, "internal error: failed to create comparison for array setter");
4076 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4078 ast_delete(cmp); /* will delete left and right */
4079 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4083 return (ast_expression*)ifthen;
4086 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4088 lex_ctx_t ctx = ast_ctx(array);
4090 if (from+1 == afterend) {
4091 /* set this value */
4094 ast_array_index *subscript;
4096 int assignop = type_store_instr[value->expression.vtype];
4098 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4099 assignop = INSTR_STORE_V;
4101 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4105 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4107 ast_delete(subscript);
4111 block = ast_block_new(ctx);
4117 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4122 ret = ast_return_new(ctx, NULL);
4128 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4133 return (ast_expression*)block;
4135 ast_expression *left, *right;
4136 size_t diff = afterend - from;
4137 size_t middle = from + diff/2;
4138 left = array_setter_node(parser, array, index, value, from, middle);
4139 right = array_setter_node(parser, array, index, value, middle, afterend);
4140 return array_accessor_split(parser, array, index, middle, left, right);
4144 static ast_expression *array_field_setter_node(
4153 lex_ctx_t ctx = ast_ctx(array);
4155 if (from+1 == afterend) {
4156 /* set this value */
4159 ast_entfield *entfield;
4160 ast_array_index *subscript;
4162 int assignop = type_storep_instr[value->expression.vtype];
4164 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4165 assignop = INSTR_STOREP_V;
4167 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4171 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4172 subscript->expression.vtype = TYPE_FIELD;
4174 entfield = ast_entfield_new_force(ctx,
4175 (ast_expression*)entity,
4176 (ast_expression*)subscript,
4177 (ast_expression*)subscript);
4179 ast_delete(subscript);
4183 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4185 ast_delete(entfield);
4189 block = ast_block_new(ctx);
4195 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4200 ret = ast_return_new(ctx, NULL);
4206 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4211 return (ast_expression*)block;
4213 ast_expression *left, *right;
4214 size_t diff = afterend - from;
4215 size_t middle = from + diff/2;
4216 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4217 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4218 return array_accessor_split(parser, array, index, middle, left, right);
4222 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4224 lex_ctx_t ctx = ast_ctx(array);
4226 if (from+1 == afterend) {
4228 ast_array_index *subscript;
4230 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)fold_constgen_float(parser->fold, from));
4234 ret = ast_return_new(ctx, (ast_expression*)subscript);
4236 ast_delete(subscript);
4240 return (ast_expression*)ret;
4242 ast_expression *left, *right;
4243 size_t diff = afterend - from;
4244 size_t middle = from + diff/2;
4245 left = array_getter_node(parser, array, index, from, middle);
4246 right = array_getter_node(parser, array, index, middle, afterend);
4247 return array_accessor_split(parser, array, index, middle, left, right);
4251 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4253 ast_function *func = NULL;
4254 ast_value *fval = NULL;
4255 ast_block *body = NULL;
4257 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4259 parseerror(parser, "failed to create accessor function value");
4263 func = ast_function_new(ast_ctx(array), funcname, fval);
4266 parseerror(parser, "failed to create accessor function node");
4270 body = ast_block_new(ast_ctx(array));
4272 parseerror(parser, "failed to create block for array accessor");
4278 vec_push(func->blocks, body);
4281 vec_push(parser->accessors, fval);
4286 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4288 ast_value *index = NULL;
4289 ast_value *value = NULL;
4293 if (!ast_istype(array->expression.next, ast_value)) {
4294 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4298 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4300 func = fval->constval.vfunc;
4301 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4303 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4304 value = ast_value_copy((ast_value*)array->expression.next);
4306 if (!index || !value) {
4307 parseerror(parser, "failed to create locals for array accessor");
4310 (void)!ast_value_set_name(value, "value"); /* not important */
4311 vec_push(fval->expression.params, index);
4312 vec_push(fval->expression.params, value);
4314 array->setter = fval;
4317 if (index) ast_delete(index);
4318 if (value) ast_delete(value);
4324 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4326 ast_expression *root = NULL;
4327 root = array_setter_node(parser, array,
4328 array->setter->expression.params[0],
4329 array->setter->expression.params[1],
4330 0, array->expression.count);
4332 parseerror(parser, "failed to build accessor search tree");
4335 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4342 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4344 if (!parser_create_array_setter_proto(parser, array, funcname))
4346 return parser_create_array_setter_impl(parser, array);
4349 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4351 ast_expression *root = NULL;
4352 ast_value *entity = NULL;
4353 ast_value *index = NULL;
4354 ast_value *value = NULL;
4358 if (!ast_istype(array->expression.next, ast_value)) {
4359 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4363 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4365 func = fval->constval.vfunc;
4366 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4368 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4369 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4370 value = ast_value_copy((ast_value*)array->expression.next);
4371 if (!entity || !index || !value) {
4372 parseerror(parser, "failed to create locals for array accessor");
4375 (void)!ast_value_set_name(value, "value"); /* not important */
4376 vec_push(fval->expression.params, entity);
4377 vec_push(fval->expression.params, index);
4378 vec_push(fval->expression.params, value);
4380 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4382 parseerror(parser, "failed to build accessor search tree");
4386 array->setter = fval;
4387 return ast_block_add_expr(func->blocks[0], root);
4389 if (entity) ast_delete(entity);
4390 if (index) ast_delete(index);
4391 if (value) ast_delete(value);
4392 if (root) ast_delete(root);
4398 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4400 ast_value *index = NULL;
4404 /* NOTE: checking array->expression.next rather than elemtype since
4405 * for fields elemtype is a temporary fieldtype.
4407 if (!ast_istype(array->expression.next, ast_value)) {
4408 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4412 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4414 func = fval->constval.vfunc;
4415 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4417 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4420 parseerror(parser, "failed to create locals for array accessor");
4423 vec_push(fval->expression.params, index);
4425 array->getter = fval;
4428 if (index) ast_delete(index);
4434 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4436 ast_expression *root = NULL;
4438 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4440 parseerror(parser, "failed to build accessor search tree");
4443 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4450 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4452 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4454 return parser_create_array_getter_impl(parser, array);
4457 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4458 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4466 bool variadic = false;
4467 ast_value *varparam = NULL;
4468 char *argcounter = NULL;
4470 ctx = parser_ctx(parser);
4472 /* for the sake of less code we parse-in in this function */
4473 if (!parser_next(parser)) {
4475 parseerror(parser, "expected parameter list");
4481 /* parse variables until we hit a closing paren */
4482 while (parser->tok != ')') {
4484 /* there must be commas between them */
4485 if (parser->tok != ',') {
4486 parseerror(parser, "expected comma or end of parameter list");
4489 if (!parser_next(parser)) {
4490 parseerror(parser, "expected parameter");
4496 if (parser->tok == TOKEN_DOTS) {
4497 /* '...' indicates a varargs function */
4499 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4500 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4503 if (parser->tok == TOKEN_IDENT) {
4504 argcounter = util_strdup(parser_tokval(parser));
4505 if (!parser_next(parser) || parser->tok != ')') {
4506 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4513 /* for anything else just parse a typename */
4514 param = parse_typename(parser, NULL, NULL);
4517 vec_push(params, param);
4518 if (param->expression.vtype >= TYPE_VARIANT) {
4519 char tname[1024]; /* typename is reserved in C++ */
4520 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4521 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4524 /* type-restricted varargs */
4525 if (parser->tok == TOKEN_DOTS) {
4527 varparam = vec_last(params);
4529 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4530 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4533 if (parser->tok == TOKEN_IDENT) {
4534 argcounter = util_strdup(parser_tokval(parser));
4535 if (!parser_next(parser) || parser->tok != ')') {
4536 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4544 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4548 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4549 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4552 if (!parser_next(parser)) {
4553 parseerror(parser, "parse error after typename");
4557 /* now turn 'var' into a function type */
4558 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4559 fval->expression.next = (ast_expression*)var;
4561 fval->expression.flags |= AST_FLAG_VARIADIC;
4564 var->expression.params = params;
4565 var->expression.varparam = (ast_expression*)varparam;
4566 var->argcounter = argcounter;
4575 ast_delete(varparam);
4577 for (i = 0; i < vec_size(params); ++i)
4578 ast_delete(params[i]);
4583 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4585 ast_expression *cexp;
4586 ast_value *cval, *tmp;
4589 ctx = parser_ctx(parser);
4591 if (!parser_next(parser)) {
4593 parseerror(parser, "expected array-size");
4597 if (parser->tok != ']') {
4598 cexp = parse_expression_leave(parser, true, false, false);
4600 if (!cexp || !ast_istype(cexp, ast_value)) {
4604 parseerror(parser, "expected array-size as constant positive integer");
4607 cval = (ast_value*)cexp;
4614 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4615 tmp->expression.next = (ast_expression*)var;
4619 if (cval->expression.vtype == TYPE_INTEGER)
4620 tmp->expression.count = cval->constval.vint;
4621 else if (cval->expression.vtype == TYPE_FLOAT)
4622 tmp->expression.count = cval->constval.vfloat;
4626 parseerror(parser, "array-size must be a positive integer constant");
4632 var->expression.count = -1;
4633 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4636 if (parser->tok != ']') {
4638 parseerror(parser, "expected ']' after array-size");
4641 if (!parser_next(parser)) {
4643 parseerror(parser, "error after parsing array size");
4649 /* Parse a complete typename.
4650 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4651 * but when parsing variables separated by comma
4652 * 'storebase' should point to where the base-type should be kept.
4653 * The base type makes up every bit of type information which comes *before* the
4656 * The following will be parsed in its entirety:
4658 * The 'basetype' in this case is 'void()'
4659 * and if there's a comma after it, say:
4661 * then the type-information 'void()' can be stored in 'storebase'
4663 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4665 ast_value *var, *tmp;
4668 const char *name = NULL;
4669 bool isfield = false;
4670 bool wasarray = false;
4671 size_t morefields = 0;
4673 ctx = parser_ctx(parser);
4675 /* types may start with a dot */
4676 if (parser->tok == '.') {
4678 /* if we parsed a dot we need a typename now */
4679 if (!parser_next(parser)) {
4680 parseerror(parser, "expected typename for field definition");
4684 /* Further dots are handled seperately because they won't be part of the
4687 while (parser->tok == '.') {
4689 if (!parser_next(parser)) {
4690 parseerror(parser, "expected typename for field definition");
4695 if (parser->tok == TOKEN_IDENT)
4696 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4697 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4698 parseerror(parser, "expected typename");
4702 /* generate the basic type value */
4703 if (cached_typedef) {
4704 var = ast_value_copy(cached_typedef);
4705 ast_value_set_name(var, "<type(from_def)>");
4707 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4709 for (; morefields; --morefields) {
4710 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4711 tmp->expression.next = (ast_expression*)var;
4715 /* do not yet turn into a field - remember:
4716 * .void() foo; is a field too
4717 * .void()() foo; is a function
4721 if (!parser_next(parser)) {
4723 parseerror(parser, "parse error after typename");
4727 /* an opening paren now starts the parameter-list of a function
4728 * this is where original-QC has parameter lists.
4729 * We allow a single parameter list here.
4730 * Much like fteqcc we don't allow `float()() x`
4732 if (parser->tok == '(') {
4733 var = parse_parameter_list(parser, var);
4738 /* store the base if requested */
4740 *storebase = ast_value_copy(var);
4742 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4743 tmp->expression.next = (ast_expression*)*storebase;
4748 /* there may be a name now */
4749 if (parser->tok == TOKEN_IDENT) {
4750 name = util_strdup(parser_tokval(parser));
4752 if (!parser_next(parser)) {
4755 parseerror(parser, "error after variable or field declaration");
4760 /* now this may be an array */
4761 if (parser->tok == '[') {
4763 var = parse_arraysize(parser, var);
4765 if (name) mem_d(name);
4770 /* This is the point where we can turn it into a field */
4772 /* turn it into a field if desired */
4773 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4774 tmp->expression.next = (ast_expression*)var;
4778 /* now there may be function parens again */
4779 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4780 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4781 if (parser->tok == '(' && wasarray)
4782 parseerror(parser, "arrays as part of a return type is not supported");
4783 while (parser->tok == '(') {
4784 var = parse_parameter_list(parser, var);
4786 if (name) mem_d(name);
4791 /* finally name it */
4793 if (!ast_value_set_name(var, name)) {
4796 parseerror(parser, "internal error: failed to set name");
4799 /* free the name, ast_value_set_name duplicates */
4806 static bool parse_typedef(parser_t *parser)
4808 ast_value *typevar, *oldtype;
4809 ast_expression *old;
4811 typevar = parse_typename(parser, NULL, NULL);
4816 if ( (old = parser_find_var(parser, typevar->name)) ) {
4817 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4818 " -> `%s` has been declared here: %s:%i",
4819 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4820 ast_delete(typevar);
4824 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4825 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4826 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4827 ast_delete(typevar);
4831 vec_push(parser->_typedefs, typevar);
4832 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4834 if (parser->tok != ';') {
4835 parseerror(parser, "expected semicolon after typedef");
4838 if (!parser_next(parser)) {
4839 parseerror(parser, "parse error after typedef");
4846 static const char *cvq_to_str(int cvq) {
4848 case CV_NONE: return "none";
4849 case CV_VAR: return "`var`";
4850 case CV_CONST: return "`const`";
4851 default: return "<INVALID>";
4855 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4858 if (proto->cvq != var->cvq) {
4859 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4860 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4861 parser->tok == '='))
4863 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4864 "`%s` declared with different qualifiers: %s\n"
4865 " -> previous declaration here: %s:%i uses %s",
4866 var->name, cvq_to_str(var->cvq),
4867 ast_ctx(proto).file, ast_ctx(proto).line,
4868 cvq_to_str(proto->cvq));
4871 av = (var ->expression.flags & AST_FLAG_NORETURN);
4872 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4874 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4875 "`%s` declared with different attributes%s\n"
4876 " -> previous declaration here: %s:%i",
4877 var->name, (av ? ": noreturn" : ""),
4878 ast_ctx(proto).file, ast_ctx(proto).line,
4879 (ao ? ": noreturn" : ""));
4884 static bool create_array_accessors(parser_t *parser, ast_value *var)
4887 util_snprintf(name, sizeof(name), "%s##SET", var->name);
4888 if (!parser_create_array_setter(parser, var, name))
4890 util_snprintf(name, sizeof(name), "%s##GET", var->name);
4891 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4896 static bool parse_array(parser_t *parser, ast_value *array)
4899 if (array->initlist) {
4900 parseerror(parser, "array already initialized elsewhere");
4903 if (!parser_next(parser)) {
4904 parseerror(parser, "parse error in array initializer");
4908 while (parser->tok != '}') {
4909 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
4912 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
4914 parseerror(parser, "initializing element must be a compile time constant");
4917 vec_push(array->initlist, v->constval);
4918 if (v->expression.vtype == TYPE_STRING) {
4919 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
4923 if (parser->tok == '}')
4925 if (parser->tok != ',' || !parser_next(parser)) {
4926 parseerror(parser, "expected comma or '}' in element list");
4930 if (!parser_next(parser) || parser->tok != ';') {
4931 parseerror(parser, "expected semicolon after initializer, got %s");
4935 if (!parser_next(parser)) {
4936 parseerror(parser, "parse error after initializer");
4941 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
4942 if (array->expression.count != (size_t)-1) {
4943 parseerror(parser, "array `%s' has already been initialized with %u elements",
4944 array->name, (unsigned)array->expression.count);
4946 array->expression.count = vec_size(array->initlist);
4947 if (!create_array_accessors(parser, array))
4953 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)
4957 ast_expression *old;
4961 ast_value *basetype = NULL;
4963 bool isparam = false;
4964 bool isvector = false;
4965 bool cleanvar = true;
4966 bool wasarray = false;
4968 ast_member *me[3] = { NULL, NULL, NULL };
4970 if (!localblock && is_static)
4971 parseerror(parser, "`static` qualifier is not supported in global scope");
4973 /* get the first complete variable */
4974 var = parse_typename(parser, &basetype, cached_typedef);
4977 ast_delete(basetype);
4985 /* Part 0: finish the type */
4986 if (parser->tok == '(') {
4987 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4988 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4989 var = parse_parameter_list(parser, var);
4995 /* we only allow 1-dimensional arrays */
4996 if (parser->tok == '[') {
4998 var = parse_arraysize(parser, var);
5004 if (parser->tok == '(' && wasarray) {
5005 parseerror(parser, "arrays as part of a return type is not supported");
5006 /* we'll still parse the type completely for now */
5008 /* for functions returning functions */
5009 while (parser->tok == '(') {
5010 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5011 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5012 var = parse_parameter_list(parser, var);
5019 var->cvq = qualifier;
5020 var->expression.flags |= qflags;
5023 * store the vstring back to var for alias and
5024 * deprecation messages.
5026 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5027 var->expression.flags & AST_FLAG_ALIAS)
5028 var->desc = vstring;
5031 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5032 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5033 * is then filled with the previous definition and the parameter-names replaced.
5035 if (!strcmp(var->name, "nil")) {
5036 if (OPTS_FLAG(UNTYPED_NIL)) {
5037 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5038 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5040 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5043 /* Deal with end_sys_ vars */
5045 if (!strcmp(var->name, "end_sys_globals")) {
5047 parser->crc_globals = vec_size(parser->globals);
5050 else if (!strcmp(var->name, "end_sys_fields")) {
5052 parser->crc_fields = vec_size(parser->fields);
5055 if (was_end && var->expression.vtype == TYPE_FIELD) {
5056 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5057 "global '%s' hint should not be a field",
5058 parser_tokval(parser)))
5065 if (!nofields && var->expression.vtype == TYPE_FIELD)
5067 /* deal with field declarations */
5068 old = parser_find_field(parser, var->name);
5070 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5071 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5080 parseerror(parser, "field `%s` already declared here: %s:%i",
5081 var->name, ast_ctx(old).file, ast_ctx(old).line);
5086 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5087 (old = parser_find_global(parser, var->name)))
5089 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5090 parseerror(parser, "field `%s` already declared here: %s:%i",
5091 var->name, ast_ctx(old).file, ast_ctx(old).line);
5098 /* deal with other globals */
5099 old = parser_find_global(parser, var->name);
5100 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5102 /* This is a function which had a prototype */
5103 if (!ast_istype(old, ast_value)) {
5104 parseerror(parser, "internal error: prototype is not an ast_value");
5108 proto = (ast_value*)old;
5109 proto->desc = var->desc;
5110 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5111 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5113 ast_ctx(proto).file, ast_ctx(proto).line);
5117 /* we need the new parameter-names */
5118 for (i = 0; i < vec_size(proto->expression.params); ++i)
5119 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5120 if (!parser_check_qualifiers(parser, var, proto)) {
5127 proto->expression.flags |= var->expression.flags;
5135 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5136 "global `%s` already declared here: %s:%i",
5137 var->name, ast_ctx(old).file, ast_ctx(old).line))
5142 proto = (ast_value*)old;
5143 if (!ast_istype(old, ast_value)) {
5144 parseerror(parser, "internal error: not an ast_value");
5149 if (!parser_check_qualifiers(parser, var, proto)) {
5154 proto->expression.flags |= var->expression.flags;
5158 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5159 (old = parser_find_field(parser, var->name)))
5161 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5162 parseerror(parser, "global `%s` already declared here: %s:%i",
5163 var->name, ast_ctx(old).file, ast_ctx(old).line);
5170 else /* it's not a global */
5172 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5173 if (old && !isparam) {
5174 parseerror(parser, "local `%s` already declared here: %s:%i",
5175 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5179 old = parser_find_local(parser, var->name, 0, &isparam);
5180 if (old && isparam) {
5181 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5182 "local `%s` is shadowing a parameter", var->name))
5184 parseerror(parser, "local `%s` already declared here: %s:%i",
5185 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5189 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5197 /* in a noref section we simply bump the usecount */
5198 if (noref || parser->noref)
5202 * Create the global/local, and deal with vector types.
5205 if (var->expression.vtype == TYPE_VECTOR)
5207 else if (var->expression.vtype == TYPE_FIELD &&
5208 var->expression.next->vtype == TYPE_VECTOR)
5212 if (!create_vector_members(var, me)) {
5219 /* deal with global variables, fields, functions */
5220 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5221 var->isfield = true;
5222 vec_push(parser->fields, (ast_expression*)var);
5223 util_htset(parser->htfields, var->name, var);
5225 for (i = 0; i < 3; ++i) {
5226 vec_push(parser->fields, (ast_expression*)me[i]);
5227 util_htset(parser->htfields, me[i]->name, me[i]);
5232 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5233 parser_addglobal(parser, var->name, (ast_expression*)var);
5235 for (i = 0; i < 3; ++i) {
5236 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5240 ast_expression *find = parser_find_global(parser, var->desc);
5243 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5247 if (var->expression.vtype != find->vtype) {
5251 ast_type_to_string(find, ty1, sizeof(ty1));
5252 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5254 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5261 * add alias to aliases table and to corrector
5262 * so corrections can apply for aliases as well.
5264 util_htset(parser->aliases, var->name, find);
5267 * add to corrector so corrections can work
5268 * even for aliases too.
5271 vec_last(parser->correct_variables),
5272 &vec_last(parser->correct_variables_score),
5276 /* generate aliases for vector components */
5280 util_asprintf(&buffer[0], "%s_x", var->desc);
5281 util_asprintf(&buffer[1], "%s_y", var->desc);
5282 util_asprintf(&buffer[2], "%s_z", var->desc);
5284 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5285 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5286 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5293 * add to corrector so corrections can work
5294 * even for aliases too.
5297 vec_last(parser->correct_variables),
5298 &vec_last(parser->correct_variables_score),
5302 vec_last(parser->correct_variables),
5303 &vec_last(parser->correct_variables_score),
5307 vec_last(parser->correct_variables),
5308 &vec_last(parser->correct_variables_score),
5316 /* a static adds itself to be generated like any other global
5317 * but is added to the local namespace instead
5319 char *defname = NULL;
5320 size_t prefix_len, ln;
5322 ln = strlen(parser->function->name);
5323 vec_append(defname, ln, parser->function->name);
5325 vec_append(defname, 2, "::");
5326 /* remember the length up to here */
5327 prefix_len = vec_size(defname);
5329 /* Add it to the local scope */
5330 util_htset(vec_last(parser->variables), var->name, (void*)var);
5334 vec_last(parser->correct_variables),
5335 &vec_last(parser->correct_variables_score),
5339 /* now rename the global */
5340 ln = strlen(var->name);
5341 vec_append(defname, ln, var->name);
5342 ast_value_set_name(var, defname);
5344 /* push it to the to-be-generated globals */
5345 vec_push(parser->globals, (ast_expression*)var);
5347 /* same game for the vector members */
5349 for (i = 0; i < 3; ++i) {
5350 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5354 vec_last(parser->correct_variables),
5355 &vec_last(parser->correct_variables_score),
5359 vec_shrinkto(defname, prefix_len);
5360 ln = strlen(me[i]->name);
5361 vec_append(defname, ln, me[i]->name);
5362 ast_member_set_name(me[i], defname);
5364 vec_push(parser->globals, (ast_expression*)me[i]);
5369 vec_push(localblock->locals, var);
5370 parser_addlocal(parser, var->name, (ast_expression*)var);
5372 for (i = 0; i < 3; ++i) {
5373 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5374 ast_block_collect(localblock, (ast_expression*)me[i]);
5380 me[0] = me[1] = me[2] = NULL;
5385 if (var->expression.vtype == TYPE_ARRAY) {
5386 if (var->expression.count != (size_t)-1) {
5387 if (!create_array_accessors(parser, var))
5391 else if (!localblock && !nofields &&
5392 var->expression.vtype == TYPE_FIELD &&
5393 var->expression.next->vtype == TYPE_ARRAY)
5396 ast_expression *telem;
5398 ast_value *array = (ast_value*)var->expression.next;
5400 if (!ast_istype(var->expression.next, ast_value)) {
5401 parseerror(parser, "internal error: field element type must be an ast_value");
5405 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5406 if (!parser_create_array_field_setter(parser, array, name))
5409 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5410 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5411 tfield->expression.next = telem;
5412 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5413 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5421 if (parser->tok == ';') {
5422 ast_delete(basetype);
5423 if (!parser_next(parser)) {
5424 parseerror(parser, "error after variable declaration");
5430 if (parser->tok == ',')
5434 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5437 parseerror(parser, "missing comma or semicolon while parsing variables");
5441 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5442 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5443 "initializing expression turns variable `%s` into a constant in this standard",
5450 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5451 if (parser->tok != '=') {
5452 if (!strcmp(parser_tokval(parser), "break")) {
5453 if (!parser_next(parser)) {
5454 parseerror(parser, "error parsing break definition");
5457 (void)!!parsewarning(parser, WARN_BREAKDEF, "break definition ignored (suggest removing it)");
5459 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5464 if (!parser_next(parser)) {
5465 parseerror(parser, "error parsing initializer");
5469 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5470 parseerror(parser, "expected '=' before function body in this standard");
5473 if (parser->tok == '#') {
5474 ast_function *func = NULL;
5475 ast_value *number = NULL;
5481 parseerror(parser, "cannot declare builtins within functions");
5484 if (var->expression.vtype != TYPE_FUNCTION) {
5485 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5488 if (!parser_next(parser)) {
5489 parseerror(parser, "expected builtin number");
5493 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5494 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5496 parseerror(parser, "builtin number expected");
5499 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5502 parseerror(parser, "builtin number must be a compile time constant");
5505 if (number->expression.vtype == TYPE_INTEGER)
5506 builtin_num = number->constval.vint;
5507 else if (number->expression.vtype == TYPE_FLOAT)
5508 builtin_num = number->constval.vfloat;
5511 parseerror(parser, "builtin number must be an integer constant");
5516 fractional = modff(builtin_num, &integral);
5517 if (builtin_num < 0 || fractional != 0) {
5518 parseerror(parser, "builtin number must be an integer greater than zero");
5522 /* we only want the integral part anyways */
5523 builtin_num = integral;
5524 } else if (parser->tok == TOKEN_INTCONST) {
5525 builtin_num = parser_token(parser)->constval.i;
5527 parseerror(parser, "builtin number must be a compile time constant");
5531 if (var->hasvalue) {
5532 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5533 "builtin `%s` has already been defined\n"
5534 " -> previous declaration here: %s:%i",
5535 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5539 func = ast_function_new(ast_ctx(var), var->name, var);
5541 parseerror(parser, "failed to allocate function for `%s`", var->name);
5544 vec_push(parser->functions, func);
5546 func->builtin = -builtin_num-1;
5549 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5550 ? (parser->tok != ',' && parser->tok != ';')
5551 : (!parser_next(parser)))
5553 parseerror(parser, "expected comma or semicolon");
5555 ast_function_delete(func);
5556 var->constval.vfunc = NULL;
5560 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5563 /* Note that fteqcc and most others don't even *have*
5564 * local arrays, so this is not a high priority.
5566 parseerror(parser, "TODO: initializers for local arrays");
5570 var->hasvalue = true;
5571 if (!parse_array(parser, var))
5574 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5577 parseerror(parser, "cannot declare functions within functions");
5582 ast_ctx(proto) = parser_ctx(parser);
5584 if (!parse_function_body(parser, var))
5586 ast_delete(basetype);
5587 for (i = 0; i < vec_size(parser->gotos); ++i)
5588 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5589 vec_free(parser->gotos);
5590 vec_free(parser->labels);
5593 ast_expression *cexp;
5596 cexp = parse_expression_leave(parser, true, false, false);
5601 cval = (ast_value*)cexp;
5602 if (cval != parser->nil &&
5603 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5606 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5610 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5611 qualifier != CV_VAR)
5613 var->cvq = CV_CONST;
5615 if (cval == parser->nil)
5616 var->expression.flags |= AST_FLAG_INITIALIZED;
5619 var->hasvalue = true;
5620 if (cval->expression.vtype == TYPE_STRING)
5621 var->constval.vstring = parser_strdup(cval->constval.vstring);
5622 else if (cval->expression.vtype == TYPE_FIELD)
5623 var->constval.vfield = cval;
5625 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5631 shunt sy = { NULL, NULL, NULL, NULL };
5634 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5635 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5636 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5637 if (!parser_sy_apply_operator(parser, &sy))
5640 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5641 parseerror(parser, "internal error: leaked operands");
5642 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5653 if (parser->tok == ',') {
5654 if (!parser_next(parser)) {
5655 parseerror(parser, "expected another variable");
5659 if (parser->tok != TOKEN_IDENT) {
5660 parseerror(parser, "expected another variable");
5663 var = ast_value_copy(basetype);
5665 ast_value_set_name(var, parser_tokval(parser));
5666 if (!parser_next(parser)) {
5667 parseerror(parser, "error parsing variable declaration");
5673 if (parser->tok != ';') {
5674 parseerror(parser, "missing semicolon after variables");
5678 if (!parser_next(parser)) {
5679 parseerror(parser, "parse error after variable declaration");
5683 ast_delete(basetype);
5687 if (cleanvar && var)
5689 ast_delete(basetype);
5693 ast_delete(basetype);
5694 if (cleanvar && var)
5696 if (me[0]) ast_member_delete(me[0]);
5697 if (me[1]) ast_member_delete(me[1]);
5698 if (me[2]) ast_member_delete(me[2]);
5702 static bool parser_global_statement(parser_t *parser)
5706 bool is_static = false;
5707 uint32_t qflags = 0;
5708 ast_value *istype = NULL;
5709 char *vstring = NULL;
5711 if (parser->tok == TOKEN_IDENT)
5712 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5714 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5716 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5718 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5720 if (cvq == CV_WRONG)
5722 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5724 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5726 return parse_enum(parser);
5728 else if (parser->tok == TOKEN_KEYWORD)
5730 if (!strcmp(parser_tokval(parser), "typedef")) {
5731 if (!parser_next(parser)) {
5732 parseerror(parser, "expected type definition after 'typedef'");
5735 return parse_typedef(parser);
5737 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5740 else if (parser->tok == '#')
5742 return parse_pragma(parser);
5744 else if (parser->tok == '$')
5746 if (!parser_next(parser)) {
5747 parseerror(parser, "parse error");
5753 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5759 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5761 return util_crc16(old, str, strlen(str));
5764 static void progdefs_crc_file(const char *str)
5766 /* write to progdefs.h here */
5770 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5772 old = progdefs_crc_sum(old, str);
5773 progdefs_crc_file(str);
5777 static void generate_checksum(parser_t *parser, ir_builder *ir)
5779 uint16_t crc = 0xFFFF;
5783 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5784 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5786 progdefs_crc_file("\tint\tpad;\n");
5787 progdefs_crc_file("\tint\tofs_return[3];\n");
5788 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5789 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5790 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5791 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5792 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5793 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5794 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5795 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5797 for (i = 0; i < parser->crc_globals; ++i) {
5798 if (!ast_istype(parser->globals[i], ast_value))
5800 value = (ast_value*)(parser->globals[i]);
5801 switch (value->expression.vtype) {
5802 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5803 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5804 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5805 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5807 crc = progdefs_crc_both(crc, "\tint\t");
5810 crc = progdefs_crc_both(crc, value->name);
5811 crc = progdefs_crc_both(crc, ";\n");
5813 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5814 for (i = 0; i < parser->crc_fields; ++i) {
5815 if (!ast_istype(parser->fields[i], ast_value))
5817 value = (ast_value*)(parser->fields[i]);
5818 switch (value->expression.next->vtype) {
5819 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5820 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5821 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5822 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5824 crc = progdefs_crc_both(crc, "\tint\t");
5827 crc = progdefs_crc_both(crc, value->name);
5828 crc = progdefs_crc_both(crc, ";\n");
5830 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5831 ir->code->crc = crc;
5834 parser_t *parser_create()
5837 lex_ctx_t empty_ctx;
5840 parser = (parser_t*)mem_a(sizeof(parser_t));
5844 memset(parser, 0, sizeof(*parser));
5846 for (i = 0; i < operator_count; ++i) {
5847 if (operators[i].id == opid1('=')) {
5848 parser->assign_op = operators+i;
5852 if (!parser->assign_op) {
5853 printf("internal error: initializing parser: failed to find assign operator\n");
5858 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5859 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5860 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5861 vec_push(parser->_blocktypedefs, 0);
5863 parser->aliases = util_htnew(PARSER_HT_SIZE);
5866 vec_push(parser->correct_variables, correct_trie_new());
5867 vec_push(parser->correct_variables_score, NULL);
5869 empty_ctx.file = "<internal>";
5871 empty_ctx.column = 0;
5872 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5873 parser->nil->cvq = CV_CONST;
5874 if (OPTS_FLAG(UNTYPED_NIL))
5875 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5877 parser->max_param_count = 1;
5879 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5880 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5881 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5883 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5884 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5885 parser->reserved_version->cvq = CV_CONST;
5886 parser->reserved_version->hasvalue = true;
5887 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5888 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5890 parser->reserved_version = NULL;
5893 parser->fold = fold_init(parser);
5897 static bool parser_compile(parser_t *parser)
5899 /* initial lexer/parser state */
5900 parser->lex->flags.noops = true;
5902 if (parser_next(parser))
5904 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5906 if (!parser_global_statement(parser)) {
5907 if (parser->tok == TOKEN_EOF)
5908 parseerror(parser, "unexpected end of file");
5909 else if (compile_errors)
5910 parseerror(parser, "there have been errors, bailing out");
5911 lex_close(parser->lex);
5917 parseerror(parser, "parse error");
5918 lex_close(parser->lex);
5923 lex_close(parser->lex);
5926 return !compile_errors;
5929 bool parser_compile_file(parser_t *parser, const char *filename)
5931 parser->lex = lex_open(filename);
5933 con_err("failed to open file \"%s\"\n", filename);
5936 return parser_compile(parser);
5939 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
5941 parser->lex = lex_open_string(str, len, name);
5943 con_err("failed to create lexer for string \"%s\"\n", name);
5946 return parser_compile(parser);
5949 static void parser_remove_ast(parser_t *parser)
5952 if (parser->ast_cleaned)
5954 parser->ast_cleaned = true;
5955 for (i = 0; i < vec_size(parser->accessors); ++i) {
5956 ast_delete(parser->accessors[i]->constval.vfunc);
5957 parser->accessors[i]->constval.vfunc = NULL;
5958 ast_delete(parser->accessors[i]);
5960 for (i = 0; i < vec_size(parser->functions); ++i) {
5961 ast_delete(parser->functions[i]);
5963 for (i = 0; i < vec_size(parser->fields); ++i) {
5964 ast_delete(parser->fields[i]);
5966 for (i = 0; i < vec_size(parser->globals); ++i) {
5967 ast_delete(parser->globals[i]);
5969 vec_free(parser->accessors);
5970 vec_free(parser->functions);
5971 vec_free(parser->globals);
5972 vec_free(parser->fields);
5974 for (i = 0; i < vec_size(parser->variables); ++i)
5975 util_htdel(parser->variables[i]);
5976 vec_free(parser->variables);
5977 vec_free(parser->_blocklocals);
5978 vec_free(parser->_locals);
5981 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5982 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5984 vec_free(parser->correct_variables);
5985 vec_free(parser->correct_variables_score);
5987 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5988 ast_delete(parser->_typedefs[i]);
5989 vec_free(parser->_typedefs);
5990 for (i = 0; i < vec_size(parser->typedefs); ++i)
5991 util_htdel(parser->typedefs[i]);
5992 vec_free(parser->typedefs);
5993 vec_free(parser->_blocktypedefs);
5995 vec_free(parser->_block_ctx);
5997 vec_free(parser->labels);
5998 vec_free(parser->gotos);
5999 vec_free(parser->breaks);
6000 vec_free(parser->continues);
6002 ast_value_delete(parser->nil);
6004 ast_value_delete(parser->const_vec[0]);
6005 ast_value_delete(parser->const_vec[1]);
6006 ast_value_delete(parser->const_vec[2]);
6008 if (parser->reserved_version)
6009 ast_value_delete(parser->reserved_version);
6011 util_htdel(parser->aliases);
6012 intrin_intrinsics_destroy(parser);
6013 fold_cleanup(parser->fold);
6016 void parser_cleanup(parser_t *parser)
6018 parser_remove_ast(parser);
6022 bool parser_finish(parser_t *parser, const char *output)
6028 if (compile_errors) {
6029 con_out("*** there were compile errors\n");
6033 ir = ir_builder_new("gmqcc_out");
6035 con_out("failed to allocate builder\n");
6039 for (i = 0; i < vec_size(parser->fields); ++i) {
6042 if (!ast_istype(parser->fields[i], ast_value))
6044 field = (ast_value*)parser->fields[i];
6045 hasvalue = field->hasvalue;
6046 field->hasvalue = false;
6047 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6048 con_out("failed to generate field %s\n", field->name);
6049 ir_builder_delete(ir);
6054 ast_expression *subtype;
6055 field->hasvalue = true;
6056 subtype = field->expression.next;
6057 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6058 if (subtype->vtype == TYPE_FIELD)
6059 ifld->fieldtype = subtype->next->vtype;
6060 else if (subtype->vtype == TYPE_FUNCTION)
6061 ifld->outtype = subtype->next->vtype;
6062 (void)!ir_value_set_field(field->ir_v, ifld);
6065 for (i = 0; i < vec_size(parser->globals); ++i) {
6067 if (!ast_istype(parser->globals[i], ast_value))
6069 asvalue = (ast_value*)(parser->globals[i]);
6070 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6071 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6072 "unused global: `%s`", asvalue->name);
6074 if (!ast_global_codegen(asvalue, ir, false)) {
6075 con_out("failed to generate global %s\n", asvalue->name);
6076 ir_builder_delete(ir);
6080 /* Build function vararg accessor ast tree now before generating
6081 * immediates, because the accessors may add new immediates
6083 for (i = 0; i < vec_size(parser->functions); ++i) {
6084 ast_function *f = parser->functions[i];
6086 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6087 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6088 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6089 con_out("failed to generate vararg setter for %s\n", f->name);
6090 ir_builder_delete(ir);
6093 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6094 con_out("failed to generate vararg getter for %s\n", f->name);
6095 ir_builder_delete(ir);
6099 ast_delete(f->varargs);
6104 /* Now we can generate immediates */
6105 if (!fold_generate(parser->fold, ir))
6108 for (i = 0; i < vec_size(parser->globals); ++i) {
6110 if (!ast_istype(parser->globals[i], ast_value))
6112 asvalue = (ast_value*)(parser->globals[i]);
6113 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6115 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6116 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6117 "uninitialized constant: `%s`",
6119 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6120 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6121 "uninitialized global: `%s`",
6124 if (!ast_generate_accessors(asvalue, ir)) {
6125 ir_builder_delete(ir);
6129 for (i = 0; i < vec_size(parser->fields); ++i) {
6131 asvalue = (ast_value*)(parser->fields[i]->next);
6133 if (!ast_istype((ast_expression*)asvalue, ast_value))
6135 if (asvalue->expression.vtype != TYPE_ARRAY)
6137 if (!ast_generate_accessors(asvalue, ir)) {
6138 ir_builder_delete(ir);
6142 if (parser->reserved_version &&
6143 !ast_global_codegen(parser->reserved_version, ir, false))
6145 con_out("failed to generate reserved::version");
6146 ir_builder_delete(ir);
6149 for (i = 0; i < vec_size(parser->functions); ++i) {
6150 ast_function *f = parser->functions[i];
6151 if (!ast_function_codegen(f, ir)) {
6152 con_out("failed to generate function %s\n", f->name);
6153 ir_builder_delete(ir);
6158 generate_checksum(parser, ir);
6160 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6161 ir_builder_dump(ir, con_out);
6162 for (i = 0; i < vec_size(parser->functions); ++i) {
6163 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6164 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6165 ir_builder_delete(ir);
6169 parser_remove_ast(parser);
6171 if (compile_Werrors) {
6172 con_out("*** there were warnings treated as errors\n");
6173 compile_show_werrors();
6178 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6179 ir_builder_dump(ir, con_out);
6181 if (!ir_builder_generate(ir, output)) {
6182 con_out("*** failed to generate output file\n");
6183 ir_builder_delete(ir);
6187 ir_builder_delete(ir);