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
32 /* beginning of locals */
33 #define PARSER_HT_LOCALS 2
35 #define PARSER_HT_SIZE 128
36 #define TYPEDEF_HT_SIZE 16
38 typedef struct parser_s {
42 ast_expression **globals;
43 ast_expression **fields;
44 ast_function **functions;
45 ast_value **imm_float;
46 ast_value **imm_string;
47 ast_value **imm_vector;
52 /* must be deleted first, they reference immediates and values */
53 ast_value **accessors;
55 ast_value *imm_float_zero;
56 ast_value *imm_float_one;
57 ast_value *imm_float_neg_one;
59 ast_value *imm_vector_zero;
62 ast_value *reserved_version;
67 ast_function *function;
70 /* All the labels the function defined...
71 * Should they be in ast_function instead?
76 const char **continues;
78 /* A list of hashtables for each scope */
84 /* same as above but for the spelling corrector */
85 correct_trie_t **correct_variables;
86 size_t ***correct_variables_score; /* vector of vector of size_t* */
88 /* not to be used directly, we use the hash table */
89 ast_expression **_locals;
91 ast_value **_typedefs;
92 size_t *_blocktypedefs;
95 /* we store the '=' operator info */
96 const oper_info *assign_op;
99 ast_value *const_vec[3];
104 /* collected information */
105 size_t max_param_count;
108 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
110 static void parser_enterblock(parser_t *parser);
111 static bool parser_leaveblock(parser_t *parser);
112 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
113 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
114 static bool parse_typedef(parser_t *parser);
115 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);
116 static ast_block* parse_block(parser_t *parser);
117 static bool parse_block_into(parser_t *parser, ast_block *block);
118 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
119 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
120 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
121 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
122 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
123 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
124 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
126 static void parseerror(parser_t *parser, const char *fmt, ...)
130 vcompile_error(parser->lex->tok.ctx, fmt, ap);
134 /* returns true if it counts as an error */
135 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
140 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
145 /**********************************************************************
146 * some maths used for constant folding
149 vector vec3_add(vector a, vector b)
158 vector vec3_sub(vector a, vector b)
167 qcfloat vec3_mulvv(vector a, vector b)
169 return (a.x * b.x + a.y * b.y + a.z * b.z);
172 vector vec3_mulvf(vector a, float b)
181 /**********************************************************************
185 bool parser_next(parser_t *parser)
187 /* lex_do kills the previous token */
188 parser->tok = lex_do(parser->lex);
189 if (parser->tok == TOKEN_EOF)
191 if (parser->tok >= TOKEN_ERROR) {
192 parseerror(parser, "lex error");
198 #define parser_tokval(p) ((p)->lex->tok.value)
199 #define parser_token(p) (&((p)->lex->tok))
200 #define parser_ctx(p) ((p)->lex->tok.ctx)
202 static ast_value* parser_const_float(parser_t *parser, double d)
207 for (i = 0; i < vec_size(parser->imm_float); ++i) {
208 const double compare = parser->imm_float[i]->constval.vfloat;
209 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
210 return parser->imm_float[i];
213 ctx = parser_ctx(parser);
215 memset(&ctx, 0, sizeof(ctx));
217 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
219 out->hasvalue = true;
220 out->constval.vfloat = d;
221 vec_push(parser->imm_float, out);
225 static ast_value* parser_const_float_0(parser_t *parser)
227 if (!parser->imm_float_zero)
228 parser->imm_float_zero = parser_const_float(parser, 0);
229 return parser->imm_float_zero;
232 static ast_value* parser_const_float_neg1(parser_t *parser) {
233 if (!parser->imm_float_neg_one)
234 parser->imm_float_neg_one = parser_const_float(parser, -1);
235 return parser->imm_float_neg_one;
238 static ast_value* parser_const_float_1(parser_t *parser)
240 if (!parser->imm_float_one)
241 parser->imm_float_one = parser_const_float(parser, 1);
242 return parser->imm_float_one;
245 static char *parser_strdup(const char *str)
248 /* actually dup empty strings */
249 char *out = (char*)mem_a(1);
253 return util_strdup(str);
256 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
258 size_t hash = util_hthash(parser->ht_imm_string, str);
260 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
261 if (dotranslate && out->name[0] == '#') {
263 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
264 ast_value_set_name(out, name);
269 for (i = 0; i < vec_size(parser->imm_string); ++i) {
270 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
271 return parser->imm_string[i];
276 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
277 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
279 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
281 out->hasvalue = true;
282 out->constval.vstring = parser_strdup(str);
283 vec_push(parser->imm_string, out);
284 util_htseth(parser->ht_imm_string, str, hash, out);
288 static ast_value* parser_const_vector(parser_t *parser, vector v)
292 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
293 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
294 return parser->imm_vector[i];
296 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
298 out->hasvalue = true;
299 out->constval.vvec = v;
300 vec_push(parser->imm_vector, out);
304 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
310 return parser_const_vector(parser, v);
313 static ast_value* parser_const_vector_0(parser_t *parser)
315 if (!parser->imm_vector_zero)
316 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
317 return parser->imm_vector_zero;
320 static ast_expression* parser_find_field(parser_t *parser, const char *name)
322 return ( ast_expression*)util_htget(parser->htfields, name);
325 static ast_expression* parser_find_label(parser_t *parser, const char *name)
328 for(i = 0; i < vec_size(parser->labels); i++)
329 if (!strcmp(parser->labels[i]->name, name))
330 return (ast_expression*)parser->labels[i];
334 static ast_expression* parser_find_global(parser_t *parser, const char *name)
336 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
339 return (ast_expression*)util_htget(parser->htglobals, name);
342 static ast_expression* parser_find_param(parser_t *parser, const char *name)
346 if (!parser->function)
348 fun = parser->function->vtype;
349 for (i = 0; i < vec_size(fun->expression.params); ++i) {
350 if (!strcmp(fun->expression.params[i]->name, name))
351 return (ast_expression*)(fun->expression.params[i]);
356 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
361 hash = util_hthash(parser->htglobals, name);
364 for (i = vec_size(parser->variables); i > upto;) {
366 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
370 return parser_find_param(parser, name);
373 static ast_expression* parser_find_var(parser_t *parser, const char *name)
377 v = parser_find_local(parser, name, 0, &dummy);
378 if (!v) v = parser_find_global(parser, name);
382 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
386 hash = util_hthash(parser->typedefs[0], name);
388 for (i = vec_size(parser->typedefs); i > upto;) {
390 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
396 /* include intrinsics */
401 size_t etype; /* 0 = expression, others are operators */
405 ast_block *block; /* for commas and function calls */
424 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
435 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
439 e.out = (ast_expression*)v;
446 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
448 e.etype = 1 + (op - operators);
457 static sy_elem syparen(lex_ctx ctx, size_t off) {
468 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
469 * so we need to rotate it to become ent.(foo[n]).
471 static bool rotate_entfield_array_index_nodes(ast_expression **out)
473 ast_array_index *index, *oldindex;
474 ast_entfield *entfield;
478 ast_expression *entity;
480 lex_ctx ctx = ast_ctx(*out);
482 if (!ast_istype(*out, ast_array_index))
484 index = (ast_array_index*)*out;
486 if (!ast_istype(index->array, ast_entfield))
488 entfield = (ast_entfield*)index->array;
490 if (!ast_istype(entfield->field, ast_value))
492 field = (ast_value*)entfield->field;
495 entity = entfield->entity;
499 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
500 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
501 *out = (ast_expression*)entfield;
503 oldindex->array = NULL;
504 oldindex->index = NULL;
505 ast_delete(oldindex);
510 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
512 switch (v->expression.vtype) {
514 return !!v->constval.vfloat;
516 return !!v->constval.vint;
518 if (OPTS_FLAG(CORRECT_LOGIC))
519 return v->constval.vvec.x &&
520 v->constval.vvec.y &&
523 return !!(v->constval.vvec.x);
525 if (!v->constval.vstring)
527 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
529 return !!v->constval.vstring[0];
531 compile_error(ctx, "internal error: immediate_is_true on invalid type");
532 return !!v->constval.vfunc;
536 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
540 ast_expression *out = NULL;
541 ast_expression *exprs[3];
542 ast_block *blocks[3];
543 ast_value *asvalue[3];
544 ast_binstore *asbinstore;
545 size_t i, assignop, addop, subop;
546 qcint generated_op = 0;
551 if (!vec_size(sy->ops)) {
552 parseerror(parser, "internal error: missing operator");
556 if (vec_last(sy->ops).isparen) {
557 parseerror(parser, "unmatched parenthesis");
561 op = &operators[vec_last(sy->ops).etype - 1];
562 ctx = vec_last(sy->ops).ctx;
564 if (vec_size(sy->out) < op->operands) {
565 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
566 op->op, (int)op->id);
570 vec_shrinkby(sy->ops, 1);
572 /* op(:?) has no input and no output */
576 vec_shrinkby(sy->out, op->operands);
577 for (i = 0; i < op->operands; ++i) {
578 exprs[i] = sy->out[vec_size(sy->out)+i].out;
579 blocks[i] = sy->out[vec_size(sy->out)+i].block;
580 asvalue[i] = (ast_value*)exprs[i];
582 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
583 !(i != 0 && op->id == opid2('?',':')) &&
584 !(i == 1 && op->id == opid1('.')))
586 if (ast_istype(exprs[i], ast_label))
587 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
589 compile_error(ast_ctx(exprs[i]), "not an expression");
590 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
594 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
595 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
599 #define NotSameType(T) \
600 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
601 exprs[0]->expression.vtype != T)
602 #define CanConstFold1(A) \
603 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
604 (A)->expression.vtype != TYPE_FUNCTION)
605 #define CanConstFold(A, B) \
606 (CanConstFold1(A) && CanConstFold1(B))
607 #define ConstV(i) (asvalue[(i)]->constval.vvec)
608 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
609 #define ConstS(i) (asvalue[(i)]->constval.vstring)
613 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
617 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
618 exprs[1]->expression.vtype == TYPE_NOEXPR)
620 if (exprs[1] == (ast_expression*)parser->const_vec[0])
621 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
622 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
623 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
624 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
625 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
627 compile_error(ctx, "access to invalid vector component");
631 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
632 if (exprs[1]->expression.vtype != TYPE_FIELD) {
633 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
636 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
638 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
639 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
643 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
649 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
650 !(exprs[0]->expression.vtype == TYPE_FIELD &&
651 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
653 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
654 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
657 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
658 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
659 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
662 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
663 if (rotate_entfield_array_index_nodes(&out))
666 /* This is not broken in fteqcc anymore */
667 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
668 /* this error doesn't need to make us bail out */
669 (void)!parsewarning(parser, WARN_EXTENSIONS,
670 "accessing array-field members of an entity without parenthesis\n"
671 " -> this is an extension from -std=gmqcc");
678 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
679 vec_push(sy->out, syexp(ctx, exprs[0]));
680 vec_push(sy->out, syexp(ctx, exprs[1]));
681 vec_last(sy->argc)++;
685 if (!ast_block_add_expr(blocks[0], exprs[1]))
688 blocks[0] = ast_block_new(ctx);
689 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
690 !ast_block_add_expr(blocks[0], exprs[1]))
695 ast_block_set_type(blocks[0], exprs[1]);
697 vec_push(sy->out, syblock(ctx, blocks[0]));
704 switch (exprs[0]->expression.vtype) {
706 if (CanConstFold1(exprs[0]))
707 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
709 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
710 (ast_expression*)parser_const_float_0(parser),
714 if (CanConstFold1(exprs[0]))
715 out = (ast_expression*)parser_const_vector_f(parser,
716 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
718 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
719 (ast_expression*)parser_const_vector_0(parser),
723 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
724 type_name[exprs[0]->expression.vtype]);
730 switch (exprs[0]->expression.vtype) {
732 if (CanConstFold1(exprs[0]))
733 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
735 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
738 if (CanConstFold1(exprs[0]))
739 out = (ast_expression*)parser_const_float(parser,
740 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
742 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
745 if (CanConstFold1(exprs[0])) {
746 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
747 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
749 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
751 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
752 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
754 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
757 /* we don't constant-fold NOT for these types */
759 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
762 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
765 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
766 type_name[exprs[0]->expression.vtype]);
772 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
773 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
775 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
776 type_name[exprs[0]->expression.vtype],
777 type_name[exprs[1]->expression.vtype]);
780 switch (exprs[0]->expression.vtype) {
782 if (CanConstFold(exprs[0], exprs[1]))
784 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
787 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
790 if (CanConstFold(exprs[0], exprs[1]))
791 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
793 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
796 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
797 type_name[exprs[0]->expression.vtype],
798 type_name[exprs[1]->expression.vtype]);
803 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
804 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
806 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
807 type_name[exprs[1]->expression.vtype],
808 type_name[exprs[0]->expression.vtype]);
811 switch (exprs[0]->expression.vtype) {
813 if (CanConstFold(exprs[0], exprs[1]))
814 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
816 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
819 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
825 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
826 type_name[exprs[1]->expression.vtype],
827 type_name[exprs[0]->expression.vtype]);
832 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
833 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
834 exprs[1]->expression.vtype == TYPE_FLOAT) &&
835 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
836 exprs[0]->expression.vtype == TYPE_FLOAT)
839 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
840 type_name[exprs[1]->expression.vtype],
841 type_name[exprs[0]->expression.vtype]);
844 switch (exprs[0]->expression.vtype) {
846 if (exprs[1]->expression.vtype == TYPE_VECTOR)
848 if (CanConstFold(exprs[0], exprs[1]))
849 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
851 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
855 if (CanConstFold(exprs[0], exprs[1]))
856 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
858 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
862 if (exprs[1]->expression.vtype == TYPE_FLOAT)
864 if (CanConstFold(exprs[0], exprs[1]))
865 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
867 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
871 if (CanConstFold(exprs[0], exprs[1]))
872 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
873 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
874 vector vec = ConstV(0);
875 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
876 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
877 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
878 out->expression.node.keep = false;
879 ((ast_member*)out)->rvalue = true;
881 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
883 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
884 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
885 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
886 out->expression.node.keep = false;
887 ((ast_member*)out)->rvalue = true;
889 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
891 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
892 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
893 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
894 out->expression.node.keep = false;
895 ((ast_member*)out)->rvalue = true;
897 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
900 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
902 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
903 vector vec = ConstV(1);
904 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
905 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
906 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
907 out->expression.node.keep = false;
908 ((ast_member*)out)->rvalue = true;
910 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
912 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
913 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
914 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
915 out->expression.node.keep = false;
916 ((ast_member*)out)->rvalue = true;
918 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
920 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
921 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
922 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
923 out->expression.node.keep = false;
924 ((ast_member*)out)->rvalue = true;
926 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
929 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
932 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
936 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
937 type_name[exprs[1]->expression.vtype],
938 type_name[exprs[0]->expression.vtype]);
943 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
944 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
945 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
946 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
949 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
950 if (CanConstFold(exprs[0], exprs[1]))
951 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
953 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
955 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
956 if (CanConstFold(exprs[0], exprs[1]))
957 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
959 if (CanConstFold1(exprs[1])) {
960 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
962 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
963 (ast_expression*)parser_const_float_1(parser),
967 compile_error(ctx, "internal error: failed to generate division");
970 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
975 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
976 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
977 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
983 if (NotSameType(TYPE_FLOAT)) {
984 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
985 type_name[exprs[0]->expression.vtype],
986 type_name[exprs[1]->expression.vtype]);
989 if (CanConstFold(exprs[0], exprs[1])) {
990 out = (ast_expression*)parser_const_float(parser,
991 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
993 /* generate a call to __builtin_mod */
994 ast_expression *mod = intrin_func(parser, "mod");
995 ast_call *call = NULL;
996 if (!mod) return false; /* can return null for missing floor */
998 call = ast_call_new(parser_ctx(parser), mod);
999 vec_push(call->params, exprs[0]);
1000 vec_push(call->params, exprs[1]);
1002 out = (ast_expression*)call;
1006 case opid2('%','='):
1007 compile_error(ctx, "%= is unimplemented");
1012 if (NotSameType(TYPE_FLOAT)) {
1013 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1014 type_name[exprs[0]->expression.vtype],
1015 type_name[exprs[1]->expression.vtype]);
1018 if (CanConstFold(exprs[0], exprs[1]))
1019 out = (ast_expression*)parser_const_float(parser,
1020 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1021 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1023 out = (ast_expression*)ast_binary_new(ctx,
1024 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1025 exprs[0], exprs[1]);
1028 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1031 case opid2('<','<'):
1032 case opid2('>','>'):
1033 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1034 if (op->id == opid2('<','<'))
1035 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1037 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1040 case opid3('<','<','='):
1041 case opid3('>','>','='):
1042 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1045 case opid2('|','|'):
1046 generated_op += 1; /* INSTR_OR */
1047 case opid2('&','&'):
1048 generated_op += INSTR_AND;
1049 if (CanConstFold(exprs[0], exprs[1]))
1051 if (OPTS_FLAG(PERL_LOGIC)) {
1052 if (immediate_is_true(ctx, asvalue[0]))
1056 out = (ast_expression*)parser_const_float(parser,
1057 ( (generated_op == INSTR_OR)
1058 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1059 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1064 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1065 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1066 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1067 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1070 for (i = 0; i < 2; ++i) {
1071 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1072 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1074 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1076 exprs[i] = out; out = NULL;
1077 if (OPTS_FLAG(PERL_LOGIC)) {
1078 /* here we want to keep the right expressions' type */
1082 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1083 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1085 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1087 exprs[i] = out; out = NULL;
1088 if (OPTS_FLAG(PERL_LOGIC)) {
1089 /* here we want to keep the right expressions' type */
1094 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1098 case opid2('?',':'):
1099 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1100 compile_error(ctx, "mismatched parenthesis/ternary");
1104 if (!ast_compare_type(exprs[1], exprs[2])) {
1105 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1106 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1107 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1110 if (CanConstFold1(exprs[0]))
1111 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1113 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1116 case opid2('*', '*'):
1117 if (NotSameType(TYPE_FLOAT)) {
1118 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1119 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1120 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1126 if (CanConstFold(exprs[0], exprs[1])) {
1127 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1129 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1130 vec_push(gencall->params, exprs[0]);
1131 vec_push(gencall->params, exprs[1]);
1132 out = (ast_expression*)gencall;
1136 case opid3('<','=','>'): /* -1, 0, or 1 */
1137 if (NotSameType(TYPE_FLOAT)) {
1138 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1139 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1140 compile_error(ctx, "invalid types used in comparision: %s and %s",
1146 if (CanConstFold(exprs[0], exprs[1])) {
1147 if (ConstF(0) < ConstF(1))
1148 out = (ast_expression*)parser_const_float_neg1(parser);
1149 else if (ConstF(0) == ConstF(1))
1150 out = (ast_expression*)parser_const_float_0(parser);
1151 else if (ConstF(0) > ConstF(1))
1152 out = (ast_expression*)parser_const_float_1(parser);
1154 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1156 eq->refs = (ast_binary_ref)false; /* references nothing */
1159 out = (ast_expression*)ast_ternary_new(ctx,
1160 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1162 (ast_expression*)parser_const_float_neg1(parser),
1165 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1167 (ast_expression*)parser_const_float_0(parser),
1170 (ast_expression*)parser_const_float_1(parser)
1180 generated_op += 1; /* INSTR_GT */
1182 generated_op += 1; /* INSTR_LT */
1183 case opid2('>', '='):
1184 generated_op += 1; /* INSTR_GE */
1185 case opid2('<', '='):
1186 generated_op += INSTR_LE;
1187 if (NotSameType(TYPE_FLOAT)) {
1188 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1189 type_name[exprs[0]->expression.vtype],
1190 type_name[exprs[1]->expression.vtype]);
1193 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1195 case opid2('!', '='):
1196 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1197 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1198 type_name[exprs[0]->expression.vtype],
1199 type_name[exprs[1]->expression.vtype]);
1202 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1204 case opid2('=', '='):
1205 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1206 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1207 type_name[exprs[0]->expression.vtype],
1208 type_name[exprs[1]->expression.vtype]);
1211 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1215 if (ast_istype(exprs[0], ast_entfield)) {
1216 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1217 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1218 exprs[0]->expression.vtype == TYPE_FIELD &&
1219 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1221 assignop = type_storep_instr[TYPE_VECTOR];
1224 assignop = type_storep_instr[exprs[0]->expression.vtype];
1225 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1227 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1228 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1229 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1230 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1231 exprs[1]->expression.vtype == TYPE_FUNCTION)
1233 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1234 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1237 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1242 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1243 exprs[0]->expression.vtype == TYPE_FIELD &&
1244 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1246 assignop = type_store_instr[TYPE_VECTOR];
1249 assignop = type_store_instr[exprs[0]->expression.vtype];
1252 if (assignop == VINSTR_END) {
1253 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1254 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1255 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1257 else if (!ast_compare_type(exprs[0], exprs[1]))
1259 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1260 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1261 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1262 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1263 exprs[1]->expression.vtype == TYPE_FUNCTION)
1265 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1266 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1269 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
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 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1277 case opid3('+','+','P'):
1278 case opid3('-','-','P'):
1280 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1281 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1282 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1285 if (op->id == opid3('+','+','P'))
1286 addop = INSTR_ADD_F;
1288 addop = INSTR_SUB_F;
1289 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1290 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1292 if (ast_istype(exprs[0], ast_entfield)) {
1293 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1295 (ast_expression*)parser_const_float_1(parser));
1297 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1299 (ast_expression*)parser_const_float_1(parser));
1302 case opid3('S','+','+'):
1303 case opid3('S','-','-'):
1305 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1306 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1307 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1310 if (op->id == opid3('S','+','+')) {
1311 addop = INSTR_ADD_F;
1312 subop = INSTR_SUB_F;
1314 addop = INSTR_SUB_F;
1315 subop = INSTR_ADD_F;
1317 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1318 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1320 if (ast_istype(exprs[0], ast_entfield)) {
1321 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1323 (ast_expression*)parser_const_float_1(parser));
1325 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1327 (ast_expression*)parser_const_float_1(parser));
1331 out = (ast_expression*)ast_binary_new(ctx, subop,
1333 (ast_expression*)parser_const_float_1(parser));
1335 case opid2('+','='):
1336 case opid2('-','='):
1337 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1338 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1340 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1341 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1342 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1346 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1347 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1349 if (ast_istype(exprs[0], ast_entfield))
1350 assignop = type_storep_instr[exprs[0]->expression.vtype];
1352 assignop = type_store_instr[exprs[0]->expression.vtype];
1353 switch (exprs[0]->expression.vtype) {
1355 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1356 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1357 exprs[0], exprs[1]);
1360 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1361 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1362 exprs[0], exprs[1]);
1365 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1366 type_name[exprs[0]->expression.vtype],
1367 type_name[exprs[1]->expression.vtype]);
1371 case opid2('*','='):
1372 case opid2('/','='):
1373 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1374 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1375 exprs[0]->expression.vtype == TYPE_VECTOR))
1377 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1378 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1379 compile_error(ctx, "invalid types used in expression: %s and %s",
1383 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1384 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1386 if (ast_istype(exprs[0], ast_entfield))
1387 assignop = type_storep_instr[exprs[0]->expression.vtype];
1389 assignop = type_store_instr[exprs[0]->expression.vtype];
1390 switch (exprs[0]->expression.vtype) {
1392 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1393 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1394 exprs[0], exprs[1]);
1397 if (op->id == opid2('*','=')) {
1398 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1399 exprs[0], exprs[1]);
1401 /* there's no DIV_VF */
1402 if (CanConstFold1(exprs[1])) {
1403 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1405 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1406 (ast_expression*)parser_const_float_1(parser),
1410 compile_error(ctx, "internal error: failed to generate division");
1413 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1418 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1419 type_name[exprs[0]->expression.vtype],
1420 type_name[exprs[1]->expression.vtype]);
1424 case opid2('&','='):
1425 case opid2('|','='):
1426 if (NotSameType(TYPE_FLOAT)) {
1427 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1428 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1429 compile_error(ctx, "invalid types used in expression: %s and %s",
1433 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1434 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1436 if (ast_istype(exprs[0], ast_entfield))
1437 assignop = type_storep_instr[exprs[0]->expression.vtype];
1439 assignop = type_store_instr[exprs[0]->expression.vtype];
1440 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1441 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1442 exprs[0], exprs[1]);
1444 case opid3('&','~','='):
1445 /* This is like: a &= ~(b);
1446 * But QC has no bitwise-not, so we implement it as
1449 if (NotSameType(TYPE_FLOAT)) {
1450 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1451 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1452 compile_error(ctx, "invalid types used in expression: %s and %s",
1456 if (ast_istype(exprs[0], ast_entfield))
1457 assignop = type_storep_instr[exprs[0]->expression.vtype];
1459 assignop = type_store_instr[exprs[0]->expression.vtype];
1460 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1463 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1464 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1466 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1467 asbinstore->keep_dest = true;
1468 out = (ast_expression*)asbinstore;
1471 case opid2('~', 'P'):
1472 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1473 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1474 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1478 if(CanConstFold1(exprs[0]))
1479 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1481 out = (ast_expression*)
1482 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1488 compile_error(ctx, "failed to apply operator %s", op->op);
1492 vec_push(sy->out, syexp(ctx, out));
1496 static bool parser_close_call(parser_t *parser, shunt *sy)
1498 /* was a function call */
1499 ast_expression *fun;
1500 ast_value *funval = NULL;
1504 size_t paramcount, i;
1506 fid = vec_last(sy->ops).off;
1507 vec_shrinkby(sy->ops, 1);
1509 /* out[fid] is the function
1510 * everything above is parameters...
1512 if (!vec_size(sy->argc)) {
1513 parseerror(parser, "internal error: no argument counter available");
1517 paramcount = vec_last(sy->argc);
1520 if (vec_size(sy->out) < fid) {
1521 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1522 (unsigned long)vec_size(sy->out),
1524 (unsigned long)paramcount);
1528 fun = sy->out[fid].out;
1530 if (fun == intrinsic_debug_typestring) {
1532 if (fid+2 != vec_size(sy->out) ||
1533 vec_last(sy->out).block)
1535 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1538 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1539 ast_unref(vec_last(sy->out).out);
1540 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1541 (ast_expression*)parser_const_string(parser, ty, false));
1542 vec_shrinkby(sy->out, 1);
1546 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1550 if (fid+1 < vec_size(sy->out))
1553 if (fid+1 + paramcount != vec_size(sy->out)) {
1554 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1555 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1559 for (i = 0; i < paramcount; ++i)
1560 vec_push(call->params, sy->out[fid+1 + i].out);
1561 vec_shrinkby(sy->out, paramcount);
1562 (void)!ast_call_check_types(call);
1563 if (parser->max_param_count < paramcount)
1564 parser->max_param_count = paramcount;
1566 if (ast_istype(fun, ast_value)) {
1567 funval = (ast_value*)fun;
1568 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1569 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1571 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1575 /* overwrite fid, the function, with a call */
1576 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1578 if (fun->expression.vtype != TYPE_FUNCTION) {
1579 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1583 if (!fun->expression.next) {
1584 parseerror(parser, "could not determine function return type");
1587 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1589 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1591 return !parsewarning(parser, WARN_DEPRECATED,
1592 "call to function (which is marked deprecated)\n",
1593 "-> it has been declared here: %s:%i",
1594 ast_ctx(fun).file, ast_ctx(fun).line);
1597 return !parsewarning(parser, WARN_DEPRECATED,
1598 "call to `%s` (which is marked deprecated)\n"
1599 "-> `%s` declared here: %s:%i",
1600 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1602 return !parsewarning(parser, WARN_DEPRECATED,
1603 "call to `%s` (deprecated: %s)\n"
1604 "-> `%s` declared here: %s:%i",
1605 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1609 if (vec_size(fun->expression.params) != paramcount &&
1610 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1611 vec_size(fun->expression.params) < paramcount))
1613 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1615 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1616 "too %s parameters for call to %s: expected %i, got %i\n"
1617 " -> `%s` has been declared here: %s:%i",
1618 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1619 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1621 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1622 "too %s parameters for function call: expected %i, got %i\n"
1623 " -> it has been declared here: %s:%i",
1624 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1625 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1632 static bool parser_close_paren(parser_t *parser, shunt *sy)
1634 if (!vec_size(sy->ops)) {
1635 parseerror(parser, "unmatched closing paren");
1639 while (vec_size(sy->ops)) {
1640 if (vec_last(sy->ops).isparen) {
1641 if (vec_last(sy->paren) == PAREN_FUNC) {
1643 if (!parser_close_call(parser, sy))
1647 if (vec_last(sy->paren) == PAREN_EXPR) {
1649 if (!vec_size(sy->out)) {
1650 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1651 vec_shrinkby(sy->ops, 1);
1654 vec_shrinkby(sy->ops, 1);
1657 if (vec_last(sy->paren) == PAREN_INDEX) {
1659 /* pop off the parenthesis */
1660 vec_shrinkby(sy->ops, 1);
1661 /* then apply the index operator */
1662 if (!parser_sy_apply_operator(parser, sy))
1666 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1667 vec_last(sy->paren) = PAREN_TERNARY2;
1668 /* pop off the parenthesis */
1669 vec_shrinkby(sy->ops, 1);
1672 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1675 if (!parser_sy_apply_operator(parser, sy))
1681 static void parser_reclassify_token(parser_t *parser)
1684 for (i = 0; i < operator_count; ++i) {
1685 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1686 parser->tok = TOKEN_OPERATOR;
1692 static ast_expression* parse_vararg_do(parser_t *parser)
1694 ast_expression *idx, *out;
1696 ast_value *funtype = parser->function->vtype;
1698 lex_ctx ctx = parser_ctx(parser);
1700 if (!parser_next(parser) || parser->tok != '(') {
1701 parseerror(parser, "expected parameter index and type in parenthesis");
1704 if (!parser_next(parser)) {
1705 parseerror(parser, "error parsing parameter index");
1709 idx = parse_expression_leave(parser, true, false, false);
1713 if (parser->tok != ',') {
1715 parseerror(parser, "expected comma after parameter index");
1719 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1721 parseerror(parser, "expected typename for vararg");
1725 typevar = parse_typename(parser, NULL, NULL);
1731 if (parser->tok != ')') {
1733 ast_delete(typevar);
1734 parseerror(parser, "expected closing paren");
1739 if (!parser_next(parser)) {
1741 ast_delete(typevar);
1742 parseerror(parser, "parse error after vararg");
1747 if (!parser->function->varargs) {
1749 ast_delete(typevar);
1750 parseerror(parser, "function has no variable argument list");
1754 if (funtype->expression.varparam &&
1755 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1759 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1760 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1761 compile_error(ast_ctx(typevar),
1762 "function was declared to take varargs of type `%s`, requested type is: %s",
1766 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1767 ast_type_adopt(out, typevar);
1768 ast_delete(typevar);
1772 static ast_expression* parse_vararg(parser_t *parser)
1774 bool old_noops = parser->lex->flags.noops;
1776 ast_expression *out;
1778 parser->lex->flags.noops = true;
1779 out = parse_vararg_do(parser);
1781 parser->lex->flags.noops = old_noops;
1785 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1787 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1788 parser->tok == TOKEN_IDENT &&
1789 !strcmp(parser_tokval(parser), "_"))
1791 /* a translatable string */
1794 parser->lex->flags.noops = true;
1795 if (!parser_next(parser) || parser->tok != '(') {
1796 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1799 parser->lex->flags.noops = false;
1800 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1801 parseerror(parser, "expected a constant string in translatable-string extension");
1804 val = parser_const_string(parser, parser_tokval(parser), true);
1807 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1809 if (!parser_next(parser) || parser->tok != ')') {
1810 parseerror(parser, "expected closing paren after translatable string");
1815 else if (parser->tok == TOKEN_DOTS)
1818 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1819 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1822 va = parse_vararg(parser);
1825 vec_push(sy->out, syexp(parser_ctx(parser), va));
1828 else if (parser->tok == TOKEN_FLOATCONST) {
1830 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1833 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1836 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1838 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1841 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1844 else if (parser->tok == TOKEN_STRINGCONST) {
1846 val = parser_const_string(parser, parser_tokval(parser), false);
1849 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1852 else if (parser->tok == TOKEN_VECTORCONST) {
1854 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1857 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1860 else if (parser->tok == TOKEN_IDENT)
1862 const char *ctoken = parser_tokval(parser);
1863 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1864 ast_expression *var;
1865 /* a_vector.{x,y,z} */
1866 if (!vec_size(sy->ops) ||
1867 !vec_last(sy->ops).etype ||
1868 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1869 (prev >= intrinsic_debug_typestring &&
1870 prev <= intrinsic_debug_typestring))
1872 /* When adding more intrinsics, fix the above condition */
1875 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1877 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1879 var = parser_find_var(parser, parser_tokval(parser));
1881 var = parser_find_field(parser, parser_tokval(parser));
1883 if (!var && with_labels) {
1884 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1886 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1887 var = (ast_expression*)lbl;
1888 vec_push(parser->labels, lbl);
1893 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1894 var = (ast_expression*)intrinsic_debug_typestring;
1896 /* now we try for the real intrinsic hashtable. If the string
1897 * begins with __builtin, we simply skip past it, otherwise we
1898 * use the identifier as is.
1900 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1901 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1905 char *correct = NULL;
1909 * sometimes people use preprocessing predefs without enabling them
1910 * i've done this thousands of times already myself. Lets check for
1911 * it in the predef table. And diagnose it better :)
1913 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1914 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1915 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1916 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1923 * TODO: determine the best score for the identifier: be it
1924 * a variable, a field.
1926 * We should also consider adding correction tables for
1927 * other things as well.
1929 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1931 correct_init(&corr);
1933 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1934 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1935 if (strcmp(correct, parser_tokval(parser))) {
1937 } else if (correct) {
1942 correct_free(&corr);
1945 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1950 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1956 if (ast_istype(var, ast_value)) {
1957 ((ast_value*)var)->uses++;
1959 else if (ast_istype(var, ast_member)) {
1960 ast_member *mem = (ast_member*)var;
1961 if (ast_istype(mem->owner, ast_value))
1962 ((ast_value*)(mem->owner))->uses++;
1965 vec_push(sy->out, syexp(parser_ctx(parser), var));
1968 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1972 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1974 ast_expression *expr = NULL;
1977 bool wantop = false;
1978 /* only warn once about an assignment in a truth value because the current code
1979 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1981 bool warn_truthvalue = true;
1983 /* count the parens because an if starts with one, so the
1984 * end of a condition is an unmatched closing paren
1988 memset(&sy, 0, sizeof(sy));
1990 parser->lex->flags.noops = false;
1992 parser_reclassify_token(parser);
1996 if (parser->tok == TOKEN_TYPENAME) {
1997 parseerror(parser, "unexpected typename");
2001 if (parser->tok == TOKEN_OPERATOR)
2003 /* classify the operator */
2004 const oper_info *op;
2005 const oper_info *olast = NULL;
2007 for (o = 0; o < operator_count; ++o) {
2008 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2009 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2010 !strcmp(parser_tokval(parser), operators[o].op))
2015 if (o == operator_count) {
2016 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2019 /* found an operator */
2022 /* when declaring variables, a comma starts a new variable */
2023 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2024 /* fixup the token */
2029 /* a colon without a pervious question mark cannot be a ternary */
2030 if (!ternaries && op->id == opid2(':','?')) {
2035 if (op->id == opid1(',')) {
2036 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2037 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2041 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2042 olast = &operators[vec_last(sy.ops).etype-1];
2044 #define IsAssignOp(x) (\
2045 (x) == opid1('=') || \
2046 (x) == opid2('+','=') || \
2047 (x) == opid2('-','=') || \
2048 (x) == opid2('*','=') || \
2049 (x) == opid2('/','=') || \
2050 (x) == opid2('%','=') || \
2051 (x) == opid2('&','=') || \
2052 (x) == opid2('|','=') || \
2053 (x) == opid3('&','~','=') \
2055 if (warn_truthvalue) {
2056 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2057 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2058 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2061 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2062 warn_truthvalue = false;
2067 (op->prec < olast->prec) ||
2068 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2070 if (!parser_sy_apply_operator(parser, &sy))
2072 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2073 olast = &operators[vec_last(sy.ops).etype-1];
2078 if (op->id == opid1('(')) {
2080 size_t sycount = vec_size(sy.out);
2081 /* we expected an operator, this is the function-call operator */
2082 vec_push(sy.paren, PAREN_FUNC);
2083 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2084 vec_push(sy.argc, 0);
2086 vec_push(sy.paren, PAREN_EXPR);
2087 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2090 } else if (op->id == opid1('[')) {
2092 parseerror(parser, "unexpected array subscript");
2095 vec_push(sy.paren, PAREN_INDEX);
2096 /* push both the operator and the paren, this makes life easier */
2097 vec_push(sy.ops, syop(parser_ctx(parser), op));
2098 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2100 } else if (op->id == opid2('?',':')) {
2101 vec_push(sy.ops, syop(parser_ctx(parser), op));
2102 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2105 vec_push(sy.paren, PAREN_TERNARY1);
2106 } else if (op->id == opid2(':','?')) {
2107 if (!vec_size(sy.paren)) {
2108 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2111 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2112 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2115 if (!parser_close_paren(parser, &sy))
2117 vec_push(sy.ops, syop(parser_ctx(parser), op));
2121 vec_push(sy.ops, syop(parser_ctx(parser), op));
2122 wantop = !!(op->flags & OP_SUFFIX);
2125 else if (parser->tok == ')') {
2126 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2127 if (!parser_sy_apply_operator(parser, &sy))
2130 if (!vec_size(sy.paren))
2133 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2134 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2137 if (!parser_close_paren(parser, &sy))
2140 /* must be a function call without parameters */
2141 if (vec_last(sy.paren) != PAREN_FUNC) {
2142 parseerror(parser, "closing paren in invalid position");
2145 if (!parser_close_paren(parser, &sy))
2150 else if (parser->tok == '(') {
2151 parseerror(parser, "internal error: '(' should be classified as operator");
2154 else if (parser->tok == '[') {
2155 parseerror(parser, "internal error: '[' should be classified as operator");
2158 else if (parser->tok == ']') {
2159 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2160 if (!parser_sy_apply_operator(parser, &sy))
2163 if (!vec_size(sy.paren))
2165 if (vec_last(sy.paren) != PAREN_INDEX) {
2166 parseerror(parser, "mismatched parentheses, unexpected ']'");
2169 if (!parser_close_paren(parser, &sy))
2174 if (!parse_sya_operand(parser, &sy, with_labels))
2177 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2178 vec_last(sy.argc)++;
2183 parseerror(parser, "expected operator or end of statement");
2187 if (!parser_next(parser)) {
2190 if (parser->tok == ';' ||
2191 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2192 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2198 while (vec_size(sy.ops)) {
2199 if (!parser_sy_apply_operator(parser, &sy))
2203 parser->lex->flags.noops = true;
2204 if (!vec_size(sy.out)) {
2205 parseerror(parser, "empty expression");
2208 expr = sy.out[0].out;
2211 if (vec_size(sy.paren)) {
2212 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2220 parser->lex->flags.noops = true;
2221 for (i = 0; i < vec_size(sy.out); ++i) {
2223 ast_unref(sy.out[i].out);
2232 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2234 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2237 if (parser->tok != ';') {
2238 parseerror(parser, "semicolon expected after expression");
2242 if (!parser_next(parser)) {
2249 static void parser_enterblock(parser_t *parser)
2251 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2252 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2253 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2254 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2255 vec_push(parser->_block_ctx, parser_ctx(parser));
2258 vec_push(parser->correct_variables, correct_trie_new());
2259 vec_push(parser->correct_variables_score, NULL);
2262 static bool parser_leaveblock(parser_t *parser)
2265 size_t locals, typedefs;
2267 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2268 parseerror(parser, "internal error: parser_leaveblock with no block");
2272 util_htdel(vec_last(parser->variables));
2273 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2275 vec_pop(parser->variables);
2276 vec_pop(parser->correct_variables);
2277 vec_pop(parser->correct_variables_score);
2278 if (!vec_size(parser->_blocklocals)) {
2279 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2283 locals = vec_last(parser->_blocklocals);
2284 vec_pop(parser->_blocklocals);
2285 while (vec_size(parser->_locals) != locals) {
2286 ast_expression *e = vec_last(parser->_locals);
2287 ast_value *v = (ast_value*)e;
2288 vec_pop(parser->_locals);
2289 if (ast_istype(e, ast_value) && !v->uses) {
2290 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2295 typedefs = vec_last(parser->_blocktypedefs);
2296 while (vec_size(parser->_typedefs) != typedefs) {
2297 ast_delete(vec_last(parser->_typedefs));
2298 vec_pop(parser->_typedefs);
2300 util_htdel(vec_last(parser->typedefs));
2301 vec_pop(parser->typedefs);
2303 vec_pop(parser->_block_ctx);
2308 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2310 vec_push(parser->_locals, e);
2311 util_htset(vec_last(parser->variables), name, (void*)e);
2315 vec_last(parser->correct_variables),
2316 &vec_last(parser->correct_variables_score),
2321 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2323 vec_push(parser->globals, e);
2324 util_htset(parser->htglobals, name, e);
2328 parser->correct_variables[0],
2329 &parser->correct_variables_score[0],
2334 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2338 ast_expression *prev;
2340 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2342 ast_type_to_string(cond, ty, sizeof(ty));
2343 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2346 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2349 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2352 parseerror(parser, "internal error: failed to process condition");
2357 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2359 /* vector types need to be cast to true booleans */
2360 ast_binary *bin = (ast_binary*)cond;
2361 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2363 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2365 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2368 parseerror(parser, "internal error: failed to process condition");
2375 unary = (ast_unary*)cond;
2376 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2378 cond = unary->operand;
2379 unary->operand = NULL;
2382 unary = (ast_unary*)cond;
2386 parseerror(parser, "internal error: failed to process condition");
2388 if (ifnot) *_ifnot = !*_ifnot;
2392 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2395 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2398 lex_ctx ctx = parser_ctx(parser);
2400 (void)block; /* not touching */
2402 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2403 if (!parser_next(parser)) {
2404 parseerror(parser, "expected condition or 'not'");
2407 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2409 if (!parser_next(parser)) {
2410 parseerror(parser, "expected condition in parenthesis");
2414 if (parser->tok != '(') {
2415 parseerror(parser, "expected 'if' condition in parenthesis");
2418 /* parse into the expression */
2419 if (!parser_next(parser)) {
2420 parseerror(parser, "expected 'if' condition after opening paren");
2423 /* parse the condition */
2424 cond = parse_expression_leave(parser, false, true, false);
2428 if (parser->tok != ')') {
2429 parseerror(parser, "expected closing paren after 'if' condition");
2433 /* parse into the 'then' branch */
2434 if (!parser_next(parser)) {
2435 parseerror(parser, "expected statement for on-true branch of 'if'");
2439 if (!parse_statement_or_block(parser, &ontrue)) {
2444 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2445 /* check for an else */
2446 if (!strcmp(parser_tokval(parser), "else")) {
2447 /* parse into the 'else' branch */
2448 if (!parser_next(parser)) {
2449 parseerror(parser, "expected on-false branch after 'else'");
2454 if (!parse_statement_or_block(parser, &onfalse)) {
2461 cond = process_condition(parser, cond, &ifnot);
2463 if (ontrue) ast_delete(ontrue);
2464 if (onfalse) ast_delete(onfalse);
2469 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2471 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2472 *out = (ast_expression*)ifthen;
2476 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2477 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2482 /* skip the 'while' and get the body */
2483 if (!parser_next(parser)) {
2484 if (OPTS_FLAG(LOOP_LABELS))
2485 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2487 parseerror(parser, "expected 'while' condition in parenthesis");
2491 if (parser->tok == ':') {
2492 if (!OPTS_FLAG(LOOP_LABELS))
2493 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2494 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2495 parseerror(parser, "expected loop label");
2498 label = util_strdup(parser_tokval(parser));
2499 if (!parser_next(parser)) {
2501 parseerror(parser, "expected 'while' condition in parenthesis");
2506 if (parser->tok != '(') {
2507 parseerror(parser, "expected 'while' condition in parenthesis");
2511 vec_push(parser->breaks, label);
2512 vec_push(parser->continues, label);
2514 rv = parse_while_go(parser, block, out);
2517 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2518 parseerror(parser, "internal error: label stack corrupted");
2524 vec_pop(parser->breaks);
2525 vec_pop(parser->continues);
2530 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2533 ast_expression *cond, *ontrue;
2537 lex_ctx ctx = parser_ctx(parser);
2539 (void)block; /* not touching */
2541 /* parse into the expression */
2542 if (!parser_next(parser)) {
2543 parseerror(parser, "expected 'while' condition after opening paren");
2546 /* parse the condition */
2547 cond = parse_expression_leave(parser, false, true, false);
2551 if (parser->tok != ')') {
2552 parseerror(parser, "expected closing paren after 'while' condition");
2556 /* parse into the 'then' branch */
2557 if (!parser_next(parser)) {
2558 parseerror(parser, "expected while-loop body");
2562 if (!parse_statement_or_block(parser, &ontrue)) {
2567 cond = process_condition(parser, cond, &ifnot);
2572 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2573 *out = (ast_expression*)aloop;
2577 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2578 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2583 /* skip the 'do' and get the body */
2584 if (!parser_next(parser)) {
2585 if (OPTS_FLAG(LOOP_LABELS))
2586 parseerror(parser, "expected loop label or body");
2588 parseerror(parser, "expected loop body");
2592 if (parser->tok == ':') {
2593 if (!OPTS_FLAG(LOOP_LABELS))
2594 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2595 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2596 parseerror(parser, "expected loop label");
2599 label = util_strdup(parser_tokval(parser));
2600 if (!parser_next(parser)) {
2602 parseerror(parser, "expected loop body");
2607 vec_push(parser->breaks, label);
2608 vec_push(parser->continues, label);
2610 rv = parse_dowhile_go(parser, block, out);
2613 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2614 parseerror(parser, "internal error: label stack corrupted");
2620 vec_pop(parser->breaks);
2621 vec_pop(parser->continues);
2626 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2629 ast_expression *cond, *ontrue;
2633 lex_ctx ctx = parser_ctx(parser);
2635 (void)block; /* not touching */
2637 if (!parse_statement_or_block(parser, &ontrue))
2640 /* expect the "while" */
2641 if (parser->tok != TOKEN_KEYWORD ||
2642 strcmp(parser_tokval(parser), "while"))
2644 parseerror(parser, "expected 'while' and condition");
2649 /* skip the 'while' and check for opening paren */
2650 if (!parser_next(parser) || parser->tok != '(') {
2651 parseerror(parser, "expected 'while' condition in parenthesis");
2655 /* parse into the expression */
2656 if (!parser_next(parser)) {
2657 parseerror(parser, "expected 'while' condition after opening paren");
2661 /* parse the condition */
2662 cond = parse_expression_leave(parser, false, true, false);
2666 if (parser->tok != ')') {
2667 parseerror(parser, "expected closing paren after 'while' condition");
2673 if (!parser_next(parser) || parser->tok != ';') {
2674 parseerror(parser, "expected semicolon after condition");
2680 if (!parser_next(parser)) {
2681 parseerror(parser, "parse error");
2687 cond = process_condition(parser, cond, &ifnot);
2692 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2693 *out = (ast_expression*)aloop;
2697 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2698 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2703 /* skip the 'for' and check for opening paren */
2704 if (!parser_next(parser)) {
2705 if (OPTS_FLAG(LOOP_LABELS))
2706 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2708 parseerror(parser, "expected 'for' expressions in parenthesis");
2712 if (parser->tok == ':') {
2713 if (!OPTS_FLAG(LOOP_LABELS))
2714 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2715 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2716 parseerror(parser, "expected loop label");
2719 label = util_strdup(parser_tokval(parser));
2720 if (!parser_next(parser)) {
2722 parseerror(parser, "expected 'for' expressions in parenthesis");
2727 if (parser->tok != '(') {
2728 parseerror(parser, "expected 'for' expressions in parenthesis");
2732 vec_push(parser->breaks, label);
2733 vec_push(parser->continues, label);
2735 rv = parse_for_go(parser, block, out);
2738 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2739 parseerror(parser, "internal error: label stack corrupted");
2745 vec_pop(parser->breaks);
2746 vec_pop(parser->continues);
2750 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2753 ast_expression *initexpr, *cond, *increment, *ontrue;
2759 lex_ctx ctx = parser_ctx(parser);
2761 parser_enterblock(parser);
2768 /* parse into the expression */
2769 if (!parser_next(parser)) {
2770 parseerror(parser, "expected 'for' initializer after opening paren");
2775 if (parser->tok == TOKEN_IDENT)
2776 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2778 if (typevar || parser->tok == TOKEN_TYPENAME) {
2780 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2781 if (parsewarning(parser, WARN_EXTENSIONS,
2782 "current standard does not allow variable declarations in for-loop initializers"))
2786 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2789 else if (parser->tok != ';')
2791 initexpr = parse_expression_leave(parser, false, false, false);
2796 /* move on to condition */
2797 if (parser->tok != ';') {
2798 parseerror(parser, "expected semicolon after for-loop initializer");
2801 if (!parser_next(parser)) {
2802 parseerror(parser, "expected for-loop condition");
2806 /* parse the condition */
2807 if (parser->tok != ';') {
2808 cond = parse_expression_leave(parser, false, true, false);
2813 /* move on to incrementor */
2814 if (parser->tok != ';') {
2815 parseerror(parser, "expected semicolon after for-loop initializer");
2818 if (!parser_next(parser)) {
2819 parseerror(parser, "expected for-loop condition");
2823 /* parse the incrementor */
2824 if (parser->tok != ')') {
2825 lex_ctx condctx = parser_ctx(parser);
2826 increment = parse_expression_leave(parser, false, false, false);
2829 if (!ast_side_effects(increment)) {
2830 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2836 if (parser->tok != ')') {
2837 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2840 /* parse into the 'then' branch */
2841 if (!parser_next(parser)) {
2842 parseerror(parser, "expected for-loop body");
2845 if (!parse_statement_or_block(parser, &ontrue))
2849 cond = process_condition(parser, cond, &ifnot);
2853 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2854 *out = (ast_expression*)aloop;
2856 if (!parser_leaveblock(parser))
2860 if (initexpr) ast_delete(initexpr);
2861 if (cond) ast_delete(cond);
2862 if (increment) ast_delete(increment);
2863 (void)!parser_leaveblock(parser);
2867 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2869 ast_expression *exp = NULL;
2870 ast_return *ret = NULL;
2871 ast_value *expected = parser->function->vtype;
2873 lex_ctx ctx = parser_ctx(parser);
2875 (void)block; /* not touching */
2877 if (!parser_next(parser)) {
2878 parseerror(parser, "expected return expression");
2882 if (parser->tok != ';') {
2883 exp = parse_expression(parser, false, false);
2887 if (exp->expression.vtype != TYPE_NIL &&
2888 exp->expression.vtype != expected->expression.next->expression.vtype)
2890 parseerror(parser, "return with invalid expression");
2893 ret = ast_return_new(ctx, exp);
2899 if (!parser_next(parser))
2900 parseerror(parser, "parse error");
2901 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2902 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2904 ret = ast_return_new(ctx, NULL);
2906 *out = (ast_expression*)ret;
2910 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2913 unsigned int levels = 0;
2914 lex_ctx ctx = parser_ctx(parser);
2915 const char **loops = (is_continue ? parser->continues : parser->breaks);
2917 (void)block; /* not touching */
2918 if (!parser_next(parser)) {
2919 parseerror(parser, "expected semicolon or loop label");
2923 if (!vec_size(loops)) {
2925 parseerror(parser, "`continue` can only be used inside loops");
2927 parseerror(parser, "`break` can only be used inside loops or switches");
2930 if (parser->tok == TOKEN_IDENT) {
2931 if (!OPTS_FLAG(LOOP_LABELS))
2932 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2933 i = vec_size(loops);
2935 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2938 parseerror(parser, "no such loop to %s: `%s`",
2939 (is_continue ? "continue" : "break out of"),
2940 parser_tokval(parser));
2945 if (!parser_next(parser)) {
2946 parseerror(parser, "expected semicolon");
2951 if (parser->tok != ';') {
2952 parseerror(parser, "expected semicolon");
2956 if (!parser_next(parser))
2957 parseerror(parser, "parse error");
2959 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2963 /* returns true when it was a variable qualifier, false otherwise!
2964 * on error, cvq is set to CV_WRONG
2966 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2968 bool had_const = false;
2969 bool had_var = false;
2970 bool had_noref = false;
2971 bool had_attrib = false;
2972 bool had_static = false;
2977 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2979 /* parse an attribute */
2980 if (!parser_next(parser)) {
2981 parseerror(parser, "expected attribute after `[[`");
2985 if (!strcmp(parser_tokval(parser), "noreturn")) {
2986 flags |= AST_FLAG_NORETURN;
2987 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2988 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2993 else if (!strcmp(parser_tokval(parser), "noref")) {
2995 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2996 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3001 else if (!strcmp(parser_tokval(parser), "inline")) {
3002 flags |= AST_FLAG_INLINE;
3003 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3004 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3009 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3010 flags |= AST_FLAG_ALIAS;
3013 if (!parser_next(parser)) {
3014 parseerror(parser, "parse error in attribute");
3018 if (parser->tok == '(') {
3019 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3020 parseerror(parser, "`alias` attribute missing parameter");
3024 *message = util_strdup(parser_tokval(parser));
3026 if (!parser_next(parser)) {
3027 parseerror(parser, "parse error in attribute");
3031 if (parser->tok != ')') {
3032 parseerror(parser, "`alias` attribute expected `)` after parameter");
3036 if (!parser_next(parser)) {
3037 parseerror(parser, "parse error in attribute");
3042 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3043 parseerror(parser, "`alias` attribute expected `]]`");
3047 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3048 flags |= AST_FLAG_DEPRECATED;
3051 if (!parser_next(parser)) {
3052 parseerror(parser, "parse error in attribute");
3056 if (parser->tok == '(') {
3057 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3058 parseerror(parser, "`deprecated` attribute missing parameter");
3062 *message = util_strdup(parser_tokval(parser));
3064 if (!parser_next(parser)) {
3065 parseerror(parser, "parse error in attribute");
3069 if(parser->tok != ')') {
3070 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3074 if (!parser_next(parser)) {
3075 parseerror(parser, "parse error in attribute");
3080 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3081 parseerror(parser, "`deprecated` attribute expected `]]`");
3084 if (*message) mem_d(*message);
3092 /* Skip tokens until we hit a ]] */
3093 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3094 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3095 if (!parser_next(parser)) {
3096 parseerror(parser, "error inside attribute");
3103 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3105 else if (!strcmp(parser_tokval(parser), "const"))
3107 else if (!strcmp(parser_tokval(parser), "var"))
3109 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3111 else if (!strcmp(parser_tokval(parser), "noref"))
3113 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3118 if (!parser_next(parser))
3128 *is_static = had_static;
3132 parseerror(parser, "parse error after variable qualifier");
3137 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3138 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3143 /* skip the 'while' and get the body */
3144 if (!parser_next(parser)) {
3145 if (OPTS_FLAG(LOOP_LABELS))
3146 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3148 parseerror(parser, "expected 'switch' operand in parenthesis");
3152 if (parser->tok == ':') {
3153 if (!OPTS_FLAG(LOOP_LABELS))
3154 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3155 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3156 parseerror(parser, "expected loop label");
3159 label = util_strdup(parser_tokval(parser));
3160 if (!parser_next(parser)) {
3162 parseerror(parser, "expected 'switch' operand in parenthesis");
3167 if (parser->tok != '(') {
3168 parseerror(parser, "expected 'switch' operand in parenthesis");
3172 vec_push(parser->breaks, label);
3174 rv = parse_switch_go(parser, block, out);
3177 if (vec_last(parser->breaks) != label) {
3178 parseerror(parser, "internal error: label stack corrupted");
3184 vec_pop(parser->breaks);
3189 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3191 ast_expression *operand;
3194 ast_switch *switchnode;
3195 ast_switch_case swcase;
3198 bool noref, is_static;
3199 uint32_t qflags = 0;
3201 lex_ctx ctx = parser_ctx(parser);
3203 (void)block; /* not touching */
3206 /* parse into the expression */
3207 if (!parser_next(parser)) {
3208 parseerror(parser, "expected switch operand");
3211 /* parse the operand */
3212 operand = parse_expression_leave(parser, false, false, false);
3216 switchnode = ast_switch_new(ctx, operand);
3219 if (parser->tok != ')') {
3220 ast_delete(switchnode);
3221 parseerror(parser, "expected closing paren after 'switch' operand");
3225 /* parse over the opening paren */
3226 if (!parser_next(parser) || parser->tok != '{') {
3227 ast_delete(switchnode);
3228 parseerror(parser, "expected list of cases");
3232 if (!parser_next(parser)) {
3233 ast_delete(switchnode);
3234 parseerror(parser, "expected 'case' or 'default'");
3238 /* new block; allow some variables to be declared here */
3239 parser_enterblock(parser);
3242 if (parser->tok == TOKEN_IDENT)
3243 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3244 if (typevar || parser->tok == TOKEN_TYPENAME) {
3245 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3246 ast_delete(switchnode);
3251 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3253 if (cvq == CV_WRONG) {
3254 ast_delete(switchnode);
3257 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3258 ast_delete(switchnode);
3267 while (parser->tok != '}') {
3268 ast_block *caseblock;
3270 if (!strcmp(parser_tokval(parser), "case")) {
3271 if (!parser_next(parser)) {
3272 ast_delete(switchnode);
3273 parseerror(parser, "expected expression for case");
3276 swcase.value = parse_expression_leave(parser, false, false, false);
3277 if (!swcase.value) {
3278 ast_delete(switchnode);
3279 parseerror(parser, "expected expression for case");
3282 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3283 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3284 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3290 else if (!strcmp(parser_tokval(parser), "default")) {
3291 swcase.value = NULL;
3292 if (!parser_next(parser)) {
3293 ast_delete(switchnode);
3294 parseerror(parser, "expected colon");
3299 ast_delete(switchnode);
3300 parseerror(parser, "expected 'case' or 'default'");
3304 /* Now the colon and body */
3305 if (parser->tok != ':') {
3306 if (swcase.value) ast_unref(swcase.value);
3307 ast_delete(switchnode);
3308 parseerror(parser, "expected colon");
3312 if (!parser_next(parser)) {
3313 if (swcase.value) ast_unref(swcase.value);
3314 ast_delete(switchnode);
3315 parseerror(parser, "expected statements or case");
3318 caseblock = ast_block_new(parser_ctx(parser));
3320 if (swcase.value) ast_unref(swcase.value);
3321 ast_delete(switchnode);
3324 swcase.code = (ast_expression*)caseblock;
3325 vec_push(switchnode->cases, swcase);
3327 ast_expression *expr;
3328 if (parser->tok == '}')
3330 if (parser->tok == TOKEN_KEYWORD) {
3331 if (!strcmp(parser_tokval(parser), "case") ||
3332 !strcmp(parser_tokval(parser), "default"))
3337 if (!parse_statement(parser, caseblock, &expr, true)) {
3338 ast_delete(switchnode);
3343 if (!ast_block_add_expr(caseblock, expr)) {
3344 ast_delete(switchnode);
3350 parser_leaveblock(parser);
3353 if (parser->tok != '}') {
3354 ast_delete(switchnode);
3355 parseerror(parser, "expected closing paren of case list");
3358 if (!parser_next(parser)) {
3359 ast_delete(switchnode);
3360 parseerror(parser, "parse error after switch");
3363 *out = (ast_expression*)switchnode;
3367 /* parse computed goto sides */
3368 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3369 ast_expression *on_true;
3370 ast_expression *on_false;
3371 ast_expression *cond;
3376 if (ast_istype(*side, ast_ternary)) {
3377 ast_ternary *tern = (ast_ternary*)*side;
3378 on_true = parse_goto_computed(parser, &tern->on_true);
3379 on_false = parse_goto_computed(parser, &tern->on_false);
3381 if (!on_true || !on_false) {
3382 parseerror(parser, "expected label or expression in ternary");
3383 if (on_true) ast_unref(on_true);
3384 if (on_false) ast_unref(on_false);
3392 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3393 } else if (ast_istype(*side, ast_label)) {
3394 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3395 ast_goto_set_label(gt, ((ast_label*)*side));
3397 return (ast_expression*)gt;
3402 static bool parse_goto(parser_t *parser, ast_expression **out)
3404 ast_goto *gt = NULL;
3405 ast_expression *lbl;
3407 if (!parser_next(parser))
3410 if (parser->tok != TOKEN_IDENT) {
3411 ast_expression *expression;
3413 /* could be an expression i.e computed goto :-) */
3414 if (parser->tok != '(') {
3415 parseerror(parser, "expected label name after `goto`");
3419 /* failed to parse expression for goto */
3420 if (!(expression = parse_expression(parser, false, true)) ||
3421 !(*out = parse_goto_computed(parser, &expression))) {
3422 parseerror(parser, "invalid goto expression");
3423 ast_unref(expression);
3430 /* not computed goto */
3431 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3432 lbl = parser_find_label(parser, gt->name);
3434 if (!ast_istype(lbl, ast_label)) {
3435 parseerror(parser, "internal error: label is not an ast_label");
3439 ast_goto_set_label(gt, (ast_label*)lbl);
3442 vec_push(parser->gotos, gt);
3444 if (!parser_next(parser) || parser->tok != ';') {
3445 parseerror(parser, "semicolon expected after goto label");
3448 if (!parser_next(parser)) {
3449 parseerror(parser, "parse error after goto");
3453 *out = (ast_expression*)gt;
3457 static bool parse_skipwhite(parser_t *parser)
3460 if (!parser_next(parser))
3462 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3463 return parser->tok < TOKEN_ERROR;
3466 static bool parse_eol(parser_t *parser)
3468 if (!parse_skipwhite(parser))
3470 return parser->tok == TOKEN_EOL;
3473 static bool parse_pragma_do(parser_t *parser)
3475 if (!parser_next(parser) ||
3476 parser->tok != TOKEN_IDENT ||
3477 strcmp(parser_tokval(parser), "pragma"))
3479 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3482 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3483 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3487 if (!strcmp(parser_tokval(parser), "noref")) {
3488 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3489 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3492 parser->noref = !!parser_token(parser)->constval.i;
3493 if (!parse_eol(parser)) {
3494 parseerror(parser, "parse error after `noref` pragma");
3500 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3507 static bool parse_pragma(parser_t *parser)
3510 parser->lex->flags.preprocessing = true;
3511 parser->lex->flags.mergelines = true;
3512 rv = parse_pragma_do(parser);
3513 if (parser->tok != TOKEN_EOL) {
3514 parseerror(parser, "junk after pragma");
3517 parser->lex->flags.preprocessing = false;
3518 parser->lex->flags.mergelines = false;
3519 if (!parser_next(parser)) {
3520 parseerror(parser, "parse error after pragma");
3526 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3528 bool noref, is_static;
3530 uint32_t qflags = 0;
3531 ast_value *typevar = NULL;
3532 char *vstring = NULL;
3536 if (parser->tok == TOKEN_IDENT)
3537 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3539 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3541 /* local variable */
3543 parseerror(parser, "cannot declare a variable from here");
3546 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3547 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3550 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3554 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3556 if (cvq == CV_WRONG)
3558 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3560 else if (parser->tok == TOKEN_KEYWORD)
3562 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3567 if (!parser_next(parser)) {
3568 parseerror(parser, "parse error after __builtin_debug_printtype");
3572 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3574 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3575 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3576 if (!parser_next(parser)) {
3577 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3583 if (!parse_statement(parser, block, out, allow_cases))
3586 con_out("__builtin_debug_printtype: got no output node\n");
3589 ast_type_to_string(*out, ty, sizeof(ty));
3590 con_out("__builtin_debug_printtype: `%s`\n", ty);
3595 else if (!strcmp(parser_tokval(parser), "return"))
3597 return parse_return(parser, block, out);
3599 else if (!strcmp(parser_tokval(parser), "if"))
3601 return parse_if(parser, block, out);
3603 else if (!strcmp(parser_tokval(parser), "while"))
3605 return parse_while(parser, block, out);
3607 else if (!strcmp(parser_tokval(parser), "do"))
3609 return parse_dowhile(parser, block, out);
3611 else if (!strcmp(parser_tokval(parser), "for"))
3613 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3614 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3617 return parse_for(parser, block, out);
3619 else if (!strcmp(parser_tokval(parser), "break"))
3621 return parse_break_continue(parser, block, out, false);
3623 else if (!strcmp(parser_tokval(parser), "continue"))
3625 return parse_break_continue(parser, block, out, true);
3627 else if (!strcmp(parser_tokval(parser), "switch"))
3629 return parse_switch(parser, block, out);
3631 else if (!strcmp(parser_tokval(parser), "case") ||
3632 !strcmp(parser_tokval(parser), "default"))
3635 parseerror(parser, "unexpected 'case' label");
3640 else if (!strcmp(parser_tokval(parser), "goto"))
3642 return parse_goto(parser, out);
3644 else if (!strcmp(parser_tokval(parser), "typedef"))
3646 if (!parser_next(parser)) {
3647 parseerror(parser, "expected type definition after 'typedef'");
3650 return parse_typedef(parser);
3652 parseerror(parser, "Unexpected keyword");
3655 else if (parser->tok == '{')
3658 inner = parse_block(parser);
3661 *out = (ast_expression*)inner;
3664 else if (parser->tok == ':')
3668 if (!parser_next(parser)) {
3669 parseerror(parser, "expected label name");
3672 if (parser->tok != TOKEN_IDENT) {
3673 parseerror(parser, "label must be an identifier");
3676 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3678 if (!label->undefined) {
3679 parseerror(parser, "label `%s` already defined", label->name);
3682 label->undefined = false;
3685 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3686 vec_push(parser->labels, label);
3688 *out = (ast_expression*)label;
3689 if (!parser_next(parser)) {
3690 parseerror(parser, "parse error after label");
3693 for (i = 0; i < vec_size(parser->gotos); ++i) {
3694 if (!strcmp(parser->gotos[i]->name, label->name)) {
3695 ast_goto_set_label(parser->gotos[i], label);
3696 vec_remove(parser->gotos, i, 1);
3702 else if (parser->tok == ';')
3704 if (!parser_next(parser)) {
3705 parseerror(parser, "parse error after empty statement");
3712 lex_ctx ctx = parser_ctx(parser);
3713 ast_expression *exp = parse_expression(parser, false, false);
3717 if (!ast_side_effects(exp)) {
3718 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3725 static bool parse_enum(parser_t *parser)
3728 bool reverse = false;
3730 ast_value **values = NULL;
3731 ast_value *var = NULL;
3734 ast_expression *old;
3736 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3737 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3741 /* enumeration attributes (can add more later) */
3742 if (parser->tok == ':') {
3743 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3744 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3749 if (!strcmp(parser_tokval(parser), "flag")) {
3753 else if (!strcmp(parser_tokval(parser), "reverse")) {
3757 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3761 if (!parser_next(parser) || parser->tok != '{') {
3762 parseerror(parser, "expected `{` after enum attribute ");
3768 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3769 if (parser->tok == '}') {
3770 /* allow an empty enum */
3773 parseerror(parser, "expected identifier or `}`");
3777 old = parser_find_field(parser, parser_tokval(parser));
3779 old = parser_find_global(parser, parser_tokval(parser));
3781 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3782 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3786 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3787 vec_push(values, var);
3788 var->cvq = CV_CONST;
3789 var->hasvalue = true;
3791 /* for flagged enumerations increment in POTs of TWO */
3792 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3793 parser_addglobal(parser, var->name, (ast_expression*)var);
3795 if (!parser_next(parser)) {
3796 parseerror(parser, "expected `=`, `}` or comma after identifier");
3800 if (parser->tok == ',')
3802 if (parser->tok == '}')
3804 if (parser->tok != '=') {
3805 parseerror(parser, "expected `=`, `}` or comma after identifier");
3809 if (!parser_next(parser)) {
3810 parseerror(parser, "expected expression after `=`");
3814 /* We got a value! */
3815 old = parse_expression_leave(parser, true, false, false);
3816 asvalue = (ast_value*)old;
3817 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3818 compile_error(ast_ctx(var), "constant value or expression expected");
3821 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3823 if (parser->tok == '}')
3825 if (parser->tok != ',') {
3826 parseerror(parser, "expected `}` or comma after expression");
3831 /* patch them all (for reversed attribute) */
3834 for (i = 0; i < vec_size(values); i++)
3835 values[i]->constval.vfloat = vec_size(values) - i - 1;
3838 if (parser->tok != '}') {
3839 parseerror(parser, "internal error: breaking without `}`");
3843 if (!parser_next(parser) || parser->tok != ';') {
3844 parseerror(parser, "expected semicolon after enumeration");
3848 if (!parser_next(parser)) {
3849 parseerror(parser, "parse error after enumeration");
3861 static bool parse_block_into(parser_t *parser, ast_block *block)
3865 parser_enterblock(parser);
3867 if (!parser_next(parser)) { /* skip the '{' */
3868 parseerror(parser, "expected function body");
3872 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3874 ast_expression *expr = NULL;
3875 if (parser->tok == '}')
3878 if (!parse_statement(parser, block, &expr, false)) {
3879 /* parseerror(parser, "parse error"); */
3885 if (!ast_block_add_expr(block, expr)) {
3892 if (parser->tok != '}') {
3895 (void)parser_next(parser);
3899 if (!parser_leaveblock(parser))
3901 return retval && !!block;
3904 static ast_block* parse_block(parser_t *parser)
3907 block = ast_block_new(parser_ctx(parser));
3910 if (!parse_block_into(parser, block)) {
3911 ast_block_delete(block);
3917 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3919 if (parser->tok == '{') {
3920 *out = (ast_expression*)parse_block(parser);
3923 return parse_statement(parser, NULL, out, false);
3926 static bool create_vector_members(ast_value *var, ast_member **me)
3929 size_t len = strlen(var->name);
3931 for (i = 0; i < 3; ++i) {
3932 char *name = (char*)mem_a(len+3);
3933 memcpy(name, var->name, len);
3935 name[len+1] = 'x'+i;
3937 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3946 do { ast_member_delete(me[--i]); } while(i);
3950 static bool parse_function_body(parser_t *parser, ast_value *var)
3952 ast_block *block = NULL;
3957 ast_expression *framenum = NULL;
3958 ast_expression *nextthink = NULL;
3959 /* None of the following have to be deleted */
3960 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3961 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3962 bool has_frame_think;
3966 has_frame_think = false;
3967 old = parser->function;
3969 if (var->expression.flags & AST_FLAG_ALIAS) {
3970 parseerror(parser, "function aliases cannot have bodies");
3974 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3975 parseerror(parser, "gotos/labels leaking");
3979 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3980 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3981 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3987 if (parser->tok == '[') {
3988 /* got a frame definition: [ framenum, nextthink ]
3989 * this translates to:
3990 * self.frame = framenum;
3991 * self.nextthink = time + 0.1;
3992 * self.think = nextthink;
3996 fld_think = parser_find_field(parser, "think");
3997 fld_nextthink = parser_find_field(parser, "nextthink");
3998 fld_frame = parser_find_field(parser, "frame");
3999 if (!fld_think || !fld_nextthink || !fld_frame) {
4000 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4001 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4004 gbl_time = parser_find_global(parser, "time");
4005 gbl_self = parser_find_global(parser, "self");
4006 if (!gbl_time || !gbl_self) {
4007 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4008 parseerror(parser, "please declare the following globals: `time`, `self`");
4012 if (!parser_next(parser))
4015 framenum = parse_expression_leave(parser, true, false, false);
4017 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4020 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4021 ast_unref(framenum);
4022 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4026 if (parser->tok != ',') {
4027 ast_unref(framenum);
4028 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4029 parseerror(parser, "Got a %i\n", parser->tok);
4033 if (!parser_next(parser)) {
4034 ast_unref(framenum);
4038 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4040 /* qc allows the use of not-yet-declared functions here
4041 * - this automatically creates a prototype */
4042 ast_value *thinkfunc;
4043 ast_expression *functype = fld_think->expression.next;
4045 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4046 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4047 ast_unref(framenum);
4048 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4051 ast_type_adopt(thinkfunc, functype);
4053 if (!parser_next(parser)) {
4054 ast_unref(framenum);
4055 ast_delete(thinkfunc);
4059 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4061 nextthink = (ast_expression*)thinkfunc;
4064 nextthink = parse_expression_leave(parser, true, false, false);
4066 ast_unref(framenum);
4067 parseerror(parser, "expected a think-function in [frame,think] notation");
4072 if (!ast_istype(nextthink, ast_value)) {
4073 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4077 if (retval && parser->tok != ']') {
4078 parseerror(parser, "expected closing `]` for [frame,think] notation");
4082 if (retval && !parser_next(parser)) {
4086 if (retval && parser->tok != '{') {
4087 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4092 ast_unref(nextthink);
4093 ast_unref(framenum);
4097 has_frame_think = true;
4100 block = ast_block_new(parser_ctx(parser));
4102 parseerror(parser, "failed to allocate block");
4103 if (has_frame_think) {
4104 ast_unref(nextthink);
4105 ast_unref(framenum);
4110 if (has_frame_think) {
4112 ast_expression *self_frame;
4113 ast_expression *self_nextthink;
4114 ast_expression *self_think;
4115 ast_expression *time_plus_1;
4116 ast_store *store_frame;
4117 ast_store *store_nextthink;
4118 ast_store *store_think;
4120 ctx = parser_ctx(parser);
4121 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4122 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4123 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4125 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4126 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4128 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4129 if (self_frame) ast_delete(self_frame);
4130 if (self_nextthink) ast_delete(self_nextthink);
4131 if (self_think) ast_delete(self_think);
4132 if (time_plus_1) ast_delete(time_plus_1);
4138 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4139 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4140 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4143 ast_delete(self_frame);
4146 if (!store_nextthink) {
4147 ast_delete(self_nextthink);
4151 ast_delete(self_think);
4155 if (store_frame) ast_delete(store_frame);
4156 if (store_nextthink) ast_delete(store_nextthink);
4157 if (store_think) ast_delete(store_think);
4160 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4161 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4162 !ast_block_add_expr(block, (ast_expression*)store_think))
4169 parseerror(parser, "failed to generate code for [frame,think]");
4170 ast_unref(nextthink);
4171 ast_unref(framenum);
4177 if (var->hasvalue) {
4178 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4179 ast_block_delete(block);
4183 func = ast_function_new(ast_ctx(var), var->name, var);
4185 parseerror(parser, "failed to allocate function for `%s`", var->name);
4186 ast_block_delete(block);
4189 vec_push(parser->functions, func);
4191 parser_enterblock(parser);
4193 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4195 ast_value *param = var->expression.params[parami];
4198 if (param->expression.vtype != TYPE_VECTOR &&
4199 (param->expression.vtype != TYPE_FIELD ||
4200 param->expression.next->expression.vtype != TYPE_VECTOR))
4205 if (!create_vector_members(param, me)) {
4206 ast_block_delete(block);
4210 for (e = 0; e < 3; ++e) {
4211 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4212 ast_block_collect(block, (ast_expression*)me[e]);
4216 if (var->argcounter) {
4217 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4218 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4222 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4224 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4225 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4226 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4227 varargs->expression.count = 0;
4228 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4229 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4230 ast_delete(varargs);
4231 ast_block_delete(block);
4234 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4235 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4236 ast_delete(varargs);
4237 ast_block_delete(block);
4240 func->varargs = varargs;
4242 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4245 parser->function = func;
4246 if (!parse_block_into(parser, block)) {
4247 ast_block_delete(block);
4251 vec_push(func->blocks, block);
4253 parser->function = old;
4254 if (!parser_leaveblock(parser))
4256 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4257 parseerror(parser, "internal error: local scopes left");
4261 if (parser->tok == ';')
4262 return parser_next(parser);
4263 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4264 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4268 (void)!parser_leaveblock(parser);
4269 vec_pop(parser->functions);
4270 ast_function_delete(func);
4271 var->constval.vfunc = NULL;
4274 parser->function = old;
4278 static ast_expression *array_accessor_split(
4283 ast_expression *left,
4284 ast_expression *right
4290 lex_ctx ctx = ast_ctx(array);
4292 if (!left || !right) {
4293 if (left) ast_delete(left);
4294 if (right) ast_delete(right);
4298 cmp = ast_binary_new(ctx, INSTR_LT,
4299 (ast_expression*)index,
4300 (ast_expression*)parser_const_float(parser, middle));
4304 parseerror(parser, "internal error: failed to create comparison for array setter");
4308 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4310 ast_delete(cmp); /* will delete left and right */
4311 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4315 return (ast_expression*)ifthen;
4318 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4320 lex_ctx ctx = ast_ctx(array);
4322 if (from+1 == afterend) {
4323 /* set this value */
4326 ast_array_index *subscript;
4328 int assignop = type_store_instr[value->expression.vtype];
4330 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4331 assignop = INSTR_STORE_V;
4333 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4337 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4339 ast_delete(subscript);
4343 block = ast_block_new(ctx);
4349 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4354 ret = ast_return_new(ctx, NULL);
4360 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4365 return (ast_expression*)block;
4367 ast_expression *left, *right;
4368 size_t diff = afterend - from;
4369 size_t middle = from + diff/2;
4370 left = array_setter_node(parser, array, index, value, from, middle);
4371 right = array_setter_node(parser, array, index, value, middle, afterend);
4372 return array_accessor_split(parser, array, index, middle, left, right);
4376 static ast_expression *array_field_setter_node(
4385 lex_ctx ctx = ast_ctx(array);
4387 if (from+1 == afterend) {
4388 /* set this value */
4391 ast_entfield *entfield;
4392 ast_array_index *subscript;
4394 int assignop = type_storep_instr[value->expression.vtype];
4396 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4397 assignop = INSTR_STOREP_V;
4399 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4403 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4404 subscript->expression.vtype = TYPE_FIELD;
4406 entfield = ast_entfield_new_force(ctx,
4407 (ast_expression*)entity,
4408 (ast_expression*)subscript,
4409 (ast_expression*)subscript);
4411 ast_delete(subscript);
4415 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4417 ast_delete(entfield);
4421 block = ast_block_new(ctx);
4427 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4432 ret = ast_return_new(ctx, NULL);
4438 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4443 return (ast_expression*)block;
4445 ast_expression *left, *right;
4446 size_t diff = afterend - from;
4447 size_t middle = from + diff/2;
4448 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4449 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4450 return array_accessor_split(parser, array, index, middle, left, right);
4454 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4456 lex_ctx ctx = ast_ctx(array);
4458 if (from+1 == afterend) {
4460 ast_array_index *subscript;
4462 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4466 ret = ast_return_new(ctx, (ast_expression*)subscript);
4468 ast_delete(subscript);
4472 return (ast_expression*)ret;
4474 ast_expression *left, *right;
4475 size_t diff = afterend - from;
4476 size_t middle = from + diff/2;
4477 left = array_getter_node(parser, array, index, from, middle);
4478 right = array_getter_node(parser, array, index, middle, afterend);
4479 return array_accessor_split(parser, array, index, middle, left, right);
4483 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4485 ast_function *func = NULL;
4486 ast_value *fval = NULL;
4487 ast_block *body = NULL;
4489 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4491 parseerror(parser, "failed to create accessor function value");
4495 func = ast_function_new(ast_ctx(array), funcname, fval);
4498 parseerror(parser, "failed to create accessor function node");
4502 body = ast_block_new(ast_ctx(array));
4504 parseerror(parser, "failed to create block for array accessor");
4510 vec_push(func->blocks, body);
4513 vec_push(parser->accessors, fval);
4518 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4520 ast_value *index = NULL;
4521 ast_value *value = NULL;
4525 if (!ast_istype(array->expression.next, ast_value)) {
4526 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4530 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4532 func = fval->constval.vfunc;
4533 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4535 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4536 value = ast_value_copy((ast_value*)array->expression.next);
4538 if (!index || !value) {
4539 parseerror(parser, "failed to create locals for array accessor");
4542 (void)!ast_value_set_name(value, "value"); /* not important */
4543 vec_push(fval->expression.params, index);
4544 vec_push(fval->expression.params, value);
4546 array->setter = fval;
4549 if (index) ast_delete(index);
4550 if (value) ast_delete(value);
4556 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4558 ast_expression *root = NULL;
4559 root = array_setter_node(parser, array,
4560 array->setter->expression.params[0],
4561 array->setter->expression.params[1],
4562 0, array->expression.count);
4564 parseerror(parser, "failed to build accessor search tree");
4567 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4574 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4576 if (!parser_create_array_setter_proto(parser, array, funcname))
4578 return parser_create_array_setter_impl(parser, array);
4581 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4583 ast_expression *root = NULL;
4584 ast_value *entity = NULL;
4585 ast_value *index = NULL;
4586 ast_value *value = NULL;
4590 if (!ast_istype(array->expression.next, ast_value)) {
4591 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4595 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4597 func = fval->constval.vfunc;
4598 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4600 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4601 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4602 value = ast_value_copy((ast_value*)array->expression.next);
4603 if (!entity || !index || !value) {
4604 parseerror(parser, "failed to create locals for array accessor");
4607 (void)!ast_value_set_name(value, "value"); /* not important */
4608 vec_push(fval->expression.params, entity);
4609 vec_push(fval->expression.params, index);
4610 vec_push(fval->expression.params, value);
4612 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4614 parseerror(parser, "failed to build accessor search tree");
4618 array->setter = fval;
4619 return ast_block_add_expr(func->blocks[0], root);
4621 if (entity) ast_delete(entity);
4622 if (index) ast_delete(index);
4623 if (value) ast_delete(value);
4624 if (root) ast_delete(root);
4630 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4632 ast_value *index = NULL;
4636 /* NOTE: checking array->expression.next rather than elemtype since
4637 * for fields elemtype is a temporary fieldtype.
4639 if (!ast_istype(array->expression.next, ast_value)) {
4640 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4644 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4646 func = fval->constval.vfunc;
4647 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4649 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4652 parseerror(parser, "failed to create locals for array accessor");
4655 vec_push(fval->expression.params, index);
4657 array->getter = fval;
4660 if (index) ast_delete(index);
4666 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4668 ast_expression *root = NULL;
4670 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4672 parseerror(parser, "failed to build accessor search tree");
4675 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4682 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4684 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4686 return parser_create_array_getter_impl(parser, array);
4689 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4690 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4698 bool variadic = false;
4699 ast_value *varparam = NULL;
4700 char *argcounter = NULL;
4702 ctx = parser_ctx(parser);
4704 /* for the sake of less code we parse-in in this function */
4705 if (!parser_next(parser)) {
4706 parseerror(parser, "expected parameter list");
4712 /* parse variables until we hit a closing paren */
4713 while (parser->tok != ')') {
4715 /* there must be commas between them */
4716 if (parser->tok != ',') {
4717 parseerror(parser, "expected comma or end of parameter list");
4720 if (!parser_next(parser)) {
4721 parseerror(parser, "expected parameter");
4727 if (parser->tok == TOKEN_DOTS) {
4728 /* '...' indicates a varargs function */
4730 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4731 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4734 if (parser->tok == TOKEN_IDENT) {
4735 argcounter = util_strdup(parser_tokval(parser));
4736 if (!parser_next(parser) || parser->tok != ')') {
4737 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4744 /* for anything else just parse a typename */
4745 param = parse_typename(parser, NULL, NULL);
4748 vec_push(params, param);
4749 if (param->expression.vtype >= TYPE_VARIANT) {
4750 char tname[1024]; /* typename is reserved in C++ */
4751 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4752 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4755 /* type-restricted varargs */
4756 if (parser->tok == TOKEN_DOTS) {
4758 varparam = vec_last(params);
4760 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4761 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4764 if (parser->tok == TOKEN_IDENT) {
4765 argcounter = util_strdup(parser_tokval(parser));
4766 if (!parser_next(parser) || parser->tok != ')') {
4767 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4775 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4779 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4780 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4783 if (!parser_next(parser)) {
4784 parseerror(parser, "parse error after typename");
4788 /* now turn 'var' into a function type */
4789 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4790 fval->expression.next = (ast_expression*)var;
4792 fval->expression.flags |= AST_FLAG_VARIADIC;
4795 var->expression.params = params;
4796 var->expression.varparam = (ast_expression*)varparam;
4797 var->argcounter = argcounter;
4806 ast_delete(varparam);
4808 for (i = 0; i < vec_size(params); ++i)
4809 ast_delete(params[i]);
4814 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4816 ast_expression *cexp;
4817 ast_value *cval, *tmp;
4820 ctx = parser_ctx(parser);
4822 if (!parser_next(parser)) {
4824 parseerror(parser, "expected array-size");
4828 cexp = parse_expression_leave(parser, true, false, false);
4830 if (!cexp || !ast_istype(cexp, ast_value)) {
4834 parseerror(parser, "expected array-size as constant positive integer");
4837 cval = (ast_value*)cexp;
4839 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4840 tmp->expression.next = (ast_expression*)var;
4843 if (cval->expression.vtype == TYPE_INTEGER)
4844 tmp->expression.count = cval->constval.vint;
4845 else if (cval->expression.vtype == TYPE_FLOAT)
4846 tmp->expression.count = cval->constval.vfloat;
4850 parseerror(parser, "array-size must be a positive integer constant");
4855 if (parser->tok != ']') {
4857 parseerror(parser, "expected ']' after array-size");
4860 if (!parser_next(parser)) {
4862 parseerror(parser, "error after parsing array size");
4868 /* Parse a complete typename.
4869 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4870 * but when parsing variables separated by comma
4871 * 'storebase' should point to where the base-type should be kept.
4872 * The base type makes up every bit of type information which comes *before* the
4875 * The following will be parsed in its entirety:
4877 * The 'basetype' in this case is 'void()'
4878 * and if there's a comma after it, say:
4880 * then the type-information 'void()' can be stored in 'storebase'
4882 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4884 ast_value *var, *tmp;
4887 const char *name = NULL;
4888 bool isfield = false;
4889 bool wasarray = false;
4890 size_t morefields = 0;
4892 ctx = parser_ctx(parser);
4894 /* types may start with a dot */
4895 if (parser->tok == '.') {
4897 /* if we parsed a dot we need a typename now */
4898 if (!parser_next(parser)) {
4899 parseerror(parser, "expected typename for field definition");
4903 /* Further dots are handled seperately because they won't be part of the
4906 while (parser->tok == '.') {
4908 if (!parser_next(parser)) {
4909 parseerror(parser, "expected typename for field definition");
4914 if (parser->tok == TOKEN_IDENT)
4915 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4916 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4917 parseerror(parser, "expected typename");
4921 /* generate the basic type value */
4922 if (cached_typedef) {
4923 var = ast_value_copy(cached_typedef);
4924 ast_value_set_name(var, "<type(from_def)>");
4926 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4928 for (; morefields; --morefields) {
4929 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4930 tmp->expression.next = (ast_expression*)var;
4934 /* do not yet turn into a field - remember:
4935 * .void() foo; is a field too
4936 * .void()() foo; is a function
4940 if (!parser_next(parser)) {
4942 parseerror(parser, "parse error after typename");
4946 /* an opening paren now starts the parameter-list of a function
4947 * this is where original-QC has parameter lists.
4948 * We allow a single parameter list here.
4949 * Much like fteqcc we don't allow `float()() x`
4951 if (parser->tok == '(') {
4952 var = parse_parameter_list(parser, var);
4957 /* store the base if requested */
4959 *storebase = ast_value_copy(var);
4961 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4962 tmp->expression.next = (ast_expression*)*storebase;
4967 /* there may be a name now */
4968 if (parser->tok == TOKEN_IDENT) {
4969 name = util_strdup(parser_tokval(parser));
4971 if (!parser_next(parser)) {
4973 parseerror(parser, "error after variable or field declaration");
4978 /* now this may be an array */
4979 if (parser->tok == '[') {
4981 var = parse_arraysize(parser, var);
4986 /* This is the point where we can turn it into a field */
4988 /* turn it into a field if desired */
4989 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4990 tmp->expression.next = (ast_expression*)var;
4994 /* now there may be function parens again */
4995 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4996 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4997 if (parser->tok == '(' && wasarray)
4998 parseerror(parser, "arrays as part of a return type is not supported");
4999 while (parser->tok == '(') {
5000 var = parse_parameter_list(parser, var);
5008 /* finally name it */
5010 if (!ast_value_set_name(var, name)) {
5012 parseerror(parser, "internal error: failed to set name");
5015 /* free the name, ast_value_set_name duplicates */
5022 static bool parse_typedef(parser_t *parser)
5024 ast_value *typevar, *oldtype;
5025 ast_expression *old;
5027 typevar = parse_typename(parser, NULL, NULL);
5032 if ( (old = parser_find_var(parser, typevar->name)) ) {
5033 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5034 " -> `%s` has been declared here: %s:%i",
5035 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5036 ast_delete(typevar);
5040 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5041 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5042 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5043 ast_delete(typevar);
5047 vec_push(parser->_typedefs, typevar);
5048 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5050 if (parser->tok != ';') {
5051 parseerror(parser, "expected semicolon after typedef");
5054 if (!parser_next(parser)) {
5055 parseerror(parser, "parse error after typedef");
5062 static const char *cvq_to_str(int cvq) {
5064 case CV_NONE: return "none";
5065 case CV_VAR: return "`var`";
5066 case CV_CONST: return "`const`";
5067 default: return "<INVALID>";
5071 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5074 if (proto->cvq != var->cvq) {
5075 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5076 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5077 parser->tok == '='))
5079 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5080 "`%s` declared with different qualifiers: %s\n"
5081 " -> previous declaration here: %s:%i uses %s",
5082 var->name, cvq_to_str(var->cvq),
5083 ast_ctx(proto).file, ast_ctx(proto).line,
5084 cvq_to_str(proto->cvq));
5087 av = (var ->expression.flags & AST_FLAG_NORETURN);
5088 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5090 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5091 "`%s` declared with different attributes%s\n"
5092 " -> previous declaration here: %s:%i",
5093 var->name, (av ? ": noreturn" : ""),
5094 ast_ctx(proto).file, ast_ctx(proto).line,
5095 (ao ? ": noreturn" : ""));
5100 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)
5104 ast_expression *old;
5108 ast_value *basetype = NULL;
5110 bool isparam = false;
5111 bool isvector = false;
5112 bool cleanvar = true;
5113 bool wasarray = false;
5115 ast_member *me[3] = { NULL, NULL, NULL };
5117 if (!localblock && is_static)
5118 parseerror(parser, "`static` qualifier is not supported in global scope");
5120 /* get the first complete variable */
5121 var = parse_typename(parser, &basetype, cached_typedef);
5124 ast_delete(basetype);
5132 /* Part 0: finish the type */
5133 if (parser->tok == '(') {
5134 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5135 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5136 var = parse_parameter_list(parser, var);
5142 /* we only allow 1-dimensional arrays */
5143 if (parser->tok == '[') {
5145 var = parse_arraysize(parser, var);
5151 if (parser->tok == '(' && wasarray) {
5152 parseerror(parser, "arrays as part of a return type is not supported");
5153 /* we'll still parse the type completely for now */
5155 /* for functions returning functions */
5156 while (parser->tok == '(') {
5157 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5158 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5159 var = parse_parameter_list(parser, var);
5166 var->cvq = qualifier;
5167 var->expression.flags |= qflags;
5170 * store the vstring back to var for alias and
5171 * deprecation messages.
5173 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5174 var->expression.flags & AST_FLAG_ALIAS)
5175 var->desc = vstring;
5178 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5179 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5180 * is then filled with the previous definition and the parameter-names replaced.
5182 if (!strcmp(var->name, "nil")) {
5183 if (OPTS_FLAG(UNTYPED_NIL)) {
5184 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5185 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5187 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5190 /* Deal with end_sys_ vars */
5192 if (!strcmp(var->name, "end_sys_globals")) {
5194 parser->crc_globals = vec_size(parser->globals);
5197 else if (!strcmp(var->name, "end_sys_fields")) {
5199 parser->crc_fields = vec_size(parser->fields);
5202 if (was_end && var->expression.vtype == TYPE_FIELD) {
5203 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5204 "global '%s' hint should not be a field",
5205 parser_tokval(parser)))
5212 if (!nofields && var->expression.vtype == TYPE_FIELD)
5214 /* deal with field declarations */
5215 old = parser_find_field(parser, var->name);
5217 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5218 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5227 parseerror(parser, "field `%s` already declared here: %s:%i",
5228 var->name, ast_ctx(old).file, ast_ctx(old).line);
5233 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5234 (old = parser_find_global(parser, var->name)))
5236 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5237 parseerror(parser, "field `%s` already declared here: %s:%i",
5238 var->name, ast_ctx(old).file, ast_ctx(old).line);
5245 /* deal with other globals */
5246 old = parser_find_global(parser, var->name);
5247 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5249 /* This is a function which had a prototype */
5250 if (!ast_istype(old, ast_value)) {
5251 parseerror(parser, "internal error: prototype is not an ast_value");
5255 proto = (ast_value*)old;
5256 proto->desc = var->desc;
5257 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5258 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5260 ast_ctx(proto).file, ast_ctx(proto).line);
5264 /* we need the new parameter-names */
5265 for (i = 0; i < vec_size(proto->expression.params); ++i)
5266 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5267 if (!parser_check_qualifiers(parser, var, proto)) {
5274 proto->expression.flags |= var->expression.flags;
5282 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5283 "global `%s` already declared here: %s:%i",
5284 var->name, ast_ctx(old).file, ast_ctx(old).line))
5289 proto = (ast_value*)old;
5290 if (!ast_istype(old, ast_value)) {
5291 parseerror(parser, "internal error: not an ast_value");
5296 if (!parser_check_qualifiers(parser, var, proto)) {
5301 proto->expression.flags |= var->expression.flags;
5305 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5306 (old = parser_find_field(parser, var->name)))
5308 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5309 parseerror(parser, "global `%s` already declared here: %s:%i",
5310 var->name, ast_ctx(old).file, ast_ctx(old).line);
5317 else /* it's not a global */
5319 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5320 if (old && !isparam) {
5321 parseerror(parser, "local `%s` already declared here: %s:%i",
5322 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5326 old = parser_find_local(parser, var->name, 0, &isparam);
5327 if (old && isparam) {
5328 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5329 "local `%s` is shadowing a parameter", var->name))
5331 parseerror(parser, "local `%s` already declared here: %s:%i",
5332 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5336 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5344 /* in a noref section we simply bump the usecount */
5345 if (noref || parser->noref)
5349 * Create the global/local, and deal with vector types.
5352 if (var->expression.vtype == TYPE_VECTOR)
5354 else if (var->expression.vtype == TYPE_FIELD &&
5355 var->expression.next->expression.vtype == TYPE_VECTOR)
5359 if (!create_vector_members(var, me)) {
5366 /* deal with global variables, fields, functions */
5367 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5368 var->isfield = true;
5369 vec_push(parser->fields, (ast_expression*)var);
5370 util_htset(parser->htfields, var->name, var);
5372 for (i = 0; i < 3; ++i) {
5373 vec_push(parser->fields, (ast_expression*)me[i]);
5374 util_htset(parser->htfields, me[i]->name, me[i]);
5379 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5380 parser_addglobal(parser, var->name, (ast_expression*)var);
5382 for (i = 0; i < 3; ++i) {
5383 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5387 ast_expression *find = parser_find_global(parser, var->desc);
5390 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5394 if (var->expression.vtype != find->expression.vtype) {
5398 ast_type_to_string(find, ty1, sizeof(ty1));
5399 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5401 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5408 * add alias to aliases table and to corrector
5409 * so corrections can apply for aliases as well.
5411 util_htset(parser->aliases, var->name, find);
5414 * add to corrector so corrections can work
5415 * even for aliases too.
5418 vec_last(parser->correct_variables),
5419 &vec_last(parser->correct_variables_score),
5423 /* generate aliases for vector components */
5427 util_asprintf(&buffer[0], "%s_x", var->desc);
5428 util_asprintf(&buffer[1], "%s_y", var->desc);
5429 util_asprintf(&buffer[2], "%s_z", var->desc);
5431 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5432 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5433 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5440 * add to corrector so corrections can work
5441 * even for aliases too.
5444 vec_last(parser->correct_variables),
5445 &vec_last(parser->correct_variables_score),
5449 vec_last(parser->correct_variables),
5450 &vec_last(parser->correct_variables_score),
5454 vec_last(parser->correct_variables),
5455 &vec_last(parser->correct_variables_score),
5463 /* a static adds itself to be generated like any other global
5464 * but is added to the local namespace instead
5466 char *defname = NULL;
5467 size_t prefix_len, ln;
5469 ln = strlen(parser->function->name);
5470 vec_append(defname, ln, parser->function->name);
5472 vec_append(defname, 2, "::");
5473 /* remember the length up to here */
5474 prefix_len = vec_size(defname);
5476 /* Add it to the local scope */
5477 util_htset(vec_last(parser->variables), var->name, (void*)var);
5481 vec_last(parser->correct_variables),
5482 &vec_last(parser->correct_variables_score),
5486 /* now rename the global */
5487 ln = strlen(var->name);
5488 vec_append(defname, ln, var->name);
5489 ast_value_set_name(var, defname);
5491 /* push it to the to-be-generated globals */
5492 vec_push(parser->globals, (ast_expression*)var);
5494 /* same game for the vector members */
5496 for (i = 0; i < 3; ++i) {
5497 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5501 vec_last(parser->correct_variables),
5502 &vec_last(parser->correct_variables_score),
5506 vec_shrinkto(defname, prefix_len);
5507 ln = strlen(me[i]->name);
5508 vec_append(defname, ln, me[i]->name);
5509 ast_member_set_name(me[i], defname);
5511 vec_push(parser->globals, (ast_expression*)me[i]);
5516 vec_push(localblock->locals, var);
5517 parser_addlocal(parser, var->name, (ast_expression*)var);
5519 for (i = 0; i < 3; ++i) {
5520 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5521 ast_block_collect(localblock, (ast_expression*)me[i]);
5527 me[0] = me[1] = me[2] = NULL;
5532 if (var->expression.vtype == TYPE_ARRAY) {
5534 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5535 if (!parser_create_array_setter(parser, var, name))
5537 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5538 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5541 else if (!localblock && !nofields &&
5542 var->expression.vtype == TYPE_FIELD &&
5543 var->expression.next->expression.vtype == TYPE_ARRAY)
5546 ast_expression *telem;
5548 ast_value *array = (ast_value*)var->expression.next;
5550 if (!ast_istype(var->expression.next, ast_value)) {
5551 parseerror(parser, "internal error: field element type must be an ast_value");
5555 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5556 if (!parser_create_array_field_setter(parser, array, name))
5559 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5560 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5561 tfield->expression.next = telem;
5562 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5563 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5571 if (parser->tok == ';') {
5572 ast_delete(basetype);
5573 if (!parser_next(parser)) {
5574 parseerror(parser, "error after variable declaration");
5580 if (parser->tok == ',')
5584 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5587 parseerror(parser, "missing comma or semicolon while parsing variables");
5591 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5592 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5593 "initializing expression turns variable `%s` into a constant in this standard",
5600 if (parser->tok != '{') {
5601 if (parser->tok != '=') {
5602 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5606 if (!parser_next(parser)) {
5607 parseerror(parser, "error parsing initializer");
5611 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5612 parseerror(parser, "expected '=' before function body in this standard");
5615 if (parser->tok == '#') {
5616 ast_function *func = NULL;
5619 parseerror(parser, "cannot declare builtins within functions");
5622 if (var->expression.vtype != TYPE_FUNCTION) {
5623 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5626 if (!parser_next(parser)) {
5627 parseerror(parser, "expected builtin number");
5630 if (parser->tok != TOKEN_INTCONST) {
5631 parseerror(parser, "builtin number must be an integer constant");
5634 if (parser_token(parser)->constval.i < 0) {
5635 parseerror(parser, "builtin number must be an integer greater than zero");
5639 if (var->hasvalue) {
5640 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5641 "builtin `%s` has already been defined\n"
5642 " -> previous declaration here: %s:%i",
5643 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5647 func = ast_function_new(ast_ctx(var), var->name, var);
5649 parseerror(parser, "failed to allocate function for `%s`", var->name);
5652 vec_push(parser->functions, func);
5654 func->builtin = -parser_token(parser)->constval.i-1;
5657 if (!parser_next(parser)) {
5658 parseerror(parser, "expected comma or semicolon");
5660 ast_function_delete(func);
5661 var->constval.vfunc = NULL;
5665 else if (parser->tok == '{' || parser->tok == '[')
5668 parseerror(parser, "cannot declare functions within functions");
5673 ast_ctx(proto) = parser_ctx(parser);
5675 if (!parse_function_body(parser, var))
5677 ast_delete(basetype);
5678 for (i = 0; i < vec_size(parser->gotos); ++i)
5679 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5680 vec_free(parser->gotos);
5681 vec_free(parser->labels);
5684 ast_expression *cexp;
5687 cexp = parse_expression_leave(parser, true, false, false);
5692 cval = (ast_value*)cexp;
5693 if (cval != parser->nil &&
5694 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5697 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5701 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5702 qualifier != CV_VAR)
5704 var->cvq = CV_CONST;
5706 if (cval == parser->nil)
5707 var->expression.flags |= AST_FLAG_INITIALIZED;
5710 var->hasvalue = true;
5711 if (cval->expression.vtype == TYPE_STRING)
5712 var->constval.vstring = parser_strdup(cval->constval.vstring);
5713 else if (cval->expression.vtype == TYPE_FIELD)
5714 var->constval.vfield = cval;
5716 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5722 shunt sy = { NULL, NULL, NULL, NULL };
5725 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5726 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5727 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5728 if (!parser_sy_apply_operator(parser, &sy))
5731 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5732 parseerror(parser, "internal error: leaked operands");
5733 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5743 if (parser->tok == ',') {
5744 if (!parser_next(parser)) {
5745 parseerror(parser, "expected another variable");
5749 if (parser->tok != TOKEN_IDENT) {
5750 parseerror(parser, "expected another variable");
5753 var = ast_value_copy(basetype);
5755 ast_value_set_name(var, parser_tokval(parser));
5756 if (!parser_next(parser)) {
5757 parseerror(parser, "error parsing variable declaration");
5763 if (parser->tok != ';') {
5764 parseerror(parser, "missing semicolon after variables");
5768 if (!parser_next(parser)) {
5769 parseerror(parser, "parse error after variable declaration");
5773 ast_delete(basetype);
5777 if (cleanvar && var)
5779 ast_delete(basetype);
5783 ast_delete(basetype);
5784 if (cleanvar && var)
5786 if (me[0]) ast_member_delete(me[0]);
5787 if (me[1]) ast_member_delete(me[1]);
5788 if (me[2]) ast_member_delete(me[2]);
5792 static bool parser_global_statement(parser_t *parser)
5796 bool is_static = false;
5797 uint32_t qflags = 0;
5798 ast_value *istype = NULL;
5799 char *vstring = NULL;
5801 if (parser->tok == TOKEN_IDENT)
5802 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5804 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5806 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5808 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5810 if (cvq == CV_WRONG)
5812 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5814 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5816 return parse_enum(parser);
5818 else if (parser->tok == TOKEN_KEYWORD)
5820 if (!strcmp(parser_tokval(parser), "typedef")) {
5821 if (!parser_next(parser)) {
5822 parseerror(parser, "expected type definition after 'typedef'");
5825 return parse_typedef(parser);
5827 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5830 else if (parser->tok == '#')
5832 return parse_pragma(parser);
5834 else if (parser->tok == '$')
5836 if (!parser_next(parser)) {
5837 parseerror(parser, "parse error");
5843 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5849 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5851 return util_crc16(old, str, strlen(str));
5854 static void progdefs_crc_file(const char *str)
5856 /* write to progdefs.h here */
5860 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5862 old = progdefs_crc_sum(old, str);
5863 progdefs_crc_file(str);
5867 static void generate_checksum(parser_t *parser)
5869 uint16_t crc = 0xFFFF;
5873 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5874 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5876 progdefs_crc_file("\tint\tpad;\n");
5877 progdefs_crc_file("\tint\tofs_return[3];\n");
5878 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5879 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5880 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5881 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5882 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5883 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5884 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5885 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5887 for (i = 0; i < parser->crc_globals; ++i) {
5888 if (!ast_istype(parser->globals[i], ast_value))
5890 value = (ast_value*)(parser->globals[i]);
5891 switch (value->expression.vtype) {
5892 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5893 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5894 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5895 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5897 crc = progdefs_crc_both(crc, "\tint\t");
5900 crc = progdefs_crc_both(crc, value->name);
5901 crc = progdefs_crc_both(crc, ";\n");
5903 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5904 for (i = 0; i < parser->crc_fields; ++i) {
5905 if (!ast_istype(parser->fields[i], ast_value))
5907 value = (ast_value*)(parser->fields[i]);
5908 switch (value->expression.next->expression.vtype) {
5909 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5910 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5911 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5912 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5914 crc = progdefs_crc_both(crc, "\tint\t");
5917 crc = progdefs_crc_both(crc, value->name);
5918 crc = progdefs_crc_both(crc, ";\n");
5920 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5925 parser_t *parser_create()
5931 parser = (parser_t*)mem_a(sizeof(parser_t));
5935 memset(parser, 0, sizeof(*parser));
5937 for (i = 0; i < operator_count; ++i) {
5938 if (operators[i].id == opid1('=')) {
5939 parser->assign_op = operators+i;
5943 if (!parser->assign_op) {
5944 printf("internal error: initializing parser: failed to find assign operator\n");
5949 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5950 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5951 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5952 vec_push(parser->_blocktypedefs, 0);
5954 parser->aliases = util_htnew(PARSER_HT_SIZE);
5956 parser->ht_imm_string = util_htnew(512);
5959 vec_push(parser->correct_variables, correct_trie_new());
5960 vec_push(parser->correct_variables_score, NULL);
5962 empty_ctx.file = "<internal>";
5964 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5965 parser->nil->cvq = CV_CONST;
5966 if (OPTS_FLAG(UNTYPED_NIL))
5967 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5969 parser->max_param_count = 1;
5971 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5972 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5973 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5975 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5976 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5977 parser->reserved_version->cvq = CV_CONST;
5978 parser->reserved_version->hasvalue = true;
5979 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5980 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5982 parser->reserved_version = NULL;
5988 bool parser_compile(parser_t *parser)
5990 /* initial lexer/parser state */
5991 parser->lex->flags.noops = true;
5993 if (parser_next(parser))
5995 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5997 if (!parser_global_statement(parser)) {
5998 if (parser->tok == TOKEN_EOF)
5999 parseerror(parser, "unexpected eof");
6000 else if (compile_errors)
6001 parseerror(parser, "there have been errors, bailing out");
6002 lex_close(parser->lex);
6008 parseerror(parser, "parse error");
6009 lex_close(parser->lex);
6014 lex_close(parser->lex);
6017 return !compile_errors;
6020 bool parser_compile_file(parser_t *parser, const char *filename)
6022 parser->lex = lex_open(filename);
6024 con_err("failed to open file \"%s\"\n", filename);
6027 return parser_compile(parser);
6030 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6032 parser->lex = lex_open_string(str, len, name);
6034 con_err("failed to create lexer for string \"%s\"\n", name);
6037 return parser_compile(parser);
6040 void parser_cleanup(parser_t *parser)
6043 for (i = 0; i < vec_size(parser->accessors); ++i) {
6044 ast_delete(parser->accessors[i]->constval.vfunc);
6045 parser->accessors[i]->constval.vfunc = NULL;
6046 ast_delete(parser->accessors[i]);
6048 for (i = 0; i < vec_size(parser->functions); ++i) {
6049 ast_delete(parser->functions[i]);
6051 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6052 ast_delete(parser->imm_vector[i]);
6054 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6055 ast_delete(parser->imm_string[i]);
6057 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6058 ast_delete(parser->imm_float[i]);
6060 for (i = 0; i < vec_size(parser->fields); ++i) {
6061 ast_delete(parser->fields[i]);
6063 for (i = 0; i < vec_size(parser->globals); ++i) {
6064 ast_delete(parser->globals[i]);
6066 vec_free(parser->accessors);
6067 vec_free(parser->functions);
6068 vec_free(parser->imm_vector);
6069 vec_free(parser->imm_string);
6070 util_htdel(parser->ht_imm_string);
6071 vec_free(parser->imm_float);
6072 vec_free(parser->globals);
6073 vec_free(parser->fields);
6075 for (i = 0; i < vec_size(parser->variables); ++i)
6076 util_htdel(parser->variables[i]);
6077 vec_free(parser->variables);
6078 vec_free(parser->_blocklocals);
6079 vec_free(parser->_locals);
6082 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6083 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6085 vec_free(parser->correct_variables);
6086 vec_free(parser->correct_variables_score);
6089 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6090 ast_delete(parser->_typedefs[i]);
6091 vec_free(parser->_typedefs);
6092 for (i = 0; i < vec_size(parser->typedefs); ++i)
6093 util_htdel(parser->typedefs[i]);
6094 vec_free(parser->typedefs);
6095 vec_free(parser->_blocktypedefs);
6097 vec_free(parser->_block_ctx);
6099 vec_free(parser->labels);
6100 vec_free(parser->gotos);
6101 vec_free(parser->breaks);
6102 vec_free(parser->continues);
6104 ast_value_delete(parser->nil);
6106 ast_value_delete(parser->const_vec[0]);
6107 ast_value_delete(parser->const_vec[1]);
6108 ast_value_delete(parser->const_vec[2]);
6110 util_htdel(parser->aliases);
6112 intrin_intrinsics_destroy(parser);
6117 bool parser_finish(parser_t *parser, const char *output)
6123 if (compile_errors) {
6124 con_out("*** there were compile errors\n");
6128 ir = ir_builder_new("gmqcc_out");
6130 con_out("failed to allocate builder\n");
6134 for (i = 0; i < vec_size(parser->fields); ++i) {
6137 if (!ast_istype(parser->fields[i], ast_value))
6139 field = (ast_value*)parser->fields[i];
6140 hasvalue = field->hasvalue;
6141 field->hasvalue = false;
6142 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6143 con_out("failed to generate field %s\n", field->name);
6144 ir_builder_delete(ir);
6149 ast_expression *subtype;
6150 field->hasvalue = true;
6151 subtype = field->expression.next;
6152 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6153 if (subtype->expression.vtype == TYPE_FIELD)
6154 ifld->fieldtype = subtype->expression.next->expression.vtype;
6155 else if (subtype->expression.vtype == TYPE_FUNCTION)
6156 ifld->outtype = subtype->expression.next->expression.vtype;
6157 (void)!ir_value_set_field(field->ir_v, ifld);
6160 for (i = 0; i < vec_size(parser->globals); ++i) {
6162 if (!ast_istype(parser->globals[i], ast_value))
6164 asvalue = (ast_value*)(parser->globals[i]);
6165 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6166 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6167 "unused global: `%s`", asvalue->name);
6169 if (!ast_global_codegen(asvalue, ir, false)) {
6170 con_out("failed to generate global %s\n", asvalue->name);
6171 ir_builder_delete(ir);
6175 /* Build function vararg accessor ast tree now before generating
6176 * immediates, because the accessors may add new immediates
6178 for (i = 0; i < vec_size(parser->functions); ++i) {
6179 ast_function *f = parser->functions[i];
6181 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6182 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6183 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6184 con_out("failed to generate vararg setter for %s\n", f->name);
6185 ir_builder_delete(ir);
6188 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6189 con_out("failed to generate vararg getter for %s\n", f->name);
6190 ir_builder_delete(ir);
6194 ast_delete(f->varargs);
6199 /* Now we can generate immediates */
6200 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6201 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6202 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6203 ir_builder_delete(ir);
6207 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6208 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6209 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6210 ir_builder_delete(ir);
6214 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6215 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6216 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6217 ir_builder_delete(ir);
6221 for (i = 0; i < vec_size(parser->globals); ++i) {
6223 if (!ast_istype(parser->globals[i], ast_value))
6225 asvalue = (ast_value*)(parser->globals[i]);
6226 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6228 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6229 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6230 "uninitialized constant: `%s`",
6232 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6233 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6234 "uninitialized global: `%s`",
6237 if (!ast_generate_accessors(asvalue, ir)) {
6238 ir_builder_delete(ir);
6242 for (i = 0; i < vec_size(parser->fields); ++i) {
6244 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6246 if (!ast_istype((ast_expression*)asvalue, ast_value))
6248 if (asvalue->expression.vtype != TYPE_ARRAY)
6250 if (!ast_generate_accessors(asvalue, ir)) {
6251 ir_builder_delete(ir);
6255 if (parser->reserved_version &&
6256 !ast_global_codegen(parser->reserved_version, ir, false))
6258 con_out("failed to generate reserved::version");
6259 ir_builder_delete(ir);
6262 for (i = 0; i < vec_size(parser->functions); ++i) {
6263 ast_function *f = parser->functions[i];
6264 if (!ast_function_codegen(f, ir)) {
6265 con_out("failed to generate function %s\n", f->name);
6266 ir_builder_delete(ir);
6270 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6271 ir_builder_dump(ir, con_out);
6272 for (i = 0; i < vec_size(parser->functions); ++i) {
6273 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6274 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6275 ir_builder_delete(ir);
6280 if (compile_Werrors) {
6281 con_out("*** there were warnings treated as errors\n");
6282 compile_show_werrors();
6287 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6288 ir_builder_dump(ir, con_out);
6290 generate_checksum(parser);
6292 if (!ir_builder_generate(ir, output)) {
6293 con_out("*** failed to generate output file\n");
6294 ir_builder_delete(ir);
6299 ir_builder_delete(ir);