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
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 128
35 #define TYPEDEF_HT_SIZE 16
41 ast_expression **globals;
42 ast_expression **fields;
43 ast_function **functions;
44 ast_value **imm_float;
45 ast_value **imm_string;
46 ast_value **imm_vector;
49 /* must be deleted first, they reference immediates and values */
50 ast_value **accessors;
52 ast_value *imm_float_zero;
53 ast_value *imm_float_one;
54 ast_value *imm_vector_zero;
56 ast_value *reserved_version;
61 ast_function *function;
63 /* All the labels the function defined...
64 * Should they be in ast_function instead?
69 const char **continues;
71 /* A list of hashtables for each scope */
77 /* same as above but for the spelling corrector */
78 correct_trie_t **correct_variables;
79 size_t ***correct_variables_score; /* vector of vector of size_t* */
81 /* not to be used directly, we use the hash table */
82 ast_expression **_locals;
84 ast_value **_typedefs;
85 size_t *_blocktypedefs;
88 /* we store the '=' operator info */
89 const oper_info *assign_op;
92 ast_value *const_vec[3];
97 /* collected information */
98 size_t max_param_count;
101 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
103 static void parser_enterblock(parser_t *parser);
104 static bool parser_leaveblock(parser_t *parser);
105 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
106 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
107 static bool parse_typedef(parser_t *parser);
108 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);
109 static ast_block* parse_block(parser_t *parser);
110 static bool parse_block_into(parser_t *parser, ast_block *block);
111 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
112 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
113 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
114 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
115 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
116 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
117 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
119 static void parseerror(parser_t *parser, const char *fmt, ...)
123 vcompile_error(parser->lex->tok.ctx, fmt, ap);
127 /* returns true if it counts as an error */
128 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
133 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
138 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
143 r = vcompile_warning(ctx, warntype, fmt, ap);
148 /**********************************************************************
149 * some maths used for constant folding
152 vector vec3_add(vector a, vector b)
161 vector vec3_sub(vector a, vector b)
170 qcfloat vec3_mulvv(vector a, vector b)
172 return (a.x * b.x + a.y * b.y + a.z * b.z);
175 vector vec3_mulvf(vector a, float b)
184 /**********************************************************************
188 bool parser_next(parser_t *parser)
190 /* lex_do kills the previous token */
191 parser->tok = lex_do(parser->lex);
192 if (parser->tok == TOKEN_EOF)
194 if (parser->tok >= TOKEN_ERROR) {
195 parseerror(parser, "lex error");
201 #define parser_tokval(p) ((p)->lex->tok.value)
202 #define parser_token(p) (&((p)->lex->tok))
203 #define parser_ctx(p) ((p)->lex->tok.ctx)
205 static ast_value* parser_const_float(parser_t *parser, double d)
210 for (i = 0; i < vec_size(parser->imm_float); ++i) {
211 const double compare = parser->imm_float[i]->constval.vfloat;
212 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
213 return parser->imm_float[i];
216 ctx = parser_ctx(parser);
218 memset(&ctx, 0, sizeof(ctx));
220 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
222 out->hasvalue = true;
223 out->constval.vfloat = d;
224 vec_push(parser->imm_float, out);
228 static ast_value* parser_const_float_0(parser_t *parser)
230 if (!parser->imm_float_zero)
231 parser->imm_float_zero = parser_const_float(parser, 0);
232 return parser->imm_float_zero;
235 static ast_value* parser_const_float_1(parser_t *parser)
237 if (!parser->imm_float_one)
238 parser->imm_float_one = parser_const_float(parser, 1);
239 return parser->imm_float_one;
242 static char *parser_strdup(const char *str)
245 /* actually dup empty strings */
246 char *out = (char*)mem_a(1);
250 return util_strdup(str);
253 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
257 for (i = 0; i < vec_size(parser->imm_string); ++i) {
258 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
259 return parser->imm_string[i];
263 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
264 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
266 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
268 out->hasvalue = true;
269 out->constval.vstring = parser_strdup(str);
270 vec_push(parser->imm_string, out);
274 static ast_value* parser_const_vector(parser_t *parser, vector v)
278 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
279 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
280 return parser->imm_vector[i];
282 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
284 out->hasvalue = true;
285 out->constval.vvec = v;
286 vec_push(parser->imm_vector, out);
290 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
296 return parser_const_vector(parser, v);
299 static ast_value* parser_const_vector_0(parser_t *parser)
301 if (!parser->imm_vector_zero)
302 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
303 return parser->imm_vector_zero;
306 static ast_expression* parser_find_field(parser_t *parser, const char *name)
308 return ( ast_expression*)util_htget(parser->htfields, name);
311 static ast_expression* parser_find_label(parser_t *parser, const char *name)
314 for(i = 0; i < vec_size(parser->labels); i++)
315 if (!strcmp(parser->labels[i]->name, name))
316 return (ast_expression*)parser->labels[i];
320 static ast_expression* parser_find_global(parser_t *parser, const char *name)
322 return (ast_expression*)util_htget(parser->htglobals, name);
325 static ast_expression* parser_find_param(parser_t *parser, const char *name)
329 if (!parser->function)
331 fun = parser->function->vtype;
332 for (i = 0; i < vec_size(fun->expression.params); ++i) {
333 if (!strcmp(fun->expression.params[i]->name, name))
334 return (ast_expression*)(fun->expression.params[i]);
339 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
344 hash = util_hthash(parser->htglobals, name);
347 for (i = vec_size(parser->variables); i > upto;) {
349 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
353 return parser_find_param(parser, name);
356 static ast_expression* parser_find_var(parser_t *parser, const char *name)
360 v = parser_find_local(parser, name, 0, &dummy);
361 if (!v) v = parser_find_global(parser, name);
365 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
369 hash = util_hthash(parser->typedefs[0], name);
371 for (i = vec_size(parser->typedefs); i > upto;) {
373 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
381 size_t etype; /* 0 = expression, others are operators */
385 ast_block *block; /* for commas and function calls */
404 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
415 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
419 e.out = (ast_expression*)v;
426 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
428 e.etype = 1 + (op - operators);
437 static sy_elem syparen(lex_ctx ctx, size_t off) {
448 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
449 * so we need to rotate it to become ent.(foo[n]).
451 static bool rotate_entfield_array_index_nodes(ast_expression **out)
453 ast_array_index *index;
454 ast_entfield *entfield;
458 ast_expression *entity;
460 lex_ctx ctx = ast_ctx(*out);
462 if (!ast_istype(*out, ast_array_index))
464 index = (ast_array_index*)*out;
466 if (!ast_istype(index->array, ast_entfield))
468 entfield = (ast_entfield*)index->array;
470 if (!ast_istype(entfield->field, ast_value))
472 field = (ast_value*)entfield->field;
475 entity = entfield->entity;
479 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
480 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
481 *out = (ast_expression*)entfield;
486 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
488 switch (v->expression.vtype) {
490 return !!v->constval.vfloat;
492 return !!v->constval.vint;
494 if (OPTS_FLAG(CORRECT_LOGIC))
495 return v->constval.vvec.x &&
496 v->constval.vvec.y &&
499 return !!(v->constval.vvec.x);
501 if (!v->constval.vstring)
503 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
505 return !!v->constval.vstring[0];
507 compile_error(ctx, "internal error: immediate_is_true on invalid type");
508 return !!v->constval.vfunc;
512 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
516 ast_expression *out = NULL;
517 ast_expression *exprs[3];
518 ast_block *blocks[3];
519 ast_value *asvalue[3];
520 ast_binstore *asbinstore;
521 size_t i, assignop, addop, subop;
522 qcint generated_op = 0;
527 if (!vec_size(sy->ops)) {
528 parseerror(parser, "internal error: missing operator");
532 if (vec_last(sy->ops).isparen) {
533 parseerror(parser, "unmatched parenthesis");
537 op = &operators[vec_last(sy->ops).etype - 1];
538 ctx = vec_last(sy->ops).ctx;
540 if (vec_size(sy->out) < op->operands) {
541 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
542 op->op, (int)op->id);
546 vec_shrinkby(sy->ops, 1);
548 /* op(:?) has no input and no output */
552 vec_shrinkby(sy->out, op->operands);
553 for (i = 0; i < op->operands; ++i) {
554 exprs[i] = sy->out[vec_size(sy->out)+i].out;
555 blocks[i] = sy->out[vec_size(sy->out)+i].block;
556 asvalue[i] = (ast_value*)exprs[i];
558 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
559 !(i != 0 && op->id == opid2('?',':')) &&
560 !(i == 1 && op->id == opid1('.')))
562 if (ast_istype(exprs[i], ast_label))
563 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
565 compile_error(ast_ctx(exprs[i]), "not an expression");
566 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
570 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
571 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
575 #define NotSameType(T) \
576 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
577 exprs[0]->expression.vtype != T)
578 #define CanConstFold1(A) \
579 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
580 (A)->expression.vtype != TYPE_FUNCTION)
581 #define CanConstFold(A, B) \
582 (CanConstFold1(A) && CanConstFold1(B))
583 #define ConstV(i) (asvalue[(i)]->constval.vvec)
584 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
585 #define ConstS(i) (asvalue[(i)]->constval.vstring)
589 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
593 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
594 exprs[1]->expression.vtype == TYPE_NOEXPR)
596 if (exprs[1] == (ast_expression*)parser->const_vec[0])
597 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
598 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
599 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
600 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
601 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
603 compile_error(ctx, "access to invalid vector component");
607 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
608 if (exprs[1]->expression.vtype != TYPE_FIELD) {
609 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
612 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
614 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
615 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
619 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
625 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
626 !(exprs[0]->expression.vtype == TYPE_FIELD &&
627 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
629 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
630 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
633 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
634 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
635 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
638 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
639 if (rotate_entfield_array_index_nodes(&out))
642 /* This is not broken in fteqcc anymore */
643 if (opts.standard != COMPILER_GMQCC) {
644 /* this error doesn't need to make us bail out */
645 (void)!parsewarning(parser, WARN_EXTENSIONS,
646 "accessing array-field members of an entity without parenthesis\n"
647 " -> this is an extension from -std=gmqcc");
654 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
655 vec_push(sy->out, syexp(ctx, exprs[0]));
656 vec_push(sy->out, syexp(ctx, exprs[1]));
657 vec_last(sy->argc)++;
661 if (!ast_block_add_expr(blocks[0], exprs[1]))
664 blocks[0] = ast_block_new(ctx);
665 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
666 !ast_block_add_expr(blocks[0], exprs[1]))
671 if (!ast_block_set_type(blocks[0], exprs[1]))
674 vec_push(sy->out, syblock(ctx, blocks[0]));
681 switch (exprs[0]->expression.vtype) {
683 if (CanConstFold1(exprs[0]))
684 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
686 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
687 (ast_expression*)parser_const_float_0(parser),
691 if (CanConstFold1(exprs[0]))
692 out = (ast_expression*)parser_const_vector_f(parser,
693 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
695 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
696 (ast_expression*)parser_const_vector_0(parser),
700 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
701 type_name[exprs[0]->expression.vtype]);
707 switch (exprs[0]->expression.vtype) {
709 if (CanConstFold1(exprs[0]))
710 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
712 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
715 if (CanConstFold1(exprs[0]))
716 out = (ast_expression*)parser_const_float(parser,
717 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
719 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
722 if (CanConstFold1(exprs[0])) {
723 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
724 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
726 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
728 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
729 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
731 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
734 /* we don't constant-fold NOT for these types */
736 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
739 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
742 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
743 type_name[exprs[0]->expression.vtype]);
749 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
750 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
752 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
753 type_name[exprs[0]->expression.vtype],
754 type_name[exprs[1]->expression.vtype]);
757 switch (exprs[0]->expression.vtype) {
759 if (CanConstFold(exprs[0], exprs[1]))
761 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
764 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
767 if (CanConstFold(exprs[0], exprs[1]))
768 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
770 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
773 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
774 type_name[exprs[0]->expression.vtype],
775 type_name[exprs[1]->expression.vtype]);
780 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
781 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
783 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
784 type_name[exprs[1]->expression.vtype],
785 type_name[exprs[0]->expression.vtype]);
788 switch (exprs[0]->expression.vtype) {
790 if (CanConstFold(exprs[0], exprs[1]))
791 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
793 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
796 if (CanConstFold(exprs[0], exprs[1]))
797 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
799 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
802 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
803 type_name[exprs[1]->expression.vtype],
804 type_name[exprs[0]->expression.vtype]);
809 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
810 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
811 exprs[1]->expression.vtype == TYPE_FLOAT) &&
812 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
813 exprs[0]->expression.vtype == TYPE_FLOAT)
816 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
817 type_name[exprs[1]->expression.vtype],
818 type_name[exprs[0]->expression.vtype]);
821 switch (exprs[0]->expression.vtype) {
823 if (exprs[1]->expression.vtype == TYPE_VECTOR)
825 if (CanConstFold(exprs[0], exprs[1]))
826 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
828 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
832 if (CanConstFold(exprs[0], exprs[1]))
833 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
835 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
839 if (exprs[1]->expression.vtype == TYPE_FLOAT)
841 if (CanConstFold(exprs[0], exprs[1]))
842 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
844 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
848 if (CanConstFold(exprs[0], exprs[1]))
849 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
850 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
851 vector vec = ConstV(0);
852 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
853 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
854 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
855 out->expression.node.keep = false;
856 ((ast_member*)out)->rvalue = true;
858 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
860 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
861 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
862 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
863 out->expression.node.keep = false;
864 ((ast_member*)out)->rvalue = true;
866 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
868 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
869 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
870 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
871 out->expression.node.keep = false;
872 ((ast_member*)out)->rvalue = true;
874 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
877 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
879 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
880 vector vec = ConstV(1);
881 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
882 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
883 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
884 out->expression.node.keep = false;
885 ((ast_member*)out)->rvalue = true;
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
889 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
890 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
891 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
892 out->expression.node.keep = false;
893 ((ast_member*)out)->rvalue = true;
895 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
897 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
898 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
899 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
900 out->expression.node.keep = false;
901 ((ast_member*)out)->rvalue = true;
903 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
909 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
913 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
914 type_name[exprs[1]->expression.vtype],
915 type_name[exprs[0]->expression.vtype]);
920 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
921 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
922 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
923 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
926 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
927 if (CanConstFold(exprs[0], exprs[1]))
928 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
930 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
932 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
933 if (CanConstFold(exprs[0], exprs[1]))
934 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
936 if (CanConstFold1(exprs[1])) {
937 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
939 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
940 (ast_expression*)parser_const_float_1(parser),
944 compile_error(ctx, "internal error: failed to generate division");
947 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
952 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
953 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
954 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
960 compile_error(ctx, "qc does not have a modulo operator");
964 if (NotSameType(TYPE_FLOAT)) {
965 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
966 type_name[exprs[0]->expression.vtype],
967 type_name[exprs[1]->expression.vtype]);
970 if (CanConstFold(exprs[0], exprs[1]))
971 out = (ast_expression*)parser_const_float(parser,
972 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
973 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
975 out = (ast_expression*)ast_binary_new(ctx,
976 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
980 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
985 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
986 if (op->id == opid2('<','<'))
987 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
989 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
992 case opid3('<','<','='):
993 case opid3('>','>','='):
994 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
998 generated_op += 1; /* INSTR_OR */
1000 generated_op += INSTR_AND;
1001 if (CanConstFold(exprs[0], exprs[1]))
1003 if (OPTS_FLAG(PERL_LOGIC)) {
1004 if (immediate_is_true(ctx, asvalue[0]))
1008 out = (ast_expression*)parser_const_float(parser,
1009 ( (generated_op == INSTR_OR)
1010 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1011 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1016 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1017 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1018 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1019 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1022 for (i = 0; i < 2; ++i) {
1023 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1024 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1026 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1028 exprs[i] = out; out = NULL;
1029 if (OPTS_FLAG(PERL_LOGIC)) {
1030 /* here we want to keep the right expressions' type */
1034 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1035 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1037 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1039 exprs[i] = out; out = NULL;
1040 if (OPTS_FLAG(PERL_LOGIC)) {
1041 /* here we want to keep the right expressions' type */
1046 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1050 case opid2('?',':'):
1051 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1052 compile_error(ctx, "mismatched parenthesis/ternary");
1056 if (!ast_compare_type(exprs[1], exprs[2])) {
1057 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1058 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1059 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1062 if (CanConstFold1(exprs[0]))
1063 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1065 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1069 generated_op += 1; /* INSTR_GT */
1071 generated_op += 1; /* INSTR_LT */
1072 case opid2('>', '='):
1073 generated_op += 1; /* INSTR_GE */
1074 case opid2('<', '='):
1075 generated_op += INSTR_LE;
1076 if (NotSameType(TYPE_FLOAT)) {
1077 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1078 type_name[exprs[0]->expression.vtype],
1079 type_name[exprs[1]->expression.vtype]);
1082 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1084 case opid2('!', '='):
1085 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1086 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1087 type_name[exprs[0]->expression.vtype],
1088 type_name[exprs[1]->expression.vtype]);
1091 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1093 case opid2('=', '='):
1094 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1095 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1096 type_name[exprs[0]->expression.vtype],
1097 type_name[exprs[1]->expression.vtype]);
1100 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1104 if (ast_istype(exprs[0], ast_entfield)) {
1105 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1106 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1107 exprs[0]->expression.vtype == TYPE_FIELD &&
1108 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1110 assignop = type_storep_instr[TYPE_VECTOR];
1113 assignop = type_storep_instr[exprs[0]->expression.vtype];
1114 if (assignop == AINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1116 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1117 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1118 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1119 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1120 exprs[1]->expression.vtype == TYPE_FUNCTION)
1122 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1123 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1126 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1131 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1132 exprs[0]->expression.vtype == TYPE_FIELD &&
1133 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1135 assignop = type_store_instr[TYPE_VECTOR];
1138 assignop = type_store_instr[exprs[0]->expression.vtype];
1141 if (assignop == AINSTR_END) {
1142 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1143 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1144 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1146 else if (!ast_compare_type(exprs[0], exprs[1]))
1148 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1149 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1150 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1151 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1152 exprs[1]->expression.vtype == TYPE_FUNCTION)
1154 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1155 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1158 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1161 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1162 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1164 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1166 case opid3('+','+','P'):
1167 case opid3('-','-','P'):
1169 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1170 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1171 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1174 if (op->id == opid3('+','+','P'))
1175 addop = INSTR_ADD_F;
1177 addop = INSTR_SUB_F;
1178 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1179 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1181 if (ast_istype(exprs[0], ast_entfield)) {
1182 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1184 (ast_expression*)parser_const_float_1(parser));
1186 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1188 (ast_expression*)parser_const_float_1(parser));
1191 case opid3('S','+','+'):
1192 case opid3('S','-','-'):
1194 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1195 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1196 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1199 if (op->id == opid3('S','+','+')) {
1200 addop = INSTR_ADD_F;
1201 subop = INSTR_SUB_F;
1203 addop = INSTR_SUB_F;
1204 subop = INSTR_ADD_F;
1206 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1207 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1209 if (ast_istype(exprs[0], ast_entfield)) {
1210 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1212 (ast_expression*)parser_const_float_1(parser));
1214 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1216 (ast_expression*)parser_const_float_1(parser));
1220 out = (ast_expression*)ast_binary_new(ctx, subop,
1222 (ast_expression*)parser_const_float_1(parser));
1224 case opid2('+','='):
1225 case opid2('-','='):
1226 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1227 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1229 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1230 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1231 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1235 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1236 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1238 if (ast_istype(exprs[0], ast_entfield))
1239 assignop = type_storep_instr[exprs[0]->expression.vtype];
1241 assignop = type_store_instr[exprs[0]->expression.vtype];
1242 switch (exprs[0]->expression.vtype) {
1244 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1245 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1246 exprs[0], exprs[1]);
1249 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1250 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1251 exprs[0], exprs[1]);
1254 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1255 type_name[exprs[0]->expression.vtype],
1256 type_name[exprs[1]->expression.vtype]);
1260 case opid2('*','='):
1261 case opid2('/','='):
1262 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1263 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1264 exprs[0]->expression.vtype == TYPE_VECTOR))
1266 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1267 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1268 compile_error(ctx, "invalid types used in expression: %s and %s",
1272 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1273 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1275 if (ast_istype(exprs[0], ast_entfield))
1276 assignop = type_storep_instr[exprs[0]->expression.vtype];
1278 assignop = type_store_instr[exprs[0]->expression.vtype];
1279 switch (exprs[0]->expression.vtype) {
1281 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1282 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1283 exprs[0], exprs[1]);
1286 if (op->id == opid2('*','=')) {
1287 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1288 exprs[0], exprs[1]);
1290 /* there's no DIV_VF */
1291 if (CanConstFold1(exprs[1])) {
1292 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1294 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1295 (ast_expression*)parser_const_float_1(parser),
1299 compile_error(ctx, "internal error: failed to generate division");
1302 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1307 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1308 type_name[exprs[0]->expression.vtype],
1309 type_name[exprs[1]->expression.vtype]);
1313 case opid2('&','='):
1314 case opid2('|','='):
1315 if (NotSameType(TYPE_FLOAT)) {
1316 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1317 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1318 compile_error(ctx, "invalid types used in expression: %s and %s",
1322 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1323 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1325 if (ast_istype(exprs[0], ast_entfield))
1326 assignop = type_storep_instr[exprs[0]->expression.vtype];
1328 assignop = type_store_instr[exprs[0]->expression.vtype];
1329 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1330 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1331 exprs[0], exprs[1]);
1333 case opid3('&','~','='):
1334 /* This is like: a &= ~(b);
1335 * But QC has no bitwise-not, so we implement it as
1338 if (NotSameType(TYPE_FLOAT)) {
1339 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1340 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1341 compile_error(ctx, "invalid types used in expression: %s and %s",
1345 if (ast_istype(exprs[0], ast_entfield))
1346 assignop = type_storep_instr[exprs[0]->expression.vtype];
1348 assignop = type_store_instr[exprs[0]->expression.vtype];
1349 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1352 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1353 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1355 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1356 asbinstore->keep_dest = true;
1357 out = (ast_expression*)asbinstore;
1363 compile_error(ctx, "failed to apply operator %s", op->op);
1367 vec_push(sy->out, syexp(ctx, out));
1371 static bool parser_close_call(parser_t *parser, shunt *sy)
1373 /* was a function call */
1374 ast_expression *fun;
1375 ast_value *funval = NULL;
1379 size_t paramcount, i;
1381 fid = vec_last(sy->ops).off;
1382 vec_shrinkby(sy->ops, 1);
1384 /* out[fid] is the function
1385 * everything above is parameters...
1387 if (!vec_size(sy->argc)) {
1388 parseerror(parser, "internal error: no argument counter available");
1392 paramcount = vec_last(sy->argc);
1395 if (vec_size(sy->out) < fid) {
1396 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1397 (unsigned long)vec_size(sy->out),
1399 (unsigned long)paramcount);
1403 fun = sy->out[fid].out;
1405 if (fun == intrinsic_debug_typestring) {
1407 if (fid+2 != vec_size(sy->out) ||
1408 vec_last(sy->out).block)
1410 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1413 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1414 ast_unref(vec_last(sy->out).out);
1415 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1416 (ast_expression*)parser_const_string(parser, ty, false));
1417 vec_shrinkby(sy->out, 1);
1421 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1425 if (fid+1 < vec_size(sy->out))
1428 if (fid+1 + paramcount != vec_size(sy->out)) {
1429 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1430 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1434 for (i = 0; i < paramcount; ++i)
1435 vec_push(call->params, sy->out[fid+1 + i].out);
1436 vec_shrinkby(sy->out, paramcount);
1437 (void)!ast_call_check_types(call);
1438 if (parser->max_param_count < paramcount)
1439 parser->max_param_count = paramcount;
1441 if (ast_istype(fun, ast_value)) {
1442 funval = (ast_value*)fun;
1443 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1444 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1446 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1450 /* overwrite fid, the function, with a call */
1451 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1453 if (fun->expression.vtype != TYPE_FUNCTION) {
1454 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1458 if (!fun->expression.next) {
1459 parseerror(parser, "could not determine function return type");
1462 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1464 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1466 return !parsewarning(parser, WARN_DEPRECATED,
1467 "call to function (which is marked deprecated)\n",
1468 "-> it has been declared here: %s:%i",
1469 ast_ctx(fun).file, ast_ctx(fun).line);
1472 return !parsewarning(parser, WARN_DEPRECATED,
1473 "call to `%s` (which is marked deprecated)\n"
1474 "-> `%s` declared here: %s:%i",
1475 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1477 return !parsewarning(parser, WARN_DEPRECATED,
1478 "call to `%s` (deprecated: %s)\n"
1479 "-> `%s` declared here: %s:%i",
1480 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1484 if (vec_size(fun->expression.params) != paramcount &&
1485 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1486 vec_size(fun->expression.params) < paramcount))
1488 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1490 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1491 "too %s parameters for call to %s: expected %i, got %i\n"
1492 " -> `%s` has been declared here: %s:%i",
1493 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1494 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1496 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1497 "too %s parameters for function call: expected %i, got %i\n"
1498 " -> it has been declared here: %s:%i",
1499 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1500 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1507 static bool parser_close_paren(parser_t *parser, shunt *sy)
1509 if (!vec_size(sy->ops)) {
1510 parseerror(parser, "unmatched closing paren");
1514 while (vec_size(sy->ops)) {
1515 if (vec_last(sy->ops).isparen) {
1516 if (vec_last(sy->paren) == PAREN_FUNC) {
1518 if (!parser_close_call(parser, sy))
1522 if (vec_last(sy->paren) == PAREN_EXPR) {
1524 if (!vec_size(sy->out)) {
1525 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1526 vec_shrinkby(sy->ops, 1);
1529 vec_shrinkby(sy->ops, 1);
1532 if (vec_last(sy->paren) == PAREN_INDEX) {
1534 /* pop off the parenthesis */
1535 vec_shrinkby(sy->ops, 1);
1536 /* then apply the index operator */
1537 if (!parser_sy_apply_operator(parser, sy))
1541 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1542 vec_last(sy->paren) = PAREN_TERNARY2;
1543 /* pop off the parenthesis */
1544 vec_shrinkby(sy->ops, 1);
1547 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1550 if (!parser_sy_apply_operator(parser, sy))
1556 static void parser_reclassify_token(parser_t *parser)
1559 for (i = 0; i < operator_count; ++i) {
1560 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1561 parser->tok = TOKEN_OPERATOR;
1567 static ast_expression* parse_vararg_do(parser_t *parser)
1569 ast_expression *idx, *out;
1571 ast_value *funtype = parser->function->vtype;
1573 lex_ctx ctx = parser_ctx(parser);
1575 if (!parser_next(parser) || parser->tok != '(') {
1576 parseerror(parser, "expected parameter index and type in parenthesis");
1579 if (!parser_next(parser)) {
1580 parseerror(parser, "error parsing parameter index");
1584 idx = parse_expression_leave(parser, true, false, false);
1588 if (parser->tok != ',') {
1590 parseerror(parser, "expected comma after parameter index");
1594 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1596 parseerror(parser, "expected typename for vararg");
1600 typevar = parse_typename(parser, NULL, NULL);
1606 if (parser->tok != ')') {
1608 ast_delete(typevar);
1609 parseerror(parser, "expected closing paren");
1614 if (!parser_next(parser)) {
1616 ast_delete(typevar);
1617 parseerror(parser, "parse error after vararg");
1622 if (!parser->function->varargs) {
1624 ast_delete(typevar);
1625 parseerror(parser, "function has no variable argument list");
1629 if (funtype->expression.varparam &&
1630 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1634 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1635 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1636 compile_error(ast_ctx(typevar),
1637 "function was declared to take varargs of type `%s`, requested type is: %s",
1641 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1642 ast_type_adopt(out, typevar);
1643 ast_delete(typevar);
1647 static ast_expression* parse_vararg(parser_t *parser)
1649 bool old_noops = parser->lex->flags.noops;
1651 ast_expression *out;
1653 parser->lex->flags.noops = true;
1654 out = parse_vararg_do(parser);
1656 parser->lex->flags.noops = old_noops;
1660 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1662 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1663 parser->tok == TOKEN_IDENT &&
1664 !strcmp(parser_tokval(parser), "_"))
1666 /* a translatable string */
1669 parser->lex->flags.noops = true;
1670 if (!parser_next(parser) || parser->tok != '(') {
1671 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1674 parser->lex->flags.noops = false;
1675 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1676 parseerror(parser, "expected a constant string in translatable-string extension");
1679 val = parser_const_string(parser, parser_tokval(parser), true);
1682 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1684 if (!parser_next(parser) || parser->tok != ')') {
1685 parseerror(parser, "expected closing paren after translatable string");
1690 else if (parser->tok == TOKEN_DOTS)
1693 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1694 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1697 va = parse_vararg(parser);
1700 vec_push(sy->out, syexp(parser_ctx(parser), va));
1703 else if (parser->tok == TOKEN_FLOATCONST) {
1705 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1708 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1711 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1713 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1716 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1719 else if (parser->tok == TOKEN_STRINGCONST) {
1721 val = parser_const_string(parser, parser_tokval(parser), false);
1724 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1727 else if (parser->tok == TOKEN_VECTORCONST) {
1729 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1732 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1735 else if (parser->tok == TOKEN_IDENT)
1737 const char *ctoken = parser_tokval(parser);
1738 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1739 ast_expression *var;
1740 /* a_vector.{x,y,z} */
1741 if (!vec_size(sy->ops) ||
1742 !vec_last(sy->ops).etype ||
1743 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1744 (prev >= intrinsic_debug_typestring &&
1745 prev <= intrinsic_debug_typestring))
1747 /* When adding more intrinsics, fix the above condition */
1750 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1752 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1754 var = parser_find_var(parser, parser_tokval(parser));
1756 var = parser_find_field(parser, parser_tokval(parser));
1758 if (!var && with_labels) {
1759 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1761 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1762 var = (ast_expression*)lbl;
1763 vec_push(parser->labels, lbl);
1768 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1769 var = (ast_expression*)intrinsic_debug_typestring;
1773 char *correct = NULL;
1777 * sometimes people use preprocessing predefs without enabling them
1778 * i've done this thousands of times already myself. Lets check for
1779 * it in the predef table. And diagnose it better :)
1781 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1782 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1783 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1784 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1791 * TODO: determine the best score for the identifier: be it
1792 * a variable, a field.
1794 * We should also consider adding correction tables for
1795 * other things as well.
1797 if (opts.correction) {
1799 correct_init(&corr);
1801 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1802 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1803 if (strcmp(correct, parser_tokval(parser))) {
1805 } else if (correct) {
1810 correct_free(&corr);
1813 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1818 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1824 if (ast_istype(var, ast_value)) {
1825 ((ast_value*)var)->uses++;
1827 else if (ast_istype(var, ast_member)) {
1828 ast_member *mem = (ast_member*)var;
1829 if (ast_istype(mem->owner, ast_value))
1830 ((ast_value*)(mem->owner))->uses++;
1833 vec_push(sy->out, syexp(parser_ctx(parser), var));
1836 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1840 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1842 ast_expression *expr = NULL;
1845 bool wantop = false;
1846 /* only warn once about an assignment in a truth value because the current code
1847 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1849 bool warn_truthvalue = true;
1851 /* count the parens because an if starts with one, so the
1852 * end of a condition is an unmatched closing paren
1856 memset(&sy, 0, sizeof(sy));
1858 parser->lex->flags.noops = false;
1860 parser_reclassify_token(parser);
1864 if (parser->tok == TOKEN_TYPENAME) {
1865 parseerror(parser, "unexpected typename");
1869 if (parser->tok == TOKEN_OPERATOR)
1871 /* classify the operator */
1872 const oper_info *op;
1873 const oper_info *olast = NULL;
1875 for (o = 0; o < operator_count; ++o) {
1876 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1877 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1878 !strcmp(parser_tokval(parser), operators[o].op))
1883 if (o == operator_count) {
1884 /* no operator found... must be the end of the statement */
1887 /* found an operator */
1890 /* when declaring variables, a comma starts a new variable */
1891 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
1892 /* fixup the token */
1897 /* a colon without a pervious question mark cannot be a ternary */
1898 if (!ternaries && op->id == opid2(':','?')) {
1903 if (op->id == opid1(',')) {
1904 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1905 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1909 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1910 olast = &operators[vec_last(sy.ops).etype-1];
1912 #define IsAssignOp(x) (\
1913 (x) == opid1('=') || \
1914 (x) == opid2('+','=') || \
1915 (x) == opid2('-','=') || \
1916 (x) == opid2('*','=') || \
1917 (x) == opid2('/','=') || \
1918 (x) == opid2('%','=') || \
1919 (x) == opid2('&','=') || \
1920 (x) == opid2('|','=') || \
1921 (x) == opid3('&','~','=') \
1923 if (warn_truthvalue) {
1924 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
1925 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
1926 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
1929 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
1930 warn_truthvalue = false;
1935 (op->prec < olast->prec) ||
1936 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1938 if (!parser_sy_apply_operator(parser, &sy))
1940 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
1941 olast = &operators[vec_last(sy.ops).etype-1];
1946 if (op->id == opid1('(')) {
1948 size_t sycount = vec_size(sy.out);
1949 /* we expected an operator, this is the function-call operator */
1950 vec_push(sy.paren, PAREN_FUNC);
1951 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
1952 vec_push(sy.argc, 0);
1954 vec_push(sy.paren, PAREN_EXPR);
1955 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1958 } else if (op->id == opid1('[')) {
1960 parseerror(parser, "unexpected array subscript");
1963 vec_push(sy.paren, PAREN_INDEX);
1964 /* push both the operator and the paren, this makes life easier */
1965 vec_push(sy.ops, syop(parser_ctx(parser), op));
1966 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1968 } else if (op->id == opid2('?',':')) {
1969 vec_push(sy.ops, syop(parser_ctx(parser), op));
1970 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
1973 vec_push(sy.paren, PAREN_TERNARY1);
1974 } else if (op->id == opid2(':','?')) {
1975 if (!vec_size(sy.paren)) {
1976 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1979 if (vec_last(sy.paren) != PAREN_TERNARY1) {
1980 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1983 if (!parser_close_paren(parser, &sy))
1985 vec_push(sy.ops, syop(parser_ctx(parser), op));
1989 vec_push(sy.ops, syop(parser_ctx(parser), op));
1990 wantop = !!(op->flags & OP_SUFFIX);
1993 else if (parser->tok == ')') {
1994 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
1995 if (!parser_sy_apply_operator(parser, &sy))
1998 if (!vec_size(sy.paren))
2001 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2002 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2005 if (!parser_close_paren(parser, &sy))
2008 /* must be a function call without parameters */
2009 if (vec_last(sy.paren) != PAREN_FUNC) {
2010 parseerror(parser, "closing paren in invalid position");
2013 if (!parser_close_paren(parser, &sy))
2018 else if (parser->tok == '(') {
2019 parseerror(parser, "internal error: '(' should be classified as operator");
2022 else if (parser->tok == '[') {
2023 parseerror(parser, "internal error: '[' should be classified as operator");
2026 else if (parser->tok == ']') {
2027 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2028 if (!parser_sy_apply_operator(parser, &sy))
2031 if (!vec_size(sy.paren))
2033 if (vec_last(sy.paren) != PAREN_INDEX) {
2034 parseerror(parser, "mismatched parentheses, unexpected ']'");
2037 if (!parser_close_paren(parser, &sy))
2042 if (!parse_sya_operand(parser, &sy, with_labels))
2045 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2046 vec_last(sy.argc)++;
2051 parseerror(parser, "expected operator or end of statement");
2055 if (!parser_next(parser)) {
2058 if (parser->tok == ';' ||
2059 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2060 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2066 while (vec_size(sy.ops)) {
2067 if (!parser_sy_apply_operator(parser, &sy))
2071 parser->lex->flags.noops = true;
2072 if (!vec_size(sy.out)) {
2073 parseerror(parser, "empty expression");
2076 expr = sy.out[0].out;
2079 if (vec_size(sy.paren)) {
2080 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2088 parser->lex->flags.noops = true;
2089 for (i = 0; i < vec_size(sy.out); ++i) {
2091 ast_unref(sy.out[i].out);
2100 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2102 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2105 if (parser->tok != ';') {
2106 parseerror(parser, "semicolon expected after expression");
2110 if (!parser_next(parser)) {
2117 static void parser_enterblock(parser_t *parser)
2119 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2120 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2121 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2122 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2123 vec_push(parser->_block_ctx, parser_ctx(parser));
2126 vec_push(parser->correct_variables, correct_trie_new());
2127 vec_push(parser->correct_variables_score, NULL);
2130 static bool parser_leaveblock(parser_t *parser)
2133 size_t locals, typedefs;
2135 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2136 parseerror(parser, "internal error: parser_leaveblock with no block");
2140 util_htdel(vec_last(parser->variables));
2141 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2143 vec_pop(parser->variables);
2144 vec_pop(parser->correct_variables);
2145 vec_pop(parser->correct_variables_score);
2146 if (!vec_size(parser->_blocklocals)) {
2147 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2151 locals = vec_last(parser->_blocklocals);
2152 vec_pop(parser->_blocklocals);
2153 while (vec_size(parser->_locals) != locals) {
2154 ast_expression *e = vec_last(parser->_locals);
2155 ast_value *v = (ast_value*)e;
2156 vec_pop(parser->_locals);
2157 if (ast_istype(e, ast_value) && !v->uses) {
2158 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2163 typedefs = vec_last(parser->_blocktypedefs);
2164 while (vec_size(parser->_typedefs) != typedefs) {
2165 ast_delete(vec_last(parser->_typedefs));
2166 vec_pop(parser->_typedefs);
2168 util_htdel(vec_last(parser->typedefs));
2169 vec_pop(parser->typedefs);
2171 vec_pop(parser->_block_ctx);
2176 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2178 vec_push(parser->_locals, e);
2179 util_htset(vec_last(parser->variables), name, (void*)e);
2183 vec_last(parser->correct_variables),
2184 &vec_last(parser->correct_variables_score),
2189 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2191 vec_push(parser->globals, e);
2192 util_htset(parser->htglobals, name, e);
2196 parser->correct_variables[0],
2197 &parser->correct_variables_score[0],
2202 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2206 ast_expression *prev;
2208 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2211 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2214 parseerror(parser, "internal error: failed to process condition");
2219 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2221 /* vector types need to be cast to true booleans */
2222 ast_binary *bin = (ast_binary*)cond;
2223 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2225 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2227 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2230 parseerror(parser, "internal error: failed to process condition");
2237 unary = (ast_unary*)cond;
2238 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2240 cond = unary->operand;
2241 unary->operand = NULL;
2244 unary = (ast_unary*)cond;
2248 parseerror(parser, "internal error: failed to process condition");
2250 if (ifnot) *_ifnot = !*_ifnot;
2254 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2257 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2260 lex_ctx ctx = parser_ctx(parser);
2262 (void)block; /* not touching */
2264 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2265 if (!parser_next(parser)) {
2266 parseerror(parser, "expected condition or 'not'");
2269 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2271 if (!parser_next(parser)) {
2272 parseerror(parser, "expected condition in parenthesis");
2276 if (parser->tok != '(') {
2277 parseerror(parser, "expected 'if' condition in parenthesis");
2280 /* parse into the expression */
2281 if (!parser_next(parser)) {
2282 parseerror(parser, "expected 'if' condition after opening paren");
2285 /* parse the condition */
2286 cond = parse_expression_leave(parser, false, true, false);
2290 if (parser->tok != ')') {
2291 parseerror(parser, "expected closing paren after 'if' condition");
2295 /* parse into the 'then' branch */
2296 if (!parser_next(parser)) {
2297 parseerror(parser, "expected statement for on-true branch of 'if'");
2301 if (!parse_statement_or_block(parser, &ontrue)) {
2306 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2307 /* check for an else */
2308 if (!strcmp(parser_tokval(parser), "else")) {
2309 /* parse into the 'else' branch */
2310 if (!parser_next(parser)) {
2311 parseerror(parser, "expected on-false branch after 'else'");
2316 if (!parse_statement_or_block(parser, &onfalse)) {
2323 cond = process_condition(parser, cond, &ifnot);
2325 if (ontrue) ast_delete(ontrue);
2326 if (onfalse) ast_delete(onfalse);
2331 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2333 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2334 *out = (ast_expression*)ifthen;
2338 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2339 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2344 /* skip the 'while' and get the body */
2345 if (!parser_next(parser)) {
2346 if (OPTS_FLAG(LOOP_LABELS))
2347 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2349 parseerror(parser, "expected 'while' condition in parenthesis");
2353 if (parser->tok == ':') {
2354 if (!OPTS_FLAG(LOOP_LABELS))
2355 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2356 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2357 parseerror(parser, "expected loop label");
2360 label = util_strdup(parser_tokval(parser));
2361 if (!parser_next(parser)) {
2363 parseerror(parser, "expected 'while' condition in parenthesis");
2368 if (parser->tok != '(') {
2369 parseerror(parser, "expected 'while' condition in parenthesis");
2373 vec_push(parser->breaks, label);
2374 vec_push(parser->continues, label);
2376 rv = parse_while_go(parser, block, out);
2379 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2380 parseerror(parser, "internal error: label stack corrupted");
2386 vec_pop(parser->breaks);
2387 vec_pop(parser->continues);
2392 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2395 ast_expression *cond, *ontrue;
2399 lex_ctx ctx = parser_ctx(parser);
2401 (void)block; /* not touching */
2403 /* parse into the expression */
2404 if (!parser_next(parser)) {
2405 parseerror(parser, "expected 'while' condition after opening paren");
2408 /* parse the condition */
2409 cond = parse_expression_leave(parser, false, true, false);
2413 if (parser->tok != ')') {
2414 parseerror(parser, "expected closing paren after 'while' condition");
2418 /* parse into the 'then' branch */
2419 if (!parser_next(parser)) {
2420 parseerror(parser, "expected while-loop body");
2424 if (!parse_statement_or_block(parser, &ontrue)) {
2429 cond = process_condition(parser, cond, &ifnot);
2434 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2435 *out = (ast_expression*)aloop;
2439 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2440 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2445 /* skip the 'do' and get the body */
2446 if (!parser_next(parser)) {
2447 if (OPTS_FLAG(LOOP_LABELS))
2448 parseerror(parser, "expected loop label or body");
2450 parseerror(parser, "expected loop body");
2454 if (parser->tok == ':') {
2455 if (!OPTS_FLAG(LOOP_LABELS))
2456 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2457 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2458 parseerror(parser, "expected loop label");
2461 label = util_strdup(parser_tokval(parser));
2462 if (!parser_next(parser)) {
2464 parseerror(parser, "expected loop body");
2469 vec_push(parser->breaks, label);
2470 vec_push(parser->continues, label);
2472 rv = parse_dowhile_go(parser, block, out);
2475 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2476 parseerror(parser, "internal error: label stack corrupted");
2482 vec_pop(parser->breaks);
2483 vec_pop(parser->continues);
2488 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2491 ast_expression *cond, *ontrue;
2495 lex_ctx ctx = parser_ctx(parser);
2497 (void)block; /* not touching */
2499 if (!parse_statement_or_block(parser, &ontrue))
2502 /* expect the "while" */
2503 if (parser->tok != TOKEN_KEYWORD ||
2504 strcmp(parser_tokval(parser), "while"))
2506 parseerror(parser, "expected 'while' and condition");
2511 /* skip the 'while' and check for opening paren */
2512 if (!parser_next(parser) || parser->tok != '(') {
2513 parseerror(parser, "expected 'while' condition in parenthesis");
2517 /* parse into the expression */
2518 if (!parser_next(parser)) {
2519 parseerror(parser, "expected 'while' condition after opening paren");
2523 /* parse the condition */
2524 cond = parse_expression_leave(parser, false, true, false);
2528 if (parser->tok != ')') {
2529 parseerror(parser, "expected closing paren after 'while' condition");
2535 if (!parser_next(parser) || parser->tok != ';') {
2536 parseerror(parser, "expected semicolon after condition");
2542 if (!parser_next(parser)) {
2543 parseerror(parser, "parse error");
2549 cond = process_condition(parser, cond, &ifnot);
2554 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2555 *out = (ast_expression*)aloop;
2559 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2560 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2565 /* skip the 'for' and check for opening paren */
2566 if (!parser_next(parser)) {
2567 if (OPTS_FLAG(LOOP_LABELS))
2568 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2570 parseerror(parser, "expected 'for' expressions in parenthesis");
2574 if (parser->tok == ':') {
2575 if (!OPTS_FLAG(LOOP_LABELS))
2576 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2577 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2578 parseerror(parser, "expected loop label");
2581 label = util_strdup(parser_tokval(parser));
2582 if (!parser_next(parser)) {
2584 parseerror(parser, "expected 'for' expressions in parenthesis");
2589 if (parser->tok != '(') {
2590 parseerror(parser, "expected 'for' expressions in parenthesis");
2594 vec_push(parser->breaks, label);
2595 vec_push(parser->continues, label);
2597 rv = parse_for_go(parser, block, out);
2600 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2601 parseerror(parser, "internal error: label stack corrupted");
2607 vec_pop(parser->breaks);
2608 vec_pop(parser->continues);
2612 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2615 ast_expression *initexpr, *cond, *increment, *ontrue;
2621 lex_ctx ctx = parser_ctx(parser);
2623 parser_enterblock(parser);
2630 /* parse into the expression */
2631 if (!parser_next(parser)) {
2632 parseerror(parser, "expected 'for' initializer after opening paren");
2637 if (parser->tok == TOKEN_IDENT)
2638 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2640 if (typevar || parser->tok == TOKEN_TYPENAME) {
2642 if (opts.standard != COMPILER_GMQCC) {
2643 if (parsewarning(parser, WARN_EXTENSIONS,
2644 "current standard does not allow variable declarations in for-loop initializers"))
2648 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2651 else if (parser->tok != ';')
2653 initexpr = parse_expression_leave(parser, false, false, false);
2658 /* move on to condition */
2659 if (parser->tok != ';') {
2660 parseerror(parser, "expected semicolon after for-loop initializer");
2663 if (!parser_next(parser)) {
2664 parseerror(parser, "expected for-loop condition");
2668 /* parse the condition */
2669 if (parser->tok != ';') {
2670 cond = parse_expression_leave(parser, false, true, false);
2675 /* move on to incrementor */
2676 if (parser->tok != ';') {
2677 parseerror(parser, "expected semicolon after for-loop initializer");
2680 if (!parser_next(parser)) {
2681 parseerror(parser, "expected for-loop condition");
2685 /* parse the incrementor */
2686 if (parser->tok != ')') {
2687 increment = parse_expression_leave(parser, false, false, false);
2690 if (!ast_side_effects(increment)) {
2691 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2697 if (parser->tok != ')') {
2698 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2701 /* parse into the 'then' branch */
2702 if (!parser_next(parser)) {
2703 parseerror(parser, "expected for-loop body");
2706 if (!parse_statement_or_block(parser, &ontrue))
2710 cond = process_condition(parser, cond, &ifnot);
2714 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2715 *out = (ast_expression*)aloop;
2717 if (!parser_leaveblock(parser))
2721 if (initexpr) ast_delete(initexpr);
2722 if (cond) ast_delete(cond);
2723 if (increment) ast_delete(increment);
2724 (void)!parser_leaveblock(parser);
2728 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2730 ast_expression *exp = NULL;
2731 ast_return *ret = NULL;
2732 ast_value *expected = parser->function->vtype;
2734 lex_ctx ctx = parser_ctx(parser);
2736 (void)block; /* not touching */
2738 if (!parser_next(parser)) {
2739 parseerror(parser, "expected return expression");
2743 if (parser->tok != ';') {
2744 exp = parse_expression(parser, false, false);
2748 if (exp->expression.vtype != TYPE_NIL &&
2749 exp->expression.vtype != expected->expression.next->expression.vtype)
2751 parseerror(parser, "return with invalid expression");
2754 ret = ast_return_new(ctx, exp);
2760 if (!parser_next(parser))
2761 parseerror(parser, "parse error");
2762 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2763 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2765 ret = ast_return_new(ctx, NULL);
2767 *out = (ast_expression*)ret;
2771 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2774 unsigned int levels = 0;
2775 lex_ctx ctx = parser_ctx(parser);
2776 const char **loops = (is_continue ? parser->continues : parser->breaks);
2778 (void)block; /* not touching */
2779 if (!parser_next(parser)) {
2780 parseerror(parser, "expected semicolon or loop label");
2784 if (!vec_size(loops)) {
2786 parseerror(parser, "`continue` can only be used inside loops");
2788 parseerror(parser, "`break` can only be used inside loops or switches");
2791 if (parser->tok == TOKEN_IDENT) {
2792 if (!OPTS_FLAG(LOOP_LABELS))
2793 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2794 i = vec_size(loops);
2796 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2799 parseerror(parser, "no such loop to %s: `%s`",
2800 (is_continue ? "continue" : "break out of"),
2801 parser_tokval(parser));
2806 if (!parser_next(parser)) {
2807 parseerror(parser, "expected semicolon");
2812 if (parser->tok != ';') {
2813 parseerror(parser, "expected semicolon");
2817 if (!parser_next(parser))
2818 parseerror(parser, "parse error");
2820 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2824 /* returns true when it was a variable qualifier, false otherwise!
2825 * on error, cvq is set to CV_WRONG
2827 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2829 bool had_const = false;
2830 bool had_var = false;
2831 bool had_noref = false;
2832 bool had_attrib = false;
2833 bool had_static = false;
2838 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2840 /* parse an attribute */
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "expected attribute after `[[`");
2846 if (!strcmp(parser_tokval(parser), "noreturn")) {
2847 flags |= AST_FLAG_NORETURN;
2848 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2849 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2854 else if (!strcmp(parser_tokval(parser), "noref")) {
2856 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2857 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2862 else if (!strcmp(parser_tokval(parser), "inline")) {
2863 flags |= AST_FLAG_INLINE;
2864 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2865 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2872 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
2873 flags |= AST_FLAG_DEPRECATED;
2876 if (!parser_next(parser)) {
2877 parseerror(parser, "parse error in attribute");
2881 if (parser->tok == '(') {
2882 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
2883 parseerror(parser, "`deprecated` attribute missing parameter");
2887 *message = util_strdup(parser_tokval(parser));
2889 if (!parser_next(parser)) {
2890 parseerror(parser, "parse error in attribute");
2894 if(parser->tok != ')') {
2895 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
2899 if (!parser_next(parser)) {
2900 parseerror(parser, "parse error in attribute");
2905 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2906 parseerror(parser, "`deprecated` attribute expected `]]`");
2909 if (*message) mem_d(*message);
2917 /* Skip tokens until we hit a ]] */
2918 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2919 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2920 if (!parser_next(parser)) {
2921 parseerror(parser, "error inside attribute");
2928 else if (with_local && !strcmp(parser_tokval(parser), "static"))
2930 else if (!strcmp(parser_tokval(parser), "const"))
2932 else if (!strcmp(parser_tokval(parser), "var"))
2934 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2936 else if (!strcmp(parser_tokval(parser), "noref"))
2938 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
2943 if (!parser_next(parser))
2953 *is_static = had_static;
2957 parseerror(parser, "parse error after variable qualifier");
2962 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2963 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2968 /* skip the 'while' and get the body */
2969 if (!parser_next(parser)) {
2970 if (OPTS_FLAG(LOOP_LABELS))
2971 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2973 parseerror(parser, "expected 'switch' operand in parenthesis");
2977 if (parser->tok == ':') {
2978 if (!OPTS_FLAG(LOOP_LABELS))
2979 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2980 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2981 parseerror(parser, "expected loop label");
2984 label = util_strdup(parser_tokval(parser));
2985 if (!parser_next(parser)) {
2987 parseerror(parser, "expected 'switch' operand in parenthesis");
2992 if (parser->tok != '(') {
2993 parseerror(parser, "expected 'switch' operand in parenthesis");
2997 vec_push(parser->breaks, label);
2999 rv = parse_switch_go(parser, block, out);
3002 if (vec_last(parser->breaks) != label) {
3003 parseerror(parser, "internal error: label stack corrupted");
3009 vec_pop(parser->breaks);
3014 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3016 ast_expression *operand;
3019 ast_switch *switchnode;
3020 ast_switch_case swcase;
3023 bool noref, is_static;
3024 uint32_t qflags = 0;
3026 lex_ctx ctx = parser_ctx(parser);
3028 (void)block; /* not touching */
3031 /* parse into the expression */
3032 if (!parser_next(parser)) {
3033 parseerror(parser, "expected switch operand");
3036 /* parse the operand */
3037 operand = parse_expression_leave(parser, false, false, false);
3041 switchnode = ast_switch_new(ctx, operand);
3044 if (parser->tok != ')') {
3045 ast_delete(switchnode);
3046 parseerror(parser, "expected closing paren after 'switch' operand");
3050 /* parse over the opening paren */
3051 if (!parser_next(parser) || parser->tok != '{') {
3052 ast_delete(switchnode);
3053 parseerror(parser, "expected list of cases");
3057 if (!parser_next(parser)) {
3058 ast_delete(switchnode);
3059 parseerror(parser, "expected 'case' or 'default'");
3063 /* new block; allow some variables to be declared here */
3064 parser_enterblock(parser);
3067 if (parser->tok == TOKEN_IDENT)
3068 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3069 if (typevar || parser->tok == TOKEN_TYPENAME) {
3070 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3071 ast_delete(switchnode);
3076 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3078 if (cvq == CV_WRONG) {
3079 ast_delete(switchnode);
3082 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3083 ast_delete(switchnode);
3092 while (parser->tok != '}') {
3093 ast_block *caseblock;
3095 if (!strcmp(parser_tokval(parser), "case")) {
3096 if (!parser_next(parser)) {
3097 ast_delete(switchnode);
3098 parseerror(parser, "expected expression for case");
3101 swcase.value = parse_expression_leave(parser, false, false, false);
3102 if (!swcase.value) {
3103 ast_delete(switchnode);
3104 parseerror(parser, "expected expression for case");
3107 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3108 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3109 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3115 else if (!strcmp(parser_tokval(parser), "default")) {
3116 swcase.value = NULL;
3117 if (!parser_next(parser)) {
3118 ast_delete(switchnode);
3119 parseerror(parser, "expected colon");
3124 ast_delete(switchnode);
3125 parseerror(parser, "expected 'case' or 'default'");
3129 /* Now the colon and body */
3130 if (parser->tok != ':') {
3131 if (swcase.value) ast_unref(swcase.value);
3132 ast_delete(switchnode);
3133 parseerror(parser, "expected colon");
3137 if (!parser_next(parser)) {
3138 if (swcase.value) ast_unref(swcase.value);
3139 ast_delete(switchnode);
3140 parseerror(parser, "expected statements or case");
3143 caseblock = ast_block_new(parser_ctx(parser));
3145 if (swcase.value) ast_unref(swcase.value);
3146 ast_delete(switchnode);
3149 swcase.code = (ast_expression*)caseblock;
3150 vec_push(switchnode->cases, swcase);
3152 ast_expression *expr;
3153 if (parser->tok == '}')
3155 if (parser->tok == TOKEN_KEYWORD) {
3156 if (!strcmp(parser_tokval(parser), "case") ||
3157 !strcmp(parser_tokval(parser), "default"))
3162 if (!parse_statement(parser, caseblock, &expr, true)) {
3163 ast_delete(switchnode);
3168 if (!ast_block_add_expr(caseblock, expr)) {
3169 ast_delete(switchnode);
3175 parser_leaveblock(parser);
3178 if (parser->tok != '}') {
3179 ast_delete(switchnode);
3180 parseerror(parser, "expected closing paren of case list");
3183 if (!parser_next(parser)) {
3184 ast_delete(switchnode);
3185 parseerror(parser, "parse error after switch");
3188 *out = (ast_expression*)switchnode;
3192 /* parse computed goto sides */
3193 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3194 ast_expression *on_true;
3195 ast_expression *on_false;
3196 ast_expression *cond;
3201 if (ast_istype(*side, ast_ternary)) {
3202 ast_ternary *tern = (ast_ternary*)*side;
3203 on_true = parse_goto_computed(parser, &tern->on_true);
3204 on_false = parse_goto_computed(parser, &tern->on_false);
3206 if (!on_true || !on_false) {
3207 parseerror(parser, "expected label or expression in ternary");
3208 if (on_true) ast_unref(on_true);
3209 if (on_false) ast_unref(on_false);
3217 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3218 } else if (ast_istype(*side, ast_label)) {
3219 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3220 ast_goto_set_label(gt, ((ast_label*)*side));
3222 return (ast_expression*)gt;
3227 static bool parse_goto(parser_t *parser, ast_expression **out)
3229 ast_goto *gt = NULL;
3230 ast_expression *lbl;
3232 if (!parser_next(parser))
3235 if (parser->tok != TOKEN_IDENT) {
3236 ast_expression *expression;
3238 /* could be an expression i.e computed goto :-) */
3239 if (parser->tok != '(') {
3240 parseerror(parser, "expected label name after `goto`");
3244 /* failed to parse expression for goto */
3245 if (!(expression = parse_expression(parser, false, true)) ||
3246 !(*out = parse_goto_computed(parser, &expression))) {
3247 parseerror(parser, "invalid goto expression");
3248 ast_unref(expression);
3255 /* not computed goto */
3256 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3257 lbl = parser_find_label(parser, gt->name);
3259 if (!ast_istype(lbl, ast_label)) {
3260 parseerror(parser, "internal error: label is not an ast_label");
3264 ast_goto_set_label(gt, (ast_label*)lbl);
3267 vec_push(parser->gotos, gt);
3269 if (!parser_next(parser) || parser->tok != ';') {
3270 parseerror(parser, "semicolon expected after goto label");
3273 if (!parser_next(parser)) {
3274 parseerror(parser, "parse error after goto");
3278 *out = (ast_expression*)gt;
3282 static bool parse_skipwhite(parser_t *parser)
3285 if (!parser_next(parser))
3287 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3288 return parser->tok < TOKEN_ERROR;
3291 static bool parse_eol(parser_t *parser)
3293 if (!parse_skipwhite(parser))
3295 return parser->tok == TOKEN_EOL;
3298 static bool parse_pragma_do(parser_t *parser)
3300 if (!parser_next(parser) ||
3301 parser->tok != TOKEN_IDENT ||
3302 strcmp(parser_tokval(parser), "pragma"))
3304 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3307 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3308 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3312 if (!strcmp(parser_tokval(parser), "noref")) {
3313 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3314 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3317 parser->noref = !!parser_token(parser)->constval.i;
3318 if (!parse_eol(parser)) {
3319 parseerror(parser, "parse error after `noref` pragma");
3325 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3332 static bool parse_pragma(parser_t *parser)
3335 parser->lex->flags.preprocessing = true;
3336 parser->lex->flags.mergelines = true;
3337 rv = parse_pragma_do(parser);
3338 if (parser->tok != TOKEN_EOL) {
3339 parseerror(parser, "junk after pragma");
3342 parser->lex->flags.preprocessing = false;
3343 parser->lex->flags.mergelines = false;
3344 if (!parser_next(parser)) {
3345 parseerror(parser, "parse error after pragma");
3351 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3353 bool noref, is_static;
3355 uint32_t qflags = 0;
3356 ast_value *typevar = NULL;
3357 char *vstring = NULL;
3361 if (parser->tok == TOKEN_IDENT)
3362 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3364 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3366 /* local variable */
3368 parseerror(parser, "cannot declare a variable from here");
3371 if (opts.standard == COMPILER_QCC) {
3372 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3375 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3379 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3381 if (cvq == CV_WRONG)
3383 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3385 else if (parser->tok == TOKEN_KEYWORD)
3387 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3392 if (!parser_next(parser)) {
3393 parseerror(parser, "parse error after __builtin_debug_printtype");
3397 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3399 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3400 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3401 if (!parser_next(parser)) {
3402 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3408 if (!parse_statement(parser, block, out, allow_cases))
3411 con_out("__builtin_debug_printtype: got no output node\n");
3414 ast_type_to_string(*out, ty, sizeof(ty));
3415 con_out("__builtin_debug_printtype: `%s`\n", ty);
3420 else if (!strcmp(parser_tokval(parser), "return"))
3422 return parse_return(parser, block, out);
3424 else if (!strcmp(parser_tokval(parser), "if"))
3426 return parse_if(parser, block, out);
3428 else if (!strcmp(parser_tokval(parser), "while"))
3430 return parse_while(parser, block, out);
3432 else if (!strcmp(parser_tokval(parser), "do"))
3434 return parse_dowhile(parser, block, out);
3436 else if (!strcmp(parser_tokval(parser), "for"))
3438 if (opts.standard == COMPILER_QCC) {
3439 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3442 return parse_for(parser, block, out);
3444 else if (!strcmp(parser_tokval(parser), "break"))
3446 return parse_break_continue(parser, block, out, false);
3448 else if (!strcmp(parser_tokval(parser), "continue"))
3450 return parse_break_continue(parser, block, out, true);
3452 else if (!strcmp(parser_tokval(parser), "switch"))
3454 return parse_switch(parser, block, out);
3456 else if (!strcmp(parser_tokval(parser), "case") ||
3457 !strcmp(parser_tokval(parser), "default"))
3460 parseerror(parser, "unexpected 'case' label");
3465 else if (!strcmp(parser_tokval(parser), "goto"))
3467 return parse_goto(parser, out);
3469 else if (!strcmp(parser_tokval(parser), "typedef"))
3471 if (!parser_next(parser)) {
3472 parseerror(parser, "expected type definition after 'typedef'");
3475 return parse_typedef(parser);
3477 parseerror(parser, "Unexpected keyword");
3480 else if (parser->tok == '{')
3483 inner = parse_block(parser);
3486 *out = (ast_expression*)inner;
3489 else if (parser->tok == ':')
3493 if (!parser_next(parser)) {
3494 parseerror(parser, "expected label name");
3497 if (parser->tok != TOKEN_IDENT) {
3498 parseerror(parser, "label must be an identifier");
3501 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3503 if (!label->undefined) {
3504 parseerror(parser, "label `%s` already defined", label->name);
3507 label->undefined = false;
3510 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3511 vec_push(parser->labels, label);
3513 *out = (ast_expression*)label;
3514 if (!parser_next(parser)) {
3515 parseerror(parser, "parse error after label");
3518 for (i = 0; i < vec_size(parser->gotos); ++i) {
3519 if (!strcmp(parser->gotos[i]->name, label->name)) {
3520 ast_goto_set_label(parser->gotos[i], label);
3521 vec_remove(parser->gotos, i, 1);
3527 else if (parser->tok == ';')
3529 if (!parser_next(parser)) {
3530 parseerror(parser, "parse error after empty statement");
3537 ast_expression *exp = parse_expression(parser, false, false);
3541 if (!ast_side_effects(exp)) {
3542 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3549 static bool parse_enum(parser_t *parser)
3552 ast_value **values = NULL;
3553 ast_value *var = NULL;
3556 ast_expression *old;
3558 if (!parser_next(parser) || parser->tok != '{') {
3559 parseerror(parser, "expected `{` after `enum` keyword");
3564 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3565 if (parser->tok == '}') {
3566 /* allow an empty enum */
3569 parseerror(parser, "expected identifier or `}`");
3573 old = parser_find_field(parser, parser_tokval(parser));
3575 old = parser_find_global(parser, parser_tokval(parser));
3577 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3578 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3582 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3583 vec_push(values, var);
3584 var->cvq = CV_CONST;
3585 var->hasvalue = true;
3586 var->constval.vfloat = num++;
3588 parser_addglobal(parser, var->name, (ast_expression*)var);
3590 if (!parser_next(parser)) {
3591 parseerror(parser, "expected `=`, `}` or comma after identifier");
3595 if (parser->tok == ',')
3597 if (parser->tok == '}')
3599 if (parser->tok != '=') {
3600 parseerror(parser, "expected `=`, `}` or comma after identifier");
3604 if (!parser_next(parser)) {
3605 parseerror(parser, "expected expression after `=`");
3609 /* We got a value! */
3610 old = parse_expression_leave(parser, true, false, false);
3611 asvalue = (ast_value*)old;
3612 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3613 compile_error(ast_ctx(var), "constant value or expression expected");
3616 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3618 if (parser->tok == '}')
3620 if (parser->tok != ',') {
3621 parseerror(parser, "expected `}` or comma after expression");
3626 if (parser->tok != '}') {
3627 parseerror(parser, "internal error: breaking without `}`");
3631 if (!parser_next(parser) || parser->tok != ';') {
3632 parseerror(parser, "expected semicolon after enumeration");
3636 if (!parser_next(parser)) {
3637 parseerror(parser, "parse error after enumeration");
3649 static bool parse_block_into(parser_t *parser, ast_block *block)
3653 parser_enterblock(parser);
3655 if (!parser_next(parser)) { /* skip the '{' */
3656 parseerror(parser, "expected function body");
3660 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3662 ast_expression *expr = NULL;
3663 if (parser->tok == '}')
3666 if (!parse_statement(parser, block, &expr, false)) {
3667 /* parseerror(parser, "parse error"); */
3673 if (!ast_block_add_expr(block, expr)) {
3680 if (parser->tok != '}') {
3683 (void)parser_next(parser);
3687 if (!parser_leaveblock(parser))
3689 return retval && !!block;
3692 static ast_block* parse_block(parser_t *parser)
3695 block = ast_block_new(parser_ctx(parser));
3698 if (!parse_block_into(parser, block)) {
3699 ast_block_delete(block);
3705 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3707 if (parser->tok == '{') {
3708 *out = (ast_expression*)parse_block(parser);
3711 return parse_statement(parser, NULL, out, false);
3714 static bool create_vector_members(ast_value *var, ast_member **me)
3717 size_t len = strlen(var->name);
3719 for (i = 0; i < 3; ++i) {
3720 char *name = (char*)mem_a(len+3);
3721 memcpy(name, var->name, len);
3723 name[len+1] = 'x'+i;
3725 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3734 do { ast_member_delete(me[--i]); } while(i);
3738 static bool parse_function_body(parser_t *parser, ast_value *var)
3740 ast_block *block = NULL;
3745 ast_expression *framenum = NULL;
3746 ast_expression *nextthink = NULL;
3747 /* None of the following have to be deleted */
3748 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3749 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3750 bool has_frame_think;
3754 has_frame_think = false;
3755 old = parser->function;
3757 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3758 parseerror(parser, "gotos/labels leaking");
3762 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3763 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3764 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3770 if (parser->tok == '[') {
3771 /* got a frame definition: [ framenum, nextthink ]
3772 * this translates to:
3773 * self.frame = framenum;
3774 * self.nextthink = time + 0.1;
3775 * self.think = nextthink;
3779 fld_think = parser_find_field(parser, "think");
3780 fld_nextthink = parser_find_field(parser, "nextthink");
3781 fld_frame = parser_find_field(parser, "frame");
3782 if (!fld_think || !fld_nextthink || !fld_frame) {
3783 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3784 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3787 gbl_time = parser_find_global(parser, "time");
3788 gbl_self = parser_find_global(parser, "self");
3789 if (!gbl_time || !gbl_self) {
3790 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3791 parseerror(parser, "please declare the following globals: `time`, `self`");
3795 if (!parser_next(parser))
3798 framenum = parse_expression_leave(parser, true, false, false);
3800 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3803 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3804 ast_unref(framenum);
3805 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3809 if (parser->tok != ',') {
3810 ast_unref(framenum);
3811 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3812 parseerror(parser, "Got a %i\n", parser->tok);
3816 if (!parser_next(parser)) {
3817 ast_unref(framenum);
3821 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3823 /* qc allows the use of not-yet-declared functions here
3824 * - this automatically creates a prototype */
3825 ast_value *thinkfunc;
3826 ast_expression *functype = fld_think->expression.next;
3828 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3829 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3830 ast_unref(framenum);
3831 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3835 if (!parser_next(parser)) {
3836 ast_unref(framenum);
3837 ast_delete(thinkfunc);
3841 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
3843 nextthink = (ast_expression*)thinkfunc;
3846 nextthink = parse_expression_leave(parser, true, false, false);
3848 ast_unref(framenum);
3849 parseerror(parser, "expected a think-function in [frame,think] notation");
3854 if (!ast_istype(nextthink, ast_value)) {
3855 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3859 if (retval && parser->tok != ']') {
3860 parseerror(parser, "expected closing `]` for [frame,think] notation");
3864 if (retval && !parser_next(parser)) {
3868 if (retval && parser->tok != '{') {
3869 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3874 ast_unref(nextthink);
3875 ast_unref(framenum);
3879 has_frame_think = true;
3882 block = ast_block_new(parser_ctx(parser));
3884 parseerror(parser, "failed to allocate block");
3885 if (has_frame_think) {
3886 ast_unref(nextthink);
3887 ast_unref(framenum);
3892 if (has_frame_think) {
3894 ast_expression *self_frame;
3895 ast_expression *self_nextthink;
3896 ast_expression *self_think;
3897 ast_expression *time_plus_1;
3898 ast_store *store_frame;
3899 ast_store *store_nextthink;
3900 ast_store *store_think;
3902 ctx = parser_ctx(parser);
3903 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3904 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3905 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3907 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3908 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3910 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3911 if (self_frame) ast_delete(self_frame);
3912 if (self_nextthink) ast_delete(self_nextthink);
3913 if (self_think) ast_delete(self_think);
3914 if (time_plus_1) ast_delete(time_plus_1);
3920 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3921 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3922 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3925 ast_delete(self_frame);
3928 if (!store_nextthink) {
3929 ast_delete(self_nextthink);
3933 ast_delete(self_think);
3937 if (store_frame) ast_delete(store_frame);
3938 if (store_nextthink) ast_delete(store_nextthink);
3939 if (store_think) ast_delete(store_think);
3942 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3943 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3944 !ast_block_add_expr(block, (ast_expression*)store_think))
3951 parseerror(parser, "failed to generate code for [frame,think]");
3952 ast_unref(nextthink);
3953 ast_unref(framenum);
3959 func = ast_function_new(ast_ctx(var), var->name, var);
3961 parseerror(parser, "failed to allocate function for `%s`", var->name);
3962 ast_block_delete(block);
3965 vec_push(parser->functions, func);
3967 parser_enterblock(parser);
3969 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3971 ast_value *param = var->expression.params[parami];
3974 if (param->expression.vtype != TYPE_VECTOR &&
3975 (param->expression.vtype != TYPE_FIELD ||
3976 param->expression.next->expression.vtype != TYPE_VECTOR))
3981 if (!create_vector_members(param, me)) {
3982 ast_block_delete(block);
3986 for (e = 0; e < 3; ++e) {
3987 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3988 ast_block_collect(block, (ast_expression*)me[e]);
3992 if (var->argcounter) {
3993 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
3994 parser_addlocal(parser, argc->name, (ast_expression*)argc);
3998 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4000 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4001 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4002 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4003 varargs->expression.count = 0;
4004 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4005 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4006 ast_delete(varargs);
4007 ast_block_delete(block);
4010 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4011 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4012 ast_delete(varargs);
4013 ast_block_delete(block);
4016 func->varargs = varargs;
4018 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4021 parser->function = func;
4022 if (!parse_block_into(parser, block)) {
4023 ast_block_delete(block);
4027 vec_push(func->blocks, block);
4029 parser->function = old;
4030 if (!parser_leaveblock(parser))
4032 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4033 parseerror(parser, "internal error: local scopes left");
4037 if (parser->tok == ';')
4038 return parser_next(parser);
4039 else if (opts.standard == COMPILER_QCC)
4040 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4044 (void)!parser_leaveblock(parser);
4045 vec_pop(parser->functions);
4046 ast_function_delete(func);
4047 var->constval.vfunc = NULL;
4050 parser->function = old;
4054 static ast_expression *array_accessor_split(
4059 ast_expression *left,
4060 ast_expression *right
4066 lex_ctx ctx = ast_ctx(array);
4068 if (!left || !right) {
4069 if (left) ast_delete(left);
4070 if (right) ast_delete(right);
4074 cmp = ast_binary_new(ctx, INSTR_LT,
4075 (ast_expression*)index,
4076 (ast_expression*)parser_const_float(parser, middle));
4080 parseerror(parser, "internal error: failed to create comparison for array setter");
4084 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4086 ast_delete(cmp); /* will delete left and right */
4087 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4091 return (ast_expression*)ifthen;
4094 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4096 lex_ctx ctx = ast_ctx(array);
4098 if (from+1 == afterend) {
4099 /* set this value */
4102 ast_array_index *subscript;
4104 int assignop = type_store_instr[value->expression.vtype];
4106 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4107 assignop = INSTR_STORE_V;
4109 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4113 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4115 ast_delete(subscript);
4119 block = ast_block_new(ctx);
4125 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4130 ret = ast_return_new(ctx, NULL);
4136 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4141 return (ast_expression*)block;
4143 ast_expression *left, *right;
4144 size_t diff = afterend - from;
4145 size_t middle = from + diff/2;
4146 left = array_setter_node(parser, array, index, value, from, middle);
4147 right = array_setter_node(parser, array, index, value, middle, afterend);
4148 return array_accessor_split(parser, array, index, middle, left, right);
4152 static ast_expression *array_field_setter_node(
4161 lex_ctx ctx = ast_ctx(array);
4163 if (from+1 == afterend) {
4164 /* set this value */
4167 ast_entfield *entfield;
4168 ast_array_index *subscript;
4170 int assignop = type_storep_instr[value->expression.vtype];
4172 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4173 assignop = INSTR_STOREP_V;
4175 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4179 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4180 subscript->expression.vtype = TYPE_FIELD;
4182 entfield = ast_entfield_new_force(ctx,
4183 (ast_expression*)entity,
4184 (ast_expression*)subscript,
4185 (ast_expression*)subscript);
4187 ast_delete(subscript);
4191 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4193 ast_delete(entfield);
4197 block = ast_block_new(ctx);
4203 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4208 ret = ast_return_new(ctx, NULL);
4214 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4219 return (ast_expression*)block;
4221 ast_expression *left, *right;
4222 size_t diff = afterend - from;
4223 size_t middle = from + diff/2;
4224 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4225 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4226 return array_accessor_split(parser, array, index, middle, left, right);
4230 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4232 lex_ctx ctx = ast_ctx(array);
4234 if (from+1 == afterend) {
4236 ast_array_index *subscript;
4238 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4242 ret = ast_return_new(ctx, (ast_expression*)subscript);
4244 ast_delete(subscript);
4248 return (ast_expression*)ret;
4250 ast_expression *left, *right;
4251 size_t diff = afterend - from;
4252 size_t middle = from + diff/2;
4253 left = array_getter_node(parser, array, index, from, middle);
4254 right = array_getter_node(parser, array, index, middle, afterend);
4255 return array_accessor_split(parser, array, index, middle, left, right);
4259 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4261 ast_function *func = NULL;
4262 ast_value *fval = NULL;
4263 ast_block *body = NULL;
4265 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4267 parseerror(parser, "failed to create accessor function value");
4271 func = ast_function_new(ast_ctx(array), funcname, fval);
4274 parseerror(parser, "failed to create accessor function node");
4278 body = ast_block_new(ast_ctx(array));
4280 parseerror(parser, "failed to create block for array accessor");
4286 vec_push(func->blocks, body);
4289 vec_push(parser->accessors, fval);
4294 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4296 ast_value *index = NULL;
4297 ast_value *value = NULL;
4301 if (!ast_istype(array->expression.next, ast_value)) {
4302 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4306 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4308 func = fval->constval.vfunc;
4309 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4311 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4312 value = ast_value_copy((ast_value*)array->expression.next);
4314 if (!index || !value) {
4315 parseerror(parser, "failed to create locals for array accessor");
4318 (void)!ast_value_set_name(value, "value"); /* not important */
4319 vec_push(fval->expression.params, index);
4320 vec_push(fval->expression.params, value);
4322 array->setter = fval;
4325 if (index) ast_delete(index);
4326 if (value) ast_delete(value);
4332 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4334 ast_expression *root = NULL;
4335 root = array_setter_node(parser, array,
4336 array->setter->expression.params[0],
4337 array->setter->expression.params[1],
4338 0, array->expression.count);
4340 parseerror(parser, "failed to build accessor search tree");
4343 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4350 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4352 if (!parser_create_array_setter_proto(parser, array, funcname))
4354 return parser_create_array_setter_impl(parser, array);
4357 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4359 ast_expression *root = NULL;
4360 ast_value *entity = NULL;
4361 ast_value *index = NULL;
4362 ast_value *value = NULL;
4366 if (!ast_istype(array->expression.next, ast_value)) {
4367 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4371 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4373 func = fval->constval.vfunc;
4374 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4376 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4377 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4378 value = ast_value_copy((ast_value*)array->expression.next);
4379 if (!entity || !index || !value) {
4380 parseerror(parser, "failed to create locals for array accessor");
4383 (void)!ast_value_set_name(value, "value"); /* not important */
4384 vec_push(fval->expression.params, entity);
4385 vec_push(fval->expression.params, index);
4386 vec_push(fval->expression.params, value);
4388 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4390 parseerror(parser, "failed to build accessor search tree");
4394 array->setter = fval;
4395 return ast_block_add_expr(func->blocks[0], root);
4397 if (entity) ast_delete(entity);
4398 if (index) ast_delete(index);
4399 if (value) ast_delete(value);
4400 if (root) ast_delete(root);
4406 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4408 ast_value *index = NULL;
4412 /* NOTE: checking array->expression.next rather than elemtype since
4413 * for fields elemtype is a temporary fieldtype.
4415 if (!ast_istype(array->expression.next, ast_value)) {
4416 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4420 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4422 func = fval->constval.vfunc;
4423 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4425 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4428 parseerror(parser, "failed to create locals for array accessor");
4431 vec_push(fval->expression.params, index);
4433 array->getter = fval;
4436 if (index) ast_delete(index);
4442 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4444 ast_expression *root = NULL;
4446 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4448 parseerror(parser, "failed to build accessor search tree");
4451 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4458 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4460 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4462 return parser_create_array_getter_impl(parser, array);
4465 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4466 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4474 bool variadic = false;
4475 ast_value *varparam = NULL;
4476 char *argcounter = NULL;
4478 ctx = parser_ctx(parser);
4480 /* for the sake of less code we parse-in in this function */
4481 if (!parser_next(parser)) {
4482 parseerror(parser, "expected parameter list");
4488 /* parse variables until we hit a closing paren */
4489 while (parser->tok != ')') {
4491 /* there must be commas between them */
4492 if (parser->tok != ',') {
4493 parseerror(parser, "expected comma or end of parameter list");
4496 if (!parser_next(parser)) {
4497 parseerror(parser, "expected parameter");
4503 if (parser->tok == TOKEN_DOTS) {
4504 /* '...' indicates a varargs function */
4506 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4507 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4510 if (parser->tok == TOKEN_IDENT) {
4511 argcounter = util_strdup(parser_tokval(parser));
4512 if (!parser_next(parser) || parser->tok != ')') {
4513 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4520 /* for anything else just parse a typename */
4521 param = parse_typename(parser, NULL, NULL);
4524 vec_push(params, param);
4525 if (param->expression.vtype >= TYPE_VARIANT) {
4526 char tname[1024]; /* typename is reserved in C++ */
4527 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4528 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4531 /* type-restricted varargs */
4532 if (parser->tok == TOKEN_DOTS) {
4534 varparam = vec_last(params);
4536 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4537 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4540 if (parser->tok == TOKEN_IDENT) {
4541 argcounter = util_strdup(parser_tokval(parser));
4542 if (!parser_next(parser) || parser->tok != ')') {
4543 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4551 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4555 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
4556 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4559 if (!parser_next(parser)) {
4560 parseerror(parser, "parse error after typename");
4564 /* now turn 'var' into a function type */
4565 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4566 fval->expression.next = (ast_expression*)var;
4568 fval->expression.flags |= AST_FLAG_VARIADIC;
4571 var->expression.params = params;
4572 var->expression.varparam = (ast_expression*)varparam;
4573 var->argcounter = argcounter;
4582 for (i = 0; i < vec_size(params); ++i)
4583 ast_delete(params[i]);
4588 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4590 ast_expression *cexp;
4591 ast_value *cval, *tmp;
4594 ctx = parser_ctx(parser);
4596 if (!parser_next(parser)) {
4598 parseerror(parser, "expected array-size");
4602 cexp = parse_expression_leave(parser, true, false, false);
4604 if (!cexp || !ast_istype(cexp, ast_value)) {
4608 parseerror(parser, "expected array-size as constant positive integer");
4611 cval = (ast_value*)cexp;
4613 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4614 tmp->expression.next = (ast_expression*)var;
4617 if (cval->expression.vtype == TYPE_INTEGER)
4618 tmp->expression.count = cval->constval.vint;
4619 else if (cval->expression.vtype == TYPE_FLOAT)
4620 tmp->expression.count = cval->constval.vfloat;
4624 parseerror(parser, "array-size must be a positive integer constant");
4629 if (parser->tok != ']') {
4631 parseerror(parser, "expected ']' after array-size");
4634 if (!parser_next(parser)) {
4636 parseerror(parser, "error after parsing array size");
4642 /* Parse a complete typename.
4643 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4644 * but when parsing variables separated by comma
4645 * 'storebase' should point to where the base-type should be kept.
4646 * The base type makes up every bit of type information which comes *before* the
4649 * The following will be parsed in its entirety:
4651 * The 'basetype' in this case is 'void()'
4652 * and if there's a comma after it, say:
4654 * then the type-information 'void()' can be stored in 'storebase'
4656 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4658 ast_value *var, *tmp;
4661 const char *name = NULL;
4662 bool isfield = false;
4663 bool wasarray = false;
4664 size_t morefields = 0;
4666 ctx = parser_ctx(parser);
4668 /* types may start with a dot */
4669 if (parser->tok == '.') {
4671 /* if we parsed a dot we need a typename now */
4672 if (!parser_next(parser)) {
4673 parseerror(parser, "expected typename for field definition");
4677 /* Further dots are handled seperately because they won't be part of the
4680 while (parser->tok == '.') {
4682 if (!parser_next(parser)) {
4683 parseerror(parser, "expected typename for field definition");
4688 if (parser->tok == TOKEN_IDENT)
4689 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4690 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4691 parseerror(parser, "expected typename");
4695 /* generate the basic type value */
4696 if (cached_typedef) {
4697 var = ast_value_copy(cached_typedef);
4698 ast_value_set_name(var, "<type(from_def)>");
4700 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4702 for (; morefields; --morefields) {
4703 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4704 tmp->expression.next = (ast_expression*)var;
4708 /* do not yet turn into a field - remember:
4709 * .void() foo; is a field too
4710 * .void()() foo; is a function
4714 if (!parser_next(parser)) {
4716 parseerror(parser, "parse error after typename");
4720 /* an opening paren now starts the parameter-list of a function
4721 * this is where original-QC has parameter lists.
4722 * We allow a single parameter list here.
4723 * Much like fteqcc we don't allow `float()() x`
4725 if (parser->tok == '(') {
4726 var = parse_parameter_list(parser, var);
4731 /* store the base if requested */
4733 *storebase = ast_value_copy(var);
4735 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4736 tmp->expression.next = (ast_expression*)*storebase;
4741 /* there may be a name now */
4742 if (parser->tok == TOKEN_IDENT) {
4743 name = util_strdup(parser_tokval(parser));
4745 if (!parser_next(parser)) {
4747 parseerror(parser, "error after variable or field declaration");
4752 /* now this may be an array */
4753 if (parser->tok == '[') {
4755 var = parse_arraysize(parser, var);
4760 /* This is the point where we can turn it into a field */
4762 /* turn it into a field if desired */
4763 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4764 tmp->expression.next = (ast_expression*)var;
4768 /* now there may be function parens again */
4769 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4770 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4771 if (parser->tok == '(' && wasarray)
4772 parseerror(parser, "arrays as part of a return type is not supported");
4773 while (parser->tok == '(') {
4774 var = parse_parameter_list(parser, var);
4782 /* finally name it */
4784 if (!ast_value_set_name(var, name)) {
4786 parseerror(parser, "internal error: failed to set name");
4789 /* free the name, ast_value_set_name duplicates */
4796 static bool parse_typedef(parser_t *parser)
4798 ast_value *typevar, *oldtype;
4799 ast_expression *old;
4801 typevar = parse_typename(parser, NULL, NULL);
4806 if ( (old = parser_find_var(parser, typevar->name)) ) {
4807 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4808 " -> `%s` has been declared here: %s:%i",
4809 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4810 ast_delete(typevar);
4814 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4815 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4816 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4817 ast_delete(typevar);
4821 vec_push(parser->_typedefs, typevar);
4822 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4824 if (parser->tok != ';') {
4825 parseerror(parser, "expected semicolon after typedef");
4828 if (!parser_next(parser)) {
4829 parseerror(parser, "parse error after typedef");
4836 static const char *cvq_to_str(int cvq) {
4838 case CV_NONE: return "none";
4839 case CV_VAR: return "`var`";
4840 case CV_CONST: return "`const`";
4841 default: return "<INVALID>";
4845 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
4848 if (proto->cvq != var->cvq) {
4849 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
4850 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4851 parser->tok == '='))
4853 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
4854 "`%s` declared with different qualifiers: %s\n"
4855 " -> previous declaration here: %s:%i uses %s",
4856 var->name, cvq_to_str(var->cvq),
4857 ast_ctx(proto).file, ast_ctx(proto).line,
4858 cvq_to_str(proto->cvq));
4861 av = (var ->expression.flags & AST_FLAG_NORETURN);
4862 ao = (proto->expression.flags & AST_FLAG_NORETURN);
4864 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
4865 "`%s` declared with different attributes%s\n"
4866 " -> previous declaration here: %s:%i",
4867 var->name, (av ? ": noreturn" : ""),
4868 ast_ctx(proto).file, ast_ctx(proto).line,
4869 (ao ? ": noreturn" : ""));
4874 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)
4878 ast_expression *old;
4882 ast_value *basetype = NULL;
4884 bool isparam = false;
4885 bool isvector = false;
4886 bool cleanvar = true;
4887 bool wasarray = false;
4891 if (!localblock && is_static)
4892 parseerror(parser, "`static` qualifier is not supported in global scope");
4894 /* get the first complete variable */
4895 var = parse_typename(parser, &basetype, cached_typedef);
4898 ast_delete(basetype);
4906 /* Part 0: finish the type */
4907 if (parser->tok == '(') {
4908 if (opts.standard == COMPILER_QCC)
4909 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4910 var = parse_parameter_list(parser, var);
4916 /* we only allow 1-dimensional arrays */
4917 if (parser->tok == '[') {
4919 var = parse_arraysize(parser, var);
4925 if (parser->tok == '(' && wasarray) {
4926 parseerror(parser, "arrays as part of a return type is not supported");
4927 /* we'll still parse the type completely for now */
4929 /* for functions returning functions */
4930 while (parser->tok == '(') {
4931 if (opts.standard == COMPILER_QCC)
4932 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4933 var = parse_parameter_list(parser, var);
4940 var->cvq = qualifier;
4941 var->expression.flags |= qflags;
4942 if (var->expression.flags & AST_FLAG_DEPRECATED)
4943 var->desc = vstring;
4946 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4947 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4948 * is then filled with the previous definition and the parameter-names replaced.
4950 if (!strcmp(var->name, "nil")) {
4951 if (OPTS_FLAG(UNTYPED_NIL)) {
4952 if (!localblock || !OPTS_FLAG(PERMISSIVE))
4953 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
4955 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
4958 /* Deal with end_sys_ vars */
4960 if (!strcmp(var->name, "end_sys_globals")) {
4962 parser->crc_globals = vec_size(parser->globals);
4965 else if (!strcmp(var->name, "end_sys_fields")) {
4967 parser->crc_fields = vec_size(parser->fields);
4970 if (was_end && var->expression.vtype == TYPE_FIELD) {
4971 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4972 "global '%s' hint should not be a field",
4973 parser_tokval(parser)))
4980 if (!nofields && var->expression.vtype == TYPE_FIELD)
4982 /* deal with field declarations */
4983 old = parser_find_field(parser, var->name);
4985 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4986 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4995 parseerror(parser, "field `%s` already declared here: %s:%i",
4996 var->name, ast_ctx(old).file, ast_ctx(old).line);
5001 if ((opts.standard == COMPILER_QCC || opts.standard == COMPILER_FTEQCC) &&
5002 (old = parser_find_global(parser, var->name)))
5004 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5005 parseerror(parser, "field `%s` already declared here: %s:%i",
5006 var->name, ast_ctx(old).file, ast_ctx(old).line);
5013 /* deal with other globals */
5014 old = parser_find_global(parser, var->name);
5015 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5017 /* This is a function which had a prototype */
5018 if (!ast_istype(old, ast_value)) {
5019 parseerror(parser, "internal error: prototype is not an ast_value");
5023 proto = (ast_value*)old;
5024 proto->desc = var->desc;
5025 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5026 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5028 ast_ctx(proto).file, ast_ctx(proto).line);
5032 /* we need the new parameter-names */
5033 for (i = 0; i < vec_size(proto->expression.params); ++i)
5034 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5035 if (!parser_check_qualifiers(parser, var, proto)) {
5042 proto->expression.flags |= var->expression.flags;
5050 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5051 "global `%s` already declared here: %s:%i",
5052 var->name, ast_ctx(old).file, ast_ctx(old).line))
5057 proto = (ast_value*)old;
5058 if (!ast_istype(old, ast_value)) {
5059 parseerror(parser, "internal error: not an ast_value");
5064 if (!parser_check_qualifiers(parser, var, proto)) {
5069 proto->expression.flags |= var->expression.flags;
5073 if (opts.standard == COMPILER_QCC &&
5074 (old = parser_find_field(parser, var->name)))
5076 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5077 parseerror(parser, "global `%s` already declared here: %s:%i",
5078 var->name, ast_ctx(old).file, ast_ctx(old).line);
5085 else /* it's not a global */
5087 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5088 if (old && !isparam) {
5089 parseerror(parser, "local `%s` already declared here: %s:%i",
5090 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5094 old = parser_find_local(parser, var->name, 0, &isparam);
5095 if (old && isparam) {
5096 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5097 "local `%s` is shadowing a parameter", var->name))
5099 parseerror(parser, "local `%s` already declared here: %s:%i",
5100 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5104 if (opts.standard != COMPILER_GMQCC) {
5112 /* in a noref section we simply bump the usecount */
5113 if (noref || parser->noref)
5117 * Create the global/local, and deal with vector types.
5120 if (var->expression.vtype == TYPE_VECTOR)
5122 else if (var->expression.vtype == TYPE_FIELD &&
5123 var->expression.next->expression.vtype == TYPE_VECTOR)
5127 if (!create_vector_members(var, me)) {
5134 /* deal with global variables, fields, functions */
5135 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5136 var->isfield = true;
5137 vec_push(parser->fields, (ast_expression*)var);
5138 util_htset(parser->htfields, var->name, var);
5140 for (i = 0; i < 3; ++i) {
5141 vec_push(parser->fields, (ast_expression*)me[i]);
5142 util_htset(parser->htfields, me[i]->name, me[i]);
5147 parser_addglobal(parser, var->name, (ast_expression*)var);
5149 for (i = 0; i < 3; ++i) {
5150 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5156 /* a static adds itself to be generated like any other global
5157 * but is added to the local namespace instead
5159 char *defname = NULL;
5160 size_t prefix_len, ln;
5162 ln = strlen(parser->function->name);
5163 vec_append(defname, ln, parser->function->name);
5165 vec_append(defname, 2, "::");
5166 /* remember the length up to here */
5167 prefix_len = vec_size(defname);
5169 /* Add it to the local scope */
5170 util_htset(vec_last(parser->variables), var->name, (void*)var);
5174 vec_last(parser->correct_variables),
5175 &vec_last(parser->correct_variables_score),
5179 /* now rename the global */
5180 ln = strlen(var->name);
5181 vec_append(defname, ln, var->name);
5182 ast_value_set_name(var, defname);
5184 /* push it to the to-be-generated globals */
5185 vec_push(parser->globals, (ast_expression*)var);
5187 /* same game for the vector members */
5189 for (i = 0; i < 3; ++i) {
5190 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5194 vec_last(parser->correct_variables),
5195 &vec_last(parser->correct_variables_score),
5199 vec_shrinkto(defname, prefix_len);
5200 ln = strlen(me[i]->name);
5201 vec_append(defname, ln, me[i]->name);
5202 ast_member_set_name(me[i], defname);
5204 vec_push(parser->globals, (ast_expression*)me[i]);
5209 vec_push(localblock->locals, var);
5210 parser_addlocal(parser, var->name, (ast_expression*)var);
5212 for (i = 0; i < 3; ++i) {
5213 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5214 ast_block_collect(localblock, (ast_expression*)me[i]);
5220 me[0] = me[1] = me[2] = NULL;
5225 if (var->expression.vtype == TYPE_ARRAY) {
5227 snprintf(name, sizeof(name), "%s##SET", var->name);
5228 if (!parser_create_array_setter(parser, var, name))
5230 snprintf(name, sizeof(name), "%s##GET", var->name);
5231 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5234 else if (!localblock && !nofields &&
5235 var->expression.vtype == TYPE_FIELD &&
5236 var->expression.next->expression.vtype == TYPE_ARRAY)
5239 ast_expression *telem;
5241 ast_value *array = (ast_value*)var->expression.next;
5243 if (!ast_istype(var->expression.next, ast_value)) {
5244 parseerror(parser, "internal error: field element type must be an ast_value");
5248 snprintf(name, sizeof(name), "%s##SETF", var->name);
5249 if (!parser_create_array_field_setter(parser, array, name))
5252 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5253 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5254 tfield->expression.next = telem;
5255 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5256 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5264 if (parser->tok == ';') {
5265 ast_delete(basetype);
5266 if (!parser_next(parser)) {
5267 parseerror(parser, "error after variable declaration");
5273 if (parser->tok == ',')
5277 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5280 parseerror(parser, "missing comma or semicolon while parsing variables");
5284 if (localblock && opts.standard == COMPILER_QCC) {
5285 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5286 "initializing expression turns variable `%s` into a constant in this standard",
5293 if (parser->tok != '{') {
5294 if (parser->tok != '=') {
5295 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5299 if (!parser_next(parser)) {
5300 parseerror(parser, "error parsing initializer");
5304 else if (opts.standard == COMPILER_QCC) {
5305 parseerror(parser, "expected '=' before function body in this standard");
5308 if (parser->tok == '#') {
5309 ast_function *func = NULL;
5312 parseerror(parser, "cannot declare builtins within functions");
5315 if (var->expression.vtype != TYPE_FUNCTION) {
5316 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5319 if (!parser_next(parser)) {
5320 parseerror(parser, "expected builtin number");
5323 if (parser->tok != TOKEN_INTCONST) {
5324 parseerror(parser, "builtin number must be an integer constant");
5327 if (parser_token(parser)->constval.i < 0) {
5328 parseerror(parser, "builtin number must be an integer greater than zero");
5332 if (var->hasvalue) {
5333 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5334 "builtin `%s` has already been defined\n"
5335 " -> previous declaration here: %s:%i",
5336 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5340 func = ast_function_new(ast_ctx(var), var->name, var);
5342 parseerror(parser, "failed to allocate function for `%s`", var->name);
5345 vec_push(parser->functions, func);
5347 func->builtin = -parser_token(parser)->constval.i-1;
5350 if (!parser_next(parser)) {
5351 parseerror(parser, "expected comma or semicolon");
5353 ast_function_delete(func);
5354 var->constval.vfunc = NULL;
5358 else if (parser->tok == '{' || parser->tok == '[')
5361 parseerror(parser, "cannot declare functions within functions");
5366 ast_ctx(proto) = parser_ctx(parser);
5368 if (!parse_function_body(parser, var))
5370 ast_delete(basetype);
5371 for (i = 0; i < vec_size(parser->gotos); ++i)
5372 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5373 vec_free(parser->gotos);
5374 vec_free(parser->labels);
5377 ast_expression *cexp;
5380 cexp = parse_expression_leave(parser, true, false, false);
5385 cval = (ast_value*)cexp;
5386 if (cval != parser->nil &&
5387 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5390 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5394 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5395 qualifier != CV_VAR)
5397 var->cvq = CV_CONST;
5399 if (cval == parser->nil)
5400 var->expression.flags |= AST_FLAG_INITIALIZED;
5403 var->hasvalue = true;
5404 if (cval->expression.vtype == TYPE_STRING)
5405 var->constval.vstring = parser_strdup(cval->constval.vstring);
5406 else if (cval->expression.vtype == TYPE_FIELD)
5407 var->constval.vfield = cval;
5409 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5415 shunt sy = { NULL, NULL, NULL, NULL };
5418 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5419 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5420 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5421 if (!parser_sy_apply_operator(parser, &sy))
5424 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5425 parseerror(parser, "internal error: leaked operands");
5426 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5436 if (parser->tok == ',') {
5437 if (!parser_next(parser)) {
5438 parseerror(parser, "expected another variable");
5442 if (parser->tok != TOKEN_IDENT) {
5443 parseerror(parser, "expected another variable");
5446 var = ast_value_copy(basetype);
5448 ast_value_set_name(var, parser_tokval(parser));
5449 if (!parser_next(parser)) {
5450 parseerror(parser, "error parsing variable declaration");
5456 if (parser->tok != ';') {
5457 parseerror(parser, "missing semicolon after variables");
5461 if (!parser_next(parser)) {
5462 parseerror(parser, "parse error after variable declaration");
5466 ast_delete(basetype);
5470 if (cleanvar && var)
5472 ast_delete(basetype);
5476 ast_delete(basetype);
5477 if (cleanvar && var)
5479 if (me[0]) ast_member_delete(me[0]);
5480 if (me[1]) ast_member_delete(me[1]);
5481 if (me[2]) ast_member_delete(me[2]);
5485 static bool parser_global_statement(parser_t *parser)
5489 bool is_static = false;
5490 uint32_t qflags = 0;
5491 ast_value *istype = NULL;
5492 char *vstring = NULL;
5494 if (parser->tok == TOKEN_IDENT)
5495 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5497 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5499 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5501 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5503 if (cvq == CV_WRONG)
5505 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5507 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5509 return parse_enum(parser);
5511 else if (parser->tok == TOKEN_KEYWORD)
5513 if (!strcmp(parser_tokval(parser), "typedef")) {
5514 if (!parser_next(parser)) {
5515 parseerror(parser, "expected type definition after 'typedef'");
5518 return parse_typedef(parser);
5520 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5523 else if (parser->tok == '#')
5525 return parse_pragma(parser);
5527 else if (parser->tok == '$')
5529 if (!parser_next(parser)) {
5530 parseerror(parser, "parse error");
5536 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
5542 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5544 return util_crc16(old, str, strlen(str));
5547 static void progdefs_crc_file(const char *str)
5549 /* write to progdefs.h here */
5553 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5555 old = progdefs_crc_sum(old, str);
5556 progdefs_crc_file(str);
5560 static void generate_checksum(parser_t *parser)
5562 uint16_t crc = 0xFFFF;
5566 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5567 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5569 progdefs_crc_file("\tint\tpad;\n");
5570 progdefs_crc_file("\tint\tofs_return[3];\n");
5571 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5572 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5573 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5574 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5575 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5576 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5577 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5578 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5580 for (i = 0; i < parser->crc_globals; ++i) {
5581 if (!ast_istype(parser->globals[i], ast_value))
5583 value = (ast_value*)(parser->globals[i]);
5584 switch (value->expression.vtype) {
5585 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5586 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5587 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5588 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5590 crc = progdefs_crc_both(crc, "\tint\t");
5593 crc = progdefs_crc_both(crc, value->name);
5594 crc = progdefs_crc_both(crc, ";\n");
5596 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5597 for (i = 0; i < parser->crc_fields; ++i) {
5598 if (!ast_istype(parser->fields[i], ast_value))
5600 value = (ast_value*)(parser->fields[i]);
5601 switch (value->expression.next->expression.vtype) {
5602 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5603 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5604 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5605 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5607 crc = progdefs_crc_both(crc, "\tint\t");
5610 crc = progdefs_crc_both(crc, value->name);
5611 crc = progdefs_crc_both(crc, ";\n");
5613 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5618 static parser_t *parser;
5625 parser = (parser_t*)mem_a(sizeof(parser_t));
5629 memset(parser, 0, sizeof(*parser));
5631 for (i = 0; i < operator_count; ++i) {
5632 if (operators[i].id == opid1('=')) {
5633 parser->assign_op = operators+i;
5637 if (!parser->assign_op) {
5638 printf("internal error: initializing parser: failed to find assign operator\n");
5643 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5644 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5645 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5646 vec_push(parser->_blocktypedefs, 0);
5649 vec_push(parser->correct_variables, correct_trie_new());
5650 vec_push(parser->correct_variables_score, NULL);
5652 empty_ctx.file = "<internal>";
5654 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5655 parser->nil->cvq = CV_CONST;
5656 if (OPTS_FLAG(UNTYPED_NIL))
5657 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5659 parser->max_param_count = 1;
5661 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5662 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5663 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5665 if (opts.add_info) {
5666 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5667 parser->reserved_version->cvq = CV_CONST;
5668 parser->reserved_version->hasvalue = true;
5669 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5670 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5672 parser->reserved_version = NULL;
5677 bool parser_compile()
5679 /* initial lexer/parser state */
5680 parser->lex->flags.noops = true;
5682 if (parser_next(parser))
5684 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5686 if (!parser_global_statement(parser)) {
5687 if (parser->tok == TOKEN_EOF)
5688 parseerror(parser, "unexpected eof");
5689 else if (compile_errors)
5690 parseerror(parser, "there have been errors, bailing out");
5691 lex_close(parser->lex);
5697 parseerror(parser, "parse error");
5698 lex_close(parser->lex);
5703 lex_close(parser->lex);
5706 return !compile_errors;
5709 bool parser_compile_file(const char *filename)
5711 parser->lex = lex_open(filename);
5713 con_err("failed to open file \"%s\"\n", filename);
5716 return parser_compile();
5719 bool parser_compile_string(const char *name, const char *str, size_t len)
5721 parser->lex = lex_open_string(str, len, name);
5723 con_err("failed to create lexer for string \"%s\"\n", name);
5726 return parser_compile();
5729 void parser_cleanup()
5732 for (i = 0; i < vec_size(parser->accessors); ++i) {
5733 ast_delete(parser->accessors[i]->constval.vfunc);
5734 parser->accessors[i]->constval.vfunc = NULL;
5735 ast_delete(parser->accessors[i]);
5737 for (i = 0; i < vec_size(parser->functions); ++i) {
5738 ast_delete(parser->functions[i]);
5740 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5741 ast_delete(parser->imm_vector[i]);
5743 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5744 ast_delete(parser->imm_string[i]);
5746 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5747 ast_delete(parser->imm_float[i]);
5749 for (i = 0; i < vec_size(parser->fields); ++i) {
5750 ast_delete(parser->fields[i]);
5752 for (i = 0; i < vec_size(parser->globals); ++i) {
5753 ast_delete(parser->globals[i]);
5755 vec_free(parser->accessors);
5756 vec_free(parser->functions);
5757 vec_free(parser->imm_vector);
5758 vec_free(parser->imm_string);
5759 vec_free(parser->imm_float);
5760 vec_free(parser->globals);
5761 vec_free(parser->fields);
5763 for (i = 0; i < vec_size(parser->variables); ++i)
5764 util_htdel(parser->variables[i]);
5765 vec_free(parser->variables);
5766 vec_free(parser->_blocklocals);
5767 vec_free(parser->_locals);
5770 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
5771 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
5773 vec_free(parser->correct_variables);
5774 vec_free(parser->correct_variables_score);
5777 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5778 ast_delete(parser->_typedefs[i]);
5779 vec_free(parser->_typedefs);
5780 for (i = 0; i < vec_size(parser->typedefs); ++i)
5781 util_htdel(parser->typedefs[i]);
5782 vec_free(parser->typedefs);
5783 vec_free(parser->_blocktypedefs);
5785 vec_free(parser->_block_ctx);
5787 vec_free(parser->labels);
5788 vec_free(parser->gotos);
5789 vec_free(parser->breaks);
5790 vec_free(parser->continues);
5792 ast_value_delete(parser->nil);
5794 ast_value_delete(parser->const_vec[0]);
5795 ast_value_delete(parser->const_vec[1]);
5796 ast_value_delete(parser->const_vec[2]);
5801 bool parser_finish(const char *output)
5807 if (compile_errors) {
5808 con_out("*** there were compile errors\n");
5812 ir = ir_builder_new("gmqcc_out");
5814 con_out("failed to allocate builder\n");
5818 for (i = 0; i < vec_size(parser->fields); ++i) {
5821 if (!ast_istype(parser->fields[i], ast_value))
5823 field = (ast_value*)parser->fields[i];
5824 hasvalue = field->hasvalue;
5825 field->hasvalue = false;
5826 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5827 con_out("failed to generate field %s\n", field->name);
5828 ir_builder_delete(ir);
5833 ast_expression *subtype;
5834 field->hasvalue = true;
5835 subtype = field->expression.next;
5836 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5837 if (subtype->expression.vtype == TYPE_FIELD)
5838 ifld->fieldtype = subtype->expression.next->expression.vtype;
5839 else if (subtype->expression.vtype == TYPE_FUNCTION)
5840 ifld->outtype = subtype->expression.next->expression.vtype;
5841 (void)!ir_value_set_field(field->ir_v, ifld);
5844 for (i = 0; i < vec_size(parser->globals); ++i) {
5846 if (!ast_istype(parser->globals[i], ast_value))
5848 asvalue = (ast_value*)(parser->globals[i]);
5849 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5850 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5851 "unused global: `%s`", asvalue->name);
5853 if (!ast_global_codegen(asvalue, ir, false)) {
5854 con_out("failed to generate global %s\n", asvalue->name);
5855 ir_builder_delete(ir);
5859 /* Build function vararg accessor ast tree now before generating
5860 * immediates, because the accessors may add new immediates
5862 for (i = 0; i < vec_size(parser->functions); ++i) {
5863 ast_function *f = parser->functions[i];
5865 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
5866 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
5867 if (!parser_create_array_setter_impl(parser, f->varargs)) {
5868 con_out("failed to generate vararg setter for %s\n", f->name);
5869 ir_builder_delete(ir);
5872 if (!parser_create_array_getter_impl(parser, f->varargs)) {
5873 con_out("failed to generate vararg getter for %s\n", f->name);
5874 ir_builder_delete(ir);
5878 ast_delete(f->varargs);
5883 /* Now we can generate immediates */
5884 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5885 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5886 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5887 ir_builder_delete(ir);
5891 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5892 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5893 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5894 ir_builder_delete(ir);
5898 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5899 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5900 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5901 ir_builder_delete(ir);
5905 for (i = 0; i < vec_size(parser->globals); ++i) {
5907 if (!ast_istype(parser->globals[i], ast_value))
5909 asvalue = (ast_value*)(parser->globals[i]);
5910 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
5912 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
5913 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
5914 "uninitialized constant: `%s`",
5916 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
5917 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
5918 "uninitialized global: `%s`",
5921 if (!ast_generate_accessors(asvalue, ir)) {
5922 ir_builder_delete(ir);
5926 for (i = 0; i < vec_size(parser->fields); ++i) {
5928 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5930 if (!ast_istype((ast_expression*)asvalue, ast_value))
5932 if (asvalue->expression.vtype != TYPE_ARRAY)
5934 if (!ast_generate_accessors(asvalue, ir)) {
5935 ir_builder_delete(ir);
5939 if (parser->reserved_version &&
5940 !ast_global_codegen(parser->reserved_version, ir, false))
5942 con_out("failed to generate reserved::version");
5943 ir_builder_delete(ir);
5946 for (i = 0; i < vec_size(parser->functions); ++i) {
5947 ast_function *f = parser->functions[i];
5948 if (!ast_function_codegen(f, ir)) {
5949 con_out("failed to generate function %s\n", f->name);
5950 ir_builder_delete(ir);
5955 ir_builder_dump(ir, con_out);
5956 for (i = 0; i < vec_size(parser->functions); ++i) {
5957 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5958 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5959 ir_builder_delete(ir);
5964 if (compile_Werrors) {
5965 con_out("*** there were warnings treated as errors\n");
5966 compile_show_werrors();
5972 ir_builder_dump(ir, con_out);
5974 generate_checksum(parser);
5976 if (!ir_builder_generate(ir, output)) {
5977 con_out("*** failed to generate output file\n");
5978 ir_builder_delete(ir);
5983 ir_builder_delete(ir);