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 = util_htgeth(parser->ht_imm_string, str, hash)) ) {
261 if (dotranslate && out->name[0] == '#') {
263 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 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 */);
1903 var = intrin_func(parser, parser_tokval(parser));
1907 char *correct = NULL;
1911 * sometimes people use preprocessing predefs without enabling them
1912 * i've done this thousands of times already myself. Lets check for
1913 * it in the predef table. And diagnose it better :)
1915 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1916 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1917 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1918 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1925 * TODO: determine the best score for the identifier: be it
1926 * a variable, a field.
1928 * We should also consider adding correction tables for
1929 * other things as well.
1931 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1933 correct_init(&corr);
1935 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1936 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1937 if (strcmp(correct, parser_tokval(parser))) {
1939 } else if (correct) {
1944 correct_free(&corr);
1947 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1952 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1958 if (ast_istype(var, ast_value)) {
1959 ((ast_value*)var)->uses++;
1961 else if (ast_istype(var, ast_member)) {
1962 ast_member *mem = (ast_member*)var;
1963 if (ast_istype(mem->owner, ast_value))
1964 ((ast_value*)(mem->owner))->uses++;
1967 vec_push(sy->out, syexp(parser_ctx(parser), var));
1970 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1974 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1976 ast_expression *expr = NULL;
1979 bool wantop = false;
1980 /* only warn once about an assignment in a truth value because the current code
1981 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1983 bool warn_truthvalue = true;
1985 /* count the parens because an if starts with one, so the
1986 * end of a condition is an unmatched closing paren
1990 memset(&sy, 0, sizeof(sy));
1992 parser->lex->flags.noops = false;
1994 parser_reclassify_token(parser);
1998 if (parser->tok == TOKEN_TYPENAME) {
1999 parseerror(parser, "unexpected typename");
2003 if (parser->tok == TOKEN_OPERATOR)
2005 /* classify the operator */
2006 const oper_info *op;
2007 const oper_info *olast = NULL;
2009 for (o = 0; o < operator_count; ++o) {
2010 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2011 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2012 !strcmp(parser_tokval(parser), operators[o].op))
2017 if (o == operator_count) {
2018 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2021 /* found an operator */
2024 /* when declaring variables, a comma starts a new variable */
2025 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2026 /* fixup the token */
2031 /* a colon without a pervious question mark cannot be a ternary */
2032 if (!ternaries && op->id == opid2(':','?')) {
2037 if (op->id == opid1(',')) {
2038 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2039 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2043 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2044 olast = &operators[vec_last(sy.ops).etype-1];
2046 #define IsAssignOp(x) (\
2047 (x) == opid1('=') || \
2048 (x) == opid2('+','=') || \
2049 (x) == opid2('-','=') || \
2050 (x) == opid2('*','=') || \
2051 (x) == opid2('/','=') || \
2052 (x) == opid2('%','=') || \
2053 (x) == opid2('&','=') || \
2054 (x) == opid2('|','=') || \
2055 (x) == opid3('&','~','=') \
2057 if (warn_truthvalue) {
2058 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2059 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2060 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2063 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2064 warn_truthvalue = false;
2069 (op->prec < olast->prec) ||
2070 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2072 if (!parser_sy_apply_operator(parser, &sy))
2074 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2075 olast = &operators[vec_last(sy.ops).etype-1];
2080 if (op->id == opid1('(')) {
2082 size_t sycount = vec_size(sy.out);
2083 /* we expected an operator, this is the function-call operator */
2084 vec_push(sy.paren, PAREN_FUNC);
2085 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2086 vec_push(sy.argc, 0);
2088 vec_push(sy.paren, PAREN_EXPR);
2089 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2092 } else if (op->id == opid1('[')) {
2094 parseerror(parser, "unexpected array subscript");
2097 vec_push(sy.paren, PAREN_INDEX);
2098 /* push both the operator and the paren, this makes life easier */
2099 vec_push(sy.ops, syop(parser_ctx(parser), op));
2100 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2102 } else if (op->id == opid2('?',':')) {
2103 vec_push(sy.ops, syop(parser_ctx(parser), op));
2104 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2107 vec_push(sy.paren, PAREN_TERNARY1);
2108 } else if (op->id == opid2(':','?')) {
2109 if (!vec_size(sy.paren)) {
2110 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2113 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2114 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2117 if (!parser_close_paren(parser, &sy))
2119 vec_push(sy.ops, syop(parser_ctx(parser), op));
2123 vec_push(sy.ops, syop(parser_ctx(parser), op));
2124 wantop = !!(op->flags & OP_SUFFIX);
2127 else if (parser->tok == ')') {
2128 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2129 if (!parser_sy_apply_operator(parser, &sy))
2132 if (!vec_size(sy.paren))
2135 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2136 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2139 if (!parser_close_paren(parser, &sy))
2142 /* must be a function call without parameters */
2143 if (vec_last(sy.paren) != PAREN_FUNC) {
2144 parseerror(parser, "closing paren in invalid position");
2147 if (!parser_close_paren(parser, &sy))
2152 else if (parser->tok == '(') {
2153 parseerror(parser, "internal error: '(' should be classified as operator");
2156 else if (parser->tok == '[') {
2157 parseerror(parser, "internal error: '[' should be classified as operator");
2160 else if (parser->tok == ']') {
2161 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2162 if (!parser_sy_apply_operator(parser, &sy))
2165 if (!vec_size(sy.paren))
2167 if (vec_last(sy.paren) != PAREN_INDEX) {
2168 parseerror(parser, "mismatched parentheses, unexpected ']'");
2171 if (!parser_close_paren(parser, &sy))
2176 if (!parse_sya_operand(parser, &sy, with_labels))
2179 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2180 vec_last(sy.argc)++;
2185 parseerror(parser, "expected operator or end of statement");
2189 if (!parser_next(parser)) {
2192 if (parser->tok == ';' ||
2193 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2194 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2200 while (vec_size(sy.ops)) {
2201 if (!parser_sy_apply_operator(parser, &sy))
2205 parser->lex->flags.noops = true;
2206 if (!vec_size(sy.out)) {
2207 parseerror(parser, "empty expression");
2210 expr = sy.out[0].out;
2213 if (vec_size(sy.paren)) {
2214 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2222 parser->lex->flags.noops = true;
2223 for (i = 0; i < vec_size(sy.out); ++i) {
2225 ast_unref(sy.out[i].out);
2234 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2236 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2239 if (parser->tok != ';') {
2240 parseerror(parser, "semicolon expected after expression");
2244 if (!parser_next(parser)) {
2251 static void parser_enterblock(parser_t *parser)
2253 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2254 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2255 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2256 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2257 vec_push(parser->_block_ctx, parser_ctx(parser));
2260 vec_push(parser->correct_variables, correct_trie_new());
2261 vec_push(parser->correct_variables_score, NULL);
2264 static bool parser_leaveblock(parser_t *parser)
2267 size_t locals, typedefs;
2269 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2270 parseerror(parser, "internal error: parser_leaveblock with no block");
2274 util_htdel(vec_last(parser->variables));
2275 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2277 vec_pop(parser->variables);
2278 vec_pop(parser->correct_variables);
2279 vec_pop(parser->correct_variables_score);
2280 if (!vec_size(parser->_blocklocals)) {
2281 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2285 locals = vec_last(parser->_blocklocals);
2286 vec_pop(parser->_blocklocals);
2287 while (vec_size(parser->_locals) != locals) {
2288 ast_expression *e = vec_last(parser->_locals);
2289 ast_value *v = (ast_value*)e;
2290 vec_pop(parser->_locals);
2291 if (ast_istype(e, ast_value) && !v->uses) {
2292 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2297 typedefs = vec_last(parser->_blocktypedefs);
2298 while (vec_size(parser->_typedefs) != typedefs) {
2299 ast_delete(vec_last(parser->_typedefs));
2300 vec_pop(parser->_typedefs);
2302 util_htdel(vec_last(parser->typedefs));
2303 vec_pop(parser->typedefs);
2305 vec_pop(parser->_block_ctx);
2310 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2312 vec_push(parser->_locals, e);
2313 util_htset(vec_last(parser->variables), name, (void*)e);
2317 vec_last(parser->correct_variables),
2318 &vec_last(parser->correct_variables_score),
2323 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2325 vec_push(parser->globals, e);
2326 util_htset(parser->htglobals, name, e);
2330 parser->correct_variables[0],
2331 &parser->correct_variables_score[0],
2336 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2340 ast_expression *prev;
2342 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2344 ast_type_to_string(cond, ty, sizeof(ty));
2345 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2348 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2351 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2354 parseerror(parser, "internal error: failed to process condition");
2359 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2361 /* vector types need to be cast to true booleans */
2362 ast_binary *bin = (ast_binary*)cond;
2363 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2365 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2367 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2370 parseerror(parser, "internal error: failed to process condition");
2377 unary = (ast_unary*)cond;
2378 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2380 cond = unary->operand;
2381 unary->operand = NULL;
2384 unary = (ast_unary*)cond;
2388 parseerror(parser, "internal error: failed to process condition");
2390 if (ifnot) *_ifnot = !*_ifnot;
2394 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2397 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2400 lex_ctx ctx = parser_ctx(parser);
2402 (void)block; /* not touching */
2404 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2405 if (!parser_next(parser)) {
2406 parseerror(parser, "expected condition or 'not'");
2409 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2411 if (!parser_next(parser)) {
2412 parseerror(parser, "expected condition in parenthesis");
2416 if (parser->tok != '(') {
2417 parseerror(parser, "expected 'if' condition in parenthesis");
2420 /* parse into the expression */
2421 if (!parser_next(parser)) {
2422 parseerror(parser, "expected 'if' condition after opening paren");
2425 /* parse the condition */
2426 cond = parse_expression_leave(parser, false, true, false);
2430 if (parser->tok != ')') {
2431 parseerror(parser, "expected closing paren after 'if' condition");
2435 /* parse into the 'then' branch */
2436 if (!parser_next(parser)) {
2437 parseerror(parser, "expected statement for on-true branch of 'if'");
2441 if (!parse_statement_or_block(parser, &ontrue)) {
2446 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2447 /* check for an else */
2448 if (!strcmp(parser_tokval(parser), "else")) {
2449 /* parse into the 'else' branch */
2450 if (!parser_next(parser)) {
2451 parseerror(parser, "expected on-false branch after 'else'");
2456 if (!parse_statement_or_block(parser, &onfalse)) {
2463 cond = process_condition(parser, cond, &ifnot);
2465 if (ontrue) ast_delete(ontrue);
2466 if (onfalse) ast_delete(onfalse);
2471 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2473 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2474 *out = (ast_expression*)ifthen;
2478 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2479 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2484 /* skip the 'while' and get the body */
2485 if (!parser_next(parser)) {
2486 if (OPTS_FLAG(LOOP_LABELS))
2487 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2489 parseerror(parser, "expected 'while' condition in parenthesis");
2493 if (parser->tok == ':') {
2494 if (!OPTS_FLAG(LOOP_LABELS))
2495 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2496 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2497 parseerror(parser, "expected loop label");
2500 label = util_strdup(parser_tokval(parser));
2501 if (!parser_next(parser)) {
2503 parseerror(parser, "expected 'while' condition in parenthesis");
2508 if (parser->tok != '(') {
2509 parseerror(parser, "expected 'while' condition in parenthesis");
2513 vec_push(parser->breaks, label);
2514 vec_push(parser->continues, label);
2516 rv = parse_while_go(parser, block, out);
2519 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2520 parseerror(parser, "internal error: label stack corrupted");
2526 vec_pop(parser->breaks);
2527 vec_pop(parser->continues);
2532 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2535 ast_expression *cond, *ontrue;
2539 lex_ctx ctx = parser_ctx(parser);
2541 (void)block; /* not touching */
2543 /* parse into the expression */
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "expected 'while' condition after opening paren");
2548 /* parse the condition */
2549 cond = parse_expression_leave(parser, false, true, false);
2553 if (parser->tok != ')') {
2554 parseerror(parser, "expected closing paren after 'while' condition");
2558 /* parse into the 'then' branch */
2559 if (!parser_next(parser)) {
2560 parseerror(parser, "expected while-loop body");
2564 if (!parse_statement_or_block(parser, &ontrue)) {
2569 cond = process_condition(parser, cond, &ifnot);
2574 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2575 *out = (ast_expression*)aloop;
2579 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2580 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2585 /* skip the 'do' and get the body */
2586 if (!parser_next(parser)) {
2587 if (OPTS_FLAG(LOOP_LABELS))
2588 parseerror(parser, "expected loop label or body");
2590 parseerror(parser, "expected loop body");
2594 if (parser->tok == ':') {
2595 if (!OPTS_FLAG(LOOP_LABELS))
2596 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2597 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2598 parseerror(parser, "expected loop label");
2601 label = util_strdup(parser_tokval(parser));
2602 if (!parser_next(parser)) {
2604 parseerror(parser, "expected loop body");
2609 vec_push(parser->breaks, label);
2610 vec_push(parser->continues, label);
2612 rv = parse_dowhile_go(parser, block, out);
2615 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2616 parseerror(parser, "internal error: label stack corrupted");
2622 vec_pop(parser->breaks);
2623 vec_pop(parser->continues);
2628 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2631 ast_expression *cond, *ontrue;
2635 lex_ctx ctx = parser_ctx(parser);
2637 (void)block; /* not touching */
2639 if (!parse_statement_or_block(parser, &ontrue))
2642 /* expect the "while" */
2643 if (parser->tok != TOKEN_KEYWORD ||
2644 strcmp(parser_tokval(parser), "while"))
2646 parseerror(parser, "expected 'while' and condition");
2651 /* skip the 'while' and check for opening paren */
2652 if (!parser_next(parser) || parser->tok != '(') {
2653 parseerror(parser, "expected 'while' condition in parenthesis");
2657 /* parse into the expression */
2658 if (!parser_next(parser)) {
2659 parseerror(parser, "expected 'while' condition after opening paren");
2663 /* parse the condition */
2664 cond = parse_expression_leave(parser, false, true, false);
2668 if (parser->tok != ')') {
2669 parseerror(parser, "expected closing paren after 'while' condition");
2675 if (!parser_next(parser) || parser->tok != ';') {
2676 parseerror(parser, "expected semicolon after condition");
2682 if (!parser_next(parser)) {
2683 parseerror(parser, "parse error");
2689 cond = process_condition(parser, cond, &ifnot);
2694 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2695 *out = (ast_expression*)aloop;
2699 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2700 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2705 /* skip the 'for' and check for opening paren */
2706 if (!parser_next(parser)) {
2707 if (OPTS_FLAG(LOOP_LABELS))
2708 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2710 parseerror(parser, "expected 'for' expressions in parenthesis");
2714 if (parser->tok == ':') {
2715 if (!OPTS_FLAG(LOOP_LABELS))
2716 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2717 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2718 parseerror(parser, "expected loop label");
2721 label = util_strdup(parser_tokval(parser));
2722 if (!parser_next(parser)) {
2724 parseerror(parser, "expected 'for' expressions in parenthesis");
2729 if (parser->tok != '(') {
2730 parseerror(parser, "expected 'for' expressions in parenthesis");
2734 vec_push(parser->breaks, label);
2735 vec_push(parser->continues, label);
2737 rv = parse_for_go(parser, block, out);
2740 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2741 parseerror(parser, "internal error: label stack corrupted");
2747 vec_pop(parser->breaks);
2748 vec_pop(parser->continues);
2752 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2755 ast_expression *initexpr, *cond, *increment, *ontrue;
2761 lex_ctx ctx = parser_ctx(parser);
2763 parser_enterblock(parser);
2770 /* parse into the expression */
2771 if (!parser_next(parser)) {
2772 parseerror(parser, "expected 'for' initializer after opening paren");
2777 if (parser->tok == TOKEN_IDENT)
2778 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2780 if (typevar || parser->tok == TOKEN_TYPENAME) {
2782 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2783 if (parsewarning(parser, WARN_EXTENSIONS,
2784 "current standard does not allow variable declarations in for-loop initializers"))
2788 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2791 else if (parser->tok != ';')
2793 initexpr = parse_expression_leave(parser, false, false, false);
2798 /* move on to condition */
2799 if (parser->tok != ';') {
2800 parseerror(parser, "expected semicolon after for-loop initializer");
2803 if (!parser_next(parser)) {
2804 parseerror(parser, "expected for-loop condition");
2808 /* parse the condition */
2809 if (parser->tok != ';') {
2810 cond = parse_expression_leave(parser, false, true, false);
2815 /* move on to incrementor */
2816 if (parser->tok != ';') {
2817 parseerror(parser, "expected semicolon after for-loop initializer");
2820 if (!parser_next(parser)) {
2821 parseerror(parser, "expected for-loop condition");
2825 /* parse the incrementor */
2826 if (parser->tok != ')') {
2827 lex_ctx condctx = parser_ctx(parser);
2828 increment = parse_expression_leave(parser, false, false, false);
2831 if (!ast_side_effects(increment)) {
2832 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2838 if (parser->tok != ')') {
2839 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2842 /* parse into the 'then' branch */
2843 if (!parser_next(parser)) {
2844 parseerror(parser, "expected for-loop body");
2847 if (!parse_statement_or_block(parser, &ontrue))
2851 cond = process_condition(parser, cond, &ifnot);
2855 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2856 *out = (ast_expression*)aloop;
2858 if (!parser_leaveblock(parser))
2862 if (initexpr) ast_delete(initexpr);
2863 if (cond) ast_delete(cond);
2864 if (increment) ast_delete(increment);
2865 (void)!parser_leaveblock(parser);
2869 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2871 ast_expression *exp = NULL;
2872 ast_return *ret = NULL;
2873 ast_value *expected = parser->function->vtype;
2875 lex_ctx ctx = parser_ctx(parser);
2877 (void)block; /* not touching */
2879 if (!parser_next(parser)) {
2880 parseerror(parser, "expected return expression");
2884 if (parser->tok != ';') {
2885 exp = parse_expression(parser, false, false);
2889 if (exp->expression.vtype != TYPE_NIL &&
2890 exp->expression.vtype != expected->expression.next->expression.vtype)
2892 parseerror(parser, "return with invalid expression");
2895 ret = ast_return_new(ctx, exp);
2901 if (!parser_next(parser))
2902 parseerror(parser, "parse error");
2903 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2904 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2906 ret = ast_return_new(ctx, NULL);
2908 *out = (ast_expression*)ret;
2912 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2915 unsigned int levels = 0;
2916 lex_ctx ctx = parser_ctx(parser);
2917 const char **loops = (is_continue ? parser->continues : parser->breaks);
2919 (void)block; /* not touching */
2920 if (!parser_next(parser)) {
2921 parseerror(parser, "expected semicolon or loop label");
2925 if (!vec_size(loops)) {
2927 parseerror(parser, "`continue` can only be used inside loops");
2929 parseerror(parser, "`break` can only be used inside loops or switches");
2932 if (parser->tok == TOKEN_IDENT) {
2933 if (!OPTS_FLAG(LOOP_LABELS))
2934 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2935 i = vec_size(loops);
2937 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2940 parseerror(parser, "no such loop to %s: `%s`",
2941 (is_continue ? "continue" : "break out of"),
2942 parser_tokval(parser));
2947 if (!parser_next(parser)) {
2948 parseerror(parser, "expected semicolon");
2953 if (parser->tok != ';') {
2954 parseerror(parser, "expected semicolon");
2958 if (!parser_next(parser))
2959 parseerror(parser, "parse error");
2961 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2965 /* returns true when it was a variable qualifier, false otherwise!
2966 * on error, cvq is set to CV_WRONG
2968 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2970 bool had_const = false;
2971 bool had_var = false;
2972 bool had_noref = false;
2973 bool had_attrib = false;
2974 bool had_static = false;
2979 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2981 /* parse an attribute */
2982 if (!parser_next(parser)) {
2983 parseerror(parser, "expected attribute after `[[`");
2987 if (!strcmp(parser_tokval(parser), "noreturn")) {
2988 flags |= AST_FLAG_NORETURN;
2989 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2990 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2995 else if (!strcmp(parser_tokval(parser), "noref")) {
2997 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2998 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3003 else if (!strcmp(parser_tokval(parser), "inline")) {
3004 flags |= AST_FLAG_INLINE;
3005 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3006 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3011 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3012 flags |= AST_FLAG_ALIAS;
3015 if (!parser_next(parser)) {
3016 parseerror(parser, "parse error in attribute");
3020 if (parser->tok == '(') {
3021 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3022 parseerror(parser, "`alias` attribute missing parameter");
3026 *message = util_strdup(parser_tokval(parser));
3028 if (!parser_next(parser)) {
3029 parseerror(parser, "parse error in attribute");
3033 if (parser->tok != ')') {
3034 parseerror(parser, "`alias` attribute expected `)` after parameter");
3038 if (!parser_next(parser)) {
3039 parseerror(parser, "parse error in attribute");
3044 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3045 parseerror(parser, "`alias` attribute expected `]]`");
3049 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3050 flags |= AST_FLAG_DEPRECATED;
3053 if (!parser_next(parser)) {
3054 parseerror(parser, "parse error in attribute");
3058 if (parser->tok == '(') {
3059 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3060 parseerror(parser, "`deprecated` attribute missing parameter");
3064 *message = util_strdup(parser_tokval(parser));
3066 if (!parser_next(parser)) {
3067 parseerror(parser, "parse error in attribute");
3071 if(parser->tok != ')') {
3072 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3076 if (!parser_next(parser)) {
3077 parseerror(parser, "parse error in attribute");
3082 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3083 parseerror(parser, "`deprecated` attribute expected `]]`");
3086 if (*message) mem_d(*message);
3094 /* Skip tokens until we hit a ]] */
3095 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3096 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3097 if (!parser_next(parser)) {
3098 parseerror(parser, "error inside attribute");
3105 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3107 else if (!strcmp(parser_tokval(parser), "const"))
3109 else if (!strcmp(parser_tokval(parser), "var"))
3111 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3113 else if (!strcmp(parser_tokval(parser), "noref"))
3115 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3120 if (!parser_next(parser))
3130 *is_static = had_static;
3134 parseerror(parser, "parse error after variable qualifier");
3139 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3140 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3145 /* skip the 'while' and get the body */
3146 if (!parser_next(parser)) {
3147 if (OPTS_FLAG(LOOP_LABELS))
3148 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3150 parseerror(parser, "expected 'switch' operand in parenthesis");
3154 if (parser->tok == ':') {
3155 if (!OPTS_FLAG(LOOP_LABELS))
3156 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3157 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3158 parseerror(parser, "expected loop label");
3161 label = util_strdup(parser_tokval(parser));
3162 if (!parser_next(parser)) {
3164 parseerror(parser, "expected 'switch' operand in parenthesis");
3169 if (parser->tok != '(') {
3170 parseerror(parser, "expected 'switch' operand in parenthesis");
3174 vec_push(parser->breaks, label);
3176 rv = parse_switch_go(parser, block, out);
3179 if (vec_last(parser->breaks) != label) {
3180 parseerror(parser, "internal error: label stack corrupted");
3186 vec_pop(parser->breaks);
3191 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3193 ast_expression *operand;
3196 ast_switch *switchnode;
3197 ast_switch_case swcase;
3200 bool noref, is_static;
3201 uint32_t qflags = 0;
3203 lex_ctx ctx = parser_ctx(parser);
3205 (void)block; /* not touching */
3208 /* parse into the expression */
3209 if (!parser_next(parser)) {
3210 parseerror(parser, "expected switch operand");
3213 /* parse the operand */
3214 operand = parse_expression_leave(parser, false, false, false);
3218 switchnode = ast_switch_new(ctx, operand);
3221 if (parser->tok != ')') {
3222 ast_delete(switchnode);
3223 parseerror(parser, "expected closing paren after 'switch' operand");
3227 /* parse over the opening paren */
3228 if (!parser_next(parser) || parser->tok != '{') {
3229 ast_delete(switchnode);
3230 parseerror(parser, "expected list of cases");
3234 if (!parser_next(parser)) {
3235 ast_delete(switchnode);
3236 parseerror(parser, "expected 'case' or 'default'");
3240 /* new block; allow some variables to be declared here */
3241 parser_enterblock(parser);
3244 if (parser->tok == TOKEN_IDENT)
3245 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3246 if (typevar || parser->tok == TOKEN_TYPENAME) {
3247 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3248 ast_delete(switchnode);
3253 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3255 if (cvq == CV_WRONG) {
3256 ast_delete(switchnode);
3259 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3260 ast_delete(switchnode);
3269 while (parser->tok != '}') {
3270 ast_block *caseblock;
3272 if (!strcmp(parser_tokval(parser), "case")) {
3273 if (!parser_next(parser)) {
3274 ast_delete(switchnode);
3275 parseerror(parser, "expected expression for case");
3278 swcase.value = parse_expression_leave(parser, false, false, false);
3279 if (!swcase.value) {
3280 ast_delete(switchnode);
3281 parseerror(parser, "expected expression for case");
3284 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3285 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3286 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3292 else if (!strcmp(parser_tokval(parser), "default")) {
3293 swcase.value = NULL;
3294 if (!parser_next(parser)) {
3295 ast_delete(switchnode);
3296 parseerror(parser, "expected colon");
3301 ast_delete(switchnode);
3302 parseerror(parser, "expected 'case' or 'default'");
3306 /* Now the colon and body */
3307 if (parser->tok != ':') {
3308 if (swcase.value) ast_unref(swcase.value);
3309 ast_delete(switchnode);
3310 parseerror(parser, "expected colon");
3314 if (!parser_next(parser)) {
3315 if (swcase.value) ast_unref(swcase.value);
3316 ast_delete(switchnode);
3317 parseerror(parser, "expected statements or case");
3320 caseblock = ast_block_new(parser_ctx(parser));
3322 if (swcase.value) ast_unref(swcase.value);
3323 ast_delete(switchnode);
3326 swcase.code = (ast_expression*)caseblock;
3327 vec_push(switchnode->cases, swcase);
3329 ast_expression *expr;
3330 if (parser->tok == '}')
3332 if (parser->tok == TOKEN_KEYWORD) {
3333 if (!strcmp(parser_tokval(parser), "case") ||
3334 !strcmp(parser_tokval(parser), "default"))
3339 if (!parse_statement(parser, caseblock, &expr, true)) {
3340 ast_delete(switchnode);
3345 if (!ast_block_add_expr(caseblock, expr)) {
3346 ast_delete(switchnode);
3352 parser_leaveblock(parser);
3355 if (parser->tok != '}') {
3356 ast_delete(switchnode);
3357 parseerror(parser, "expected closing paren of case list");
3360 if (!parser_next(parser)) {
3361 ast_delete(switchnode);
3362 parseerror(parser, "parse error after switch");
3365 *out = (ast_expression*)switchnode;
3369 /* parse computed goto sides */
3370 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3371 ast_expression *on_true;
3372 ast_expression *on_false;
3373 ast_expression *cond;
3378 if (ast_istype(*side, ast_ternary)) {
3379 ast_ternary *tern = (ast_ternary*)*side;
3380 on_true = parse_goto_computed(parser, &tern->on_true);
3381 on_false = parse_goto_computed(parser, &tern->on_false);
3383 if (!on_true || !on_false) {
3384 parseerror(parser, "expected label or expression in ternary");
3385 if (on_true) ast_unref(on_true);
3386 if (on_false) ast_unref(on_false);
3394 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3395 } else if (ast_istype(*side, ast_label)) {
3396 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3397 ast_goto_set_label(gt, ((ast_label*)*side));
3399 return (ast_expression*)gt;
3404 static bool parse_goto(parser_t *parser, ast_expression **out)
3406 ast_goto *gt = NULL;
3407 ast_expression *lbl;
3409 if (!parser_next(parser))
3412 if (parser->tok != TOKEN_IDENT) {
3413 ast_expression *expression;
3415 /* could be an expression i.e computed goto :-) */
3416 if (parser->tok != '(') {
3417 parseerror(parser, "expected label name after `goto`");
3421 /* failed to parse expression for goto */
3422 if (!(expression = parse_expression(parser, false, true)) ||
3423 !(*out = parse_goto_computed(parser, &expression))) {
3424 parseerror(parser, "invalid goto expression");
3425 ast_unref(expression);
3432 /* not computed goto */
3433 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3434 lbl = parser_find_label(parser, gt->name);
3436 if (!ast_istype(lbl, ast_label)) {
3437 parseerror(parser, "internal error: label is not an ast_label");
3441 ast_goto_set_label(gt, (ast_label*)lbl);
3444 vec_push(parser->gotos, gt);
3446 if (!parser_next(parser) || parser->tok != ';') {
3447 parseerror(parser, "semicolon expected after goto label");
3450 if (!parser_next(parser)) {
3451 parseerror(parser, "parse error after goto");
3455 *out = (ast_expression*)gt;
3459 static bool parse_skipwhite(parser_t *parser)
3462 if (!parser_next(parser))
3464 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3465 return parser->tok < TOKEN_ERROR;
3468 static bool parse_eol(parser_t *parser)
3470 if (!parse_skipwhite(parser))
3472 return parser->tok == TOKEN_EOL;
3475 static bool parse_pragma_do(parser_t *parser)
3477 if (!parser_next(parser) ||
3478 parser->tok != TOKEN_IDENT ||
3479 strcmp(parser_tokval(parser), "pragma"))
3481 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3484 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3485 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3489 if (!strcmp(parser_tokval(parser), "noref")) {
3490 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3491 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3494 parser->noref = !!parser_token(parser)->constval.i;
3495 if (!parse_eol(parser)) {
3496 parseerror(parser, "parse error after `noref` pragma");
3502 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3509 static bool parse_pragma(parser_t *parser)
3512 parser->lex->flags.preprocessing = true;
3513 parser->lex->flags.mergelines = true;
3514 rv = parse_pragma_do(parser);
3515 if (parser->tok != TOKEN_EOL) {
3516 parseerror(parser, "junk after pragma");
3519 parser->lex->flags.preprocessing = false;
3520 parser->lex->flags.mergelines = false;
3521 if (!parser_next(parser)) {
3522 parseerror(parser, "parse error after pragma");
3528 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3530 bool noref, is_static;
3532 uint32_t qflags = 0;
3533 ast_value *typevar = NULL;
3534 char *vstring = NULL;
3538 if (parser->tok == TOKEN_IDENT)
3539 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3541 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3543 /* local variable */
3545 parseerror(parser, "cannot declare a variable from here");
3548 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3549 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3552 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3556 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3558 if (cvq == CV_WRONG)
3560 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3562 else if (parser->tok == TOKEN_KEYWORD)
3564 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3569 if (!parser_next(parser)) {
3570 parseerror(parser, "parse error after __builtin_debug_printtype");
3574 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3576 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3577 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3578 if (!parser_next(parser)) {
3579 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3585 if (!parse_statement(parser, block, out, allow_cases))
3588 con_out("__builtin_debug_printtype: got no output node\n");
3591 ast_type_to_string(*out, ty, sizeof(ty));
3592 con_out("__builtin_debug_printtype: `%s`\n", ty);
3597 else if (!strcmp(parser_tokval(parser), "return"))
3599 return parse_return(parser, block, out);
3601 else if (!strcmp(parser_tokval(parser), "if"))
3603 return parse_if(parser, block, out);
3605 else if (!strcmp(parser_tokval(parser), "while"))
3607 return parse_while(parser, block, out);
3609 else if (!strcmp(parser_tokval(parser), "do"))
3611 return parse_dowhile(parser, block, out);
3613 else if (!strcmp(parser_tokval(parser), "for"))
3615 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3616 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3619 return parse_for(parser, block, out);
3621 else if (!strcmp(parser_tokval(parser), "break"))
3623 return parse_break_continue(parser, block, out, false);
3625 else if (!strcmp(parser_tokval(parser), "continue"))
3627 return parse_break_continue(parser, block, out, true);
3629 else if (!strcmp(parser_tokval(parser), "switch"))
3631 return parse_switch(parser, block, out);
3633 else if (!strcmp(parser_tokval(parser), "case") ||
3634 !strcmp(parser_tokval(parser), "default"))
3637 parseerror(parser, "unexpected 'case' label");
3642 else if (!strcmp(parser_tokval(parser), "goto"))
3644 return parse_goto(parser, out);
3646 else if (!strcmp(parser_tokval(parser), "typedef"))
3648 if (!parser_next(parser)) {
3649 parseerror(parser, "expected type definition after 'typedef'");
3652 return parse_typedef(parser);
3654 parseerror(parser, "Unexpected keyword");
3657 else if (parser->tok == '{')
3660 inner = parse_block(parser);
3663 *out = (ast_expression*)inner;
3666 else if (parser->tok == ':')
3670 if (!parser_next(parser)) {
3671 parseerror(parser, "expected label name");
3674 if (parser->tok != TOKEN_IDENT) {
3675 parseerror(parser, "label must be an identifier");
3678 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3680 if (!label->undefined) {
3681 parseerror(parser, "label `%s` already defined", label->name);
3684 label->undefined = false;
3687 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3688 vec_push(parser->labels, label);
3690 *out = (ast_expression*)label;
3691 if (!parser_next(parser)) {
3692 parseerror(parser, "parse error after label");
3695 for (i = 0; i < vec_size(parser->gotos); ++i) {
3696 if (!strcmp(parser->gotos[i]->name, label->name)) {
3697 ast_goto_set_label(parser->gotos[i], label);
3698 vec_remove(parser->gotos, i, 1);
3704 else if (parser->tok == ';')
3706 if (!parser_next(parser)) {
3707 parseerror(parser, "parse error after empty statement");
3714 lex_ctx ctx = parser_ctx(parser);
3715 ast_expression *exp = parse_expression(parser, false, false);
3719 if (!ast_side_effects(exp)) {
3720 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3727 static bool parse_enum(parser_t *parser)
3730 bool reverse = false;
3732 ast_value **values = NULL;
3733 ast_value *var = NULL;
3736 ast_expression *old;
3738 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3739 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3743 /* enumeration attributes (can add more later) */
3744 if (parser->tok == ':') {
3745 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3746 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3751 if (!strcmp(parser_tokval(parser), "flag")) {
3755 else if (!strcmp(parser_tokval(parser), "reverse")) {
3759 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3763 if (!parser_next(parser) || parser->tok != '{') {
3764 parseerror(parser, "expected `{` after enum attribute ");
3770 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3771 if (parser->tok == '}') {
3772 /* allow an empty enum */
3775 parseerror(parser, "expected identifier or `}`");
3779 old = parser_find_field(parser, parser_tokval(parser));
3781 old = parser_find_global(parser, parser_tokval(parser));
3783 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3784 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3788 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3789 vec_push(values, var);
3790 var->cvq = CV_CONST;
3791 var->hasvalue = true;
3793 /* for flagged enumerations increment in POTs of TWO */
3794 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3795 parser_addglobal(parser, var->name, (ast_expression*)var);
3797 if (!parser_next(parser)) {
3798 parseerror(parser, "expected `=`, `}` or comma after identifier");
3802 if (parser->tok == ',')
3804 if (parser->tok == '}')
3806 if (parser->tok != '=') {
3807 parseerror(parser, "expected `=`, `}` or comma after identifier");
3811 if (!parser_next(parser)) {
3812 parseerror(parser, "expected expression after `=`");
3816 /* We got a value! */
3817 old = parse_expression_leave(parser, true, false, false);
3818 asvalue = (ast_value*)old;
3819 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3820 compile_error(ast_ctx(var), "constant value or expression expected");
3823 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3825 if (parser->tok == '}')
3827 if (parser->tok != ',') {
3828 parseerror(parser, "expected `}` or comma after expression");
3833 /* patch them all (for reversed attribute) */
3836 for (i = 0; i < vec_size(values); i++)
3837 values[i]->constval.vfloat = vec_size(values) - i - 1;
3840 if (parser->tok != '}') {
3841 parseerror(parser, "internal error: breaking without `}`");
3845 if (!parser_next(parser) || parser->tok != ';') {
3846 parseerror(parser, "expected semicolon after enumeration");
3850 if (!parser_next(parser)) {
3851 parseerror(parser, "parse error after enumeration");
3863 static bool parse_block_into(parser_t *parser, ast_block *block)
3867 parser_enterblock(parser);
3869 if (!parser_next(parser)) { /* skip the '{' */
3870 parseerror(parser, "expected function body");
3874 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3876 ast_expression *expr = NULL;
3877 if (parser->tok == '}')
3880 if (!parse_statement(parser, block, &expr, false)) {
3881 /* parseerror(parser, "parse error"); */
3887 if (!ast_block_add_expr(block, expr)) {
3894 if (parser->tok != '}') {
3897 (void)parser_next(parser);
3901 if (!parser_leaveblock(parser))
3903 return retval && !!block;
3906 static ast_block* parse_block(parser_t *parser)
3909 block = ast_block_new(parser_ctx(parser));
3912 if (!parse_block_into(parser, block)) {
3913 ast_block_delete(block);
3919 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3921 if (parser->tok == '{') {
3922 *out = (ast_expression*)parse_block(parser);
3925 return parse_statement(parser, NULL, out, false);
3928 static bool create_vector_members(ast_value *var, ast_member **me)
3931 size_t len = strlen(var->name);
3933 for (i = 0; i < 3; ++i) {
3934 char *name = (char*)mem_a(len+3);
3935 memcpy(name, var->name, len);
3937 name[len+1] = 'x'+i;
3939 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3948 do { ast_member_delete(me[--i]); } while(i);
3952 static bool parse_function_body(parser_t *parser, ast_value *var)
3954 ast_block *block = NULL;
3959 ast_expression *framenum = NULL;
3960 ast_expression *nextthink = NULL;
3961 /* None of the following have to be deleted */
3962 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3963 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3964 bool has_frame_think;
3968 has_frame_think = false;
3969 old = parser->function;
3971 if (var->expression.flags & AST_FLAG_ALIAS) {
3972 parseerror(parser, "function aliases cannot have bodies");
3976 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3977 parseerror(parser, "gotos/labels leaking");
3981 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3982 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3983 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3989 if (parser->tok == '[') {
3990 /* got a frame definition: [ framenum, nextthink ]
3991 * this translates to:
3992 * self.frame = framenum;
3993 * self.nextthink = time + 0.1;
3994 * self.think = nextthink;
3998 fld_think = parser_find_field(parser, "think");
3999 fld_nextthink = parser_find_field(parser, "nextthink");
4000 fld_frame = parser_find_field(parser, "frame");
4001 if (!fld_think || !fld_nextthink || !fld_frame) {
4002 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4003 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4006 gbl_time = parser_find_global(parser, "time");
4007 gbl_self = parser_find_global(parser, "self");
4008 if (!gbl_time || !gbl_self) {
4009 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4010 parseerror(parser, "please declare the following globals: `time`, `self`");
4014 if (!parser_next(parser))
4017 framenum = parse_expression_leave(parser, true, false, false);
4019 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4022 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4023 ast_unref(framenum);
4024 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4028 if (parser->tok != ',') {
4029 ast_unref(framenum);
4030 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4031 parseerror(parser, "Got a %i\n", parser->tok);
4035 if (!parser_next(parser)) {
4036 ast_unref(framenum);
4040 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4042 /* qc allows the use of not-yet-declared functions here
4043 * - this automatically creates a prototype */
4044 ast_value *thinkfunc;
4045 ast_expression *functype = fld_think->expression.next;
4047 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4048 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4049 ast_unref(framenum);
4050 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4053 ast_type_adopt(thinkfunc, functype);
4055 if (!parser_next(parser)) {
4056 ast_unref(framenum);
4057 ast_delete(thinkfunc);
4061 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4063 nextthink = (ast_expression*)thinkfunc;
4066 nextthink = parse_expression_leave(parser, true, false, false);
4068 ast_unref(framenum);
4069 parseerror(parser, "expected a think-function in [frame,think] notation");
4074 if (!ast_istype(nextthink, ast_value)) {
4075 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4079 if (retval && parser->tok != ']') {
4080 parseerror(parser, "expected closing `]` for [frame,think] notation");
4084 if (retval && !parser_next(parser)) {
4088 if (retval && parser->tok != '{') {
4089 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4094 ast_unref(nextthink);
4095 ast_unref(framenum);
4099 has_frame_think = true;
4102 block = ast_block_new(parser_ctx(parser));
4104 parseerror(parser, "failed to allocate block");
4105 if (has_frame_think) {
4106 ast_unref(nextthink);
4107 ast_unref(framenum);
4112 if (has_frame_think) {
4114 ast_expression *self_frame;
4115 ast_expression *self_nextthink;
4116 ast_expression *self_think;
4117 ast_expression *time_plus_1;
4118 ast_store *store_frame;
4119 ast_store *store_nextthink;
4120 ast_store *store_think;
4122 ctx = parser_ctx(parser);
4123 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4124 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4125 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4127 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4128 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4130 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4131 if (self_frame) ast_delete(self_frame);
4132 if (self_nextthink) ast_delete(self_nextthink);
4133 if (self_think) ast_delete(self_think);
4134 if (time_plus_1) ast_delete(time_plus_1);
4140 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4141 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4142 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4145 ast_delete(self_frame);
4148 if (!store_nextthink) {
4149 ast_delete(self_nextthink);
4153 ast_delete(self_think);
4157 if (store_frame) ast_delete(store_frame);
4158 if (store_nextthink) ast_delete(store_nextthink);
4159 if (store_think) ast_delete(store_think);
4162 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4163 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4164 !ast_block_add_expr(block, (ast_expression*)store_think))
4171 parseerror(parser, "failed to generate code for [frame,think]");
4172 ast_unref(nextthink);
4173 ast_unref(framenum);
4179 if (var->hasvalue) {
4180 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4181 ast_block_delete(block);
4185 func = ast_function_new(ast_ctx(var), var->name, var);
4187 parseerror(parser, "failed to allocate function for `%s`", var->name);
4188 ast_block_delete(block);
4191 vec_push(parser->functions, func);
4193 parser_enterblock(parser);
4195 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4197 ast_value *param = var->expression.params[parami];
4200 if (param->expression.vtype != TYPE_VECTOR &&
4201 (param->expression.vtype != TYPE_FIELD ||
4202 param->expression.next->expression.vtype != TYPE_VECTOR))
4207 if (!create_vector_members(param, me)) {
4208 ast_block_delete(block);
4212 for (e = 0; e < 3; ++e) {
4213 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4214 ast_block_collect(block, (ast_expression*)me[e]);
4218 if (var->argcounter) {
4219 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4220 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4224 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4226 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4227 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4228 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4229 varargs->expression.count = 0;
4230 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4231 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4232 ast_delete(varargs);
4233 ast_block_delete(block);
4236 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4237 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4238 ast_delete(varargs);
4239 ast_block_delete(block);
4242 func->varargs = varargs;
4244 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4247 parser->function = func;
4248 if (!parse_block_into(parser, block)) {
4249 ast_block_delete(block);
4253 vec_push(func->blocks, block);
4255 parser->function = old;
4256 if (!parser_leaveblock(parser))
4258 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4259 parseerror(parser, "internal error: local scopes left");
4263 if (parser->tok == ';')
4264 return parser_next(parser);
4265 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4266 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4270 (void)!parser_leaveblock(parser);
4271 vec_pop(parser->functions);
4272 ast_function_delete(func);
4273 var->constval.vfunc = NULL;
4276 parser->function = old;
4280 static ast_expression *array_accessor_split(
4285 ast_expression *left,
4286 ast_expression *right
4292 lex_ctx ctx = ast_ctx(array);
4294 if (!left || !right) {
4295 if (left) ast_delete(left);
4296 if (right) ast_delete(right);
4300 cmp = ast_binary_new(ctx, INSTR_LT,
4301 (ast_expression*)index,
4302 (ast_expression*)parser_const_float(parser, middle));
4306 parseerror(parser, "internal error: failed to create comparison for array setter");
4310 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4312 ast_delete(cmp); /* will delete left and right */
4313 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4317 return (ast_expression*)ifthen;
4320 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4322 lex_ctx ctx = ast_ctx(array);
4324 if (from+1 == afterend) {
4325 /* set this value */
4328 ast_array_index *subscript;
4330 int assignop = type_store_instr[value->expression.vtype];
4332 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4333 assignop = INSTR_STORE_V;
4335 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4339 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4341 ast_delete(subscript);
4345 block = ast_block_new(ctx);
4351 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4356 ret = ast_return_new(ctx, NULL);
4362 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4367 return (ast_expression*)block;
4369 ast_expression *left, *right;
4370 size_t diff = afterend - from;
4371 size_t middle = from + diff/2;
4372 left = array_setter_node(parser, array, index, value, from, middle);
4373 right = array_setter_node(parser, array, index, value, middle, afterend);
4374 return array_accessor_split(parser, array, index, middle, left, right);
4378 static ast_expression *array_field_setter_node(
4387 lex_ctx ctx = ast_ctx(array);
4389 if (from+1 == afterend) {
4390 /* set this value */
4393 ast_entfield *entfield;
4394 ast_array_index *subscript;
4396 int assignop = type_storep_instr[value->expression.vtype];
4398 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4399 assignop = INSTR_STOREP_V;
4401 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4405 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4406 subscript->expression.vtype = TYPE_FIELD;
4408 entfield = ast_entfield_new_force(ctx,
4409 (ast_expression*)entity,
4410 (ast_expression*)subscript,
4411 (ast_expression*)subscript);
4413 ast_delete(subscript);
4417 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4419 ast_delete(entfield);
4423 block = ast_block_new(ctx);
4429 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4434 ret = ast_return_new(ctx, NULL);
4440 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4445 return (ast_expression*)block;
4447 ast_expression *left, *right;
4448 size_t diff = afterend - from;
4449 size_t middle = from + diff/2;
4450 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4451 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4452 return array_accessor_split(parser, array, index, middle, left, right);
4456 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4458 lex_ctx ctx = ast_ctx(array);
4460 if (from+1 == afterend) {
4462 ast_array_index *subscript;
4464 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4468 ret = ast_return_new(ctx, (ast_expression*)subscript);
4470 ast_delete(subscript);
4474 return (ast_expression*)ret;
4476 ast_expression *left, *right;
4477 size_t diff = afterend - from;
4478 size_t middle = from + diff/2;
4479 left = array_getter_node(parser, array, index, from, middle);
4480 right = array_getter_node(parser, array, index, middle, afterend);
4481 return array_accessor_split(parser, array, index, middle, left, right);
4485 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4487 ast_function *func = NULL;
4488 ast_value *fval = NULL;
4489 ast_block *body = NULL;
4491 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4493 parseerror(parser, "failed to create accessor function value");
4497 func = ast_function_new(ast_ctx(array), funcname, fval);
4500 parseerror(parser, "failed to create accessor function node");
4504 body = ast_block_new(ast_ctx(array));
4506 parseerror(parser, "failed to create block for array accessor");
4512 vec_push(func->blocks, body);
4515 vec_push(parser->accessors, fval);
4520 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4522 ast_value *index = NULL;
4523 ast_value *value = NULL;
4527 if (!ast_istype(array->expression.next, ast_value)) {
4528 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4532 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4534 func = fval->constval.vfunc;
4535 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4537 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4538 value = ast_value_copy((ast_value*)array->expression.next);
4540 if (!index || !value) {
4541 parseerror(parser, "failed to create locals for array accessor");
4544 (void)!ast_value_set_name(value, "value"); /* not important */
4545 vec_push(fval->expression.params, index);
4546 vec_push(fval->expression.params, value);
4548 array->setter = fval;
4551 if (index) ast_delete(index);
4552 if (value) ast_delete(value);
4558 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4560 ast_expression *root = NULL;
4561 root = array_setter_node(parser, array,
4562 array->setter->expression.params[0],
4563 array->setter->expression.params[1],
4564 0, array->expression.count);
4566 parseerror(parser, "failed to build accessor search tree");
4569 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4576 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4578 if (!parser_create_array_setter_proto(parser, array, funcname))
4580 return parser_create_array_setter_impl(parser, array);
4583 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4585 ast_expression *root = NULL;
4586 ast_value *entity = NULL;
4587 ast_value *index = NULL;
4588 ast_value *value = NULL;
4592 if (!ast_istype(array->expression.next, ast_value)) {
4593 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4597 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4599 func = fval->constval.vfunc;
4600 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4602 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4603 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4604 value = ast_value_copy((ast_value*)array->expression.next);
4605 if (!entity || !index || !value) {
4606 parseerror(parser, "failed to create locals for array accessor");
4609 (void)!ast_value_set_name(value, "value"); /* not important */
4610 vec_push(fval->expression.params, entity);
4611 vec_push(fval->expression.params, index);
4612 vec_push(fval->expression.params, value);
4614 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4616 parseerror(parser, "failed to build accessor search tree");
4620 array->setter = fval;
4621 return ast_block_add_expr(func->blocks[0], root);
4623 if (entity) ast_delete(entity);
4624 if (index) ast_delete(index);
4625 if (value) ast_delete(value);
4626 if (root) ast_delete(root);
4632 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4634 ast_value *index = NULL;
4638 /* NOTE: checking array->expression.next rather than elemtype since
4639 * for fields elemtype is a temporary fieldtype.
4641 if (!ast_istype(array->expression.next, ast_value)) {
4642 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4646 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4648 func = fval->constval.vfunc;
4649 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4651 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4654 parseerror(parser, "failed to create locals for array accessor");
4657 vec_push(fval->expression.params, index);
4659 array->getter = fval;
4662 if (index) ast_delete(index);
4668 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4670 ast_expression *root = NULL;
4672 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4674 parseerror(parser, "failed to build accessor search tree");
4677 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4684 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4686 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4688 return parser_create_array_getter_impl(parser, array);
4691 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4692 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4700 bool variadic = false;
4701 ast_value *varparam = NULL;
4702 char *argcounter = NULL;
4704 ctx = parser_ctx(parser);
4706 /* for the sake of less code we parse-in in this function */
4707 if (!parser_next(parser)) {
4708 parseerror(parser, "expected parameter list");
4714 /* parse variables until we hit a closing paren */
4715 while (parser->tok != ')') {
4717 /* there must be commas between them */
4718 if (parser->tok != ',') {
4719 parseerror(parser, "expected comma or end of parameter list");
4722 if (!parser_next(parser)) {
4723 parseerror(parser, "expected parameter");
4729 if (parser->tok == TOKEN_DOTS) {
4730 /* '...' indicates a varargs function */
4732 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4733 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4736 if (parser->tok == TOKEN_IDENT) {
4737 argcounter = util_strdup(parser_tokval(parser));
4738 if (!parser_next(parser) || parser->tok != ')') {
4739 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4746 /* for anything else just parse a typename */
4747 param = parse_typename(parser, NULL, NULL);
4750 vec_push(params, param);
4751 if (param->expression.vtype >= TYPE_VARIANT) {
4752 char tname[1024]; /* typename is reserved in C++ */
4753 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4754 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4757 /* type-restricted varargs */
4758 if (parser->tok == TOKEN_DOTS) {
4760 varparam = vec_last(params);
4762 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4763 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4766 if (parser->tok == TOKEN_IDENT) {
4767 argcounter = util_strdup(parser_tokval(parser));
4768 if (!parser_next(parser) || parser->tok != ')') {
4769 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4777 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4781 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4782 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4785 if (!parser_next(parser)) {
4786 parseerror(parser, "parse error after typename");
4790 /* now turn 'var' into a function type */
4791 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4792 fval->expression.next = (ast_expression*)var;
4794 fval->expression.flags |= AST_FLAG_VARIADIC;
4797 var->expression.params = params;
4798 var->expression.varparam = (ast_expression*)varparam;
4799 var->argcounter = argcounter;
4808 ast_delete(varparam);
4810 for (i = 0; i < vec_size(params); ++i)
4811 ast_delete(params[i]);
4816 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4818 ast_expression *cexp;
4819 ast_value *cval, *tmp;
4822 ctx = parser_ctx(parser);
4824 if (!parser_next(parser)) {
4826 parseerror(parser, "expected array-size");
4830 cexp = parse_expression_leave(parser, true, false, false);
4832 if (!cexp || !ast_istype(cexp, ast_value)) {
4836 parseerror(parser, "expected array-size as constant positive integer");
4839 cval = (ast_value*)cexp;
4841 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4842 tmp->expression.next = (ast_expression*)var;
4845 if (cval->expression.vtype == TYPE_INTEGER)
4846 tmp->expression.count = cval->constval.vint;
4847 else if (cval->expression.vtype == TYPE_FLOAT)
4848 tmp->expression.count = cval->constval.vfloat;
4852 parseerror(parser, "array-size must be a positive integer constant");
4857 if (parser->tok != ']') {
4859 parseerror(parser, "expected ']' after array-size");
4862 if (!parser_next(parser)) {
4864 parseerror(parser, "error after parsing array size");
4870 /* Parse a complete typename.
4871 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4872 * but when parsing variables separated by comma
4873 * 'storebase' should point to where the base-type should be kept.
4874 * The base type makes up every bit of type information which comes *before* the
4877 * The following will be parsed in its entirety:
4879 * The 'basetype' in this case is 'void()'
4880 * and if there's a comma after it, say:
4882 * then the type-information 'void()' can be stored in 'storebase'
4884 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4886 ast_value *var, *tmp;
4889 const char *name = NULL;
4890 bool isfield = false;
4891 bool wasarray = false;
4892 size_t morefields = 0;
4894 ctx = parser_ctx(parser);
4896 /* types may start with a dot */
4897 if (parser->tok == '.') {
4899 /* if we parsed a dot we need a typename now */
4900 if (!parser_next(parser)) {
4901 parseerror(parser, "expected typename for field definition");
4905 /* Further dots are handled seperately because they won't be part of the
4908 while (parser->tok == '.') {
4910 if (!parser_next(parser)) {
4911 parseerror(parser, "expected typename for field definition");
4916 if (parser->tok == TOKEN_IDENT)
4917 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4918 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4919 parseerror(parser, "expected typename");
4923 /* generate the basic type value */
4924 if (cached_typedef) {
4925 var = ast_value_copy(cached_typedef);
4926 ast_value_set_name(var, "<type(from_def)>");
4928 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4930 for (; morefields; --morefields) {
4931 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4932 tmp->expression.next = (ast_expression*)var;
4936 /* do not yet turn into a field - remember:
4937 * .void() foo; is a field too
4938 * .void()() foo; is a function
4942 if (!parser_next(parser)) {
4944 parseerror(parser, "parse error after typename");
4948 /* an opening paren now starts the parameter-list of a function
4949 * this is where original-QC has parameter lists.
4950 * We allow a single parameter list here.
4951 * Much like fteqcc we don't allow `float()() x`
4953 if (parser->tok == '(') {
4954 var = parse_parameter_list(parser, var);
4959 /* store the base if requested */
4961 *storebase = ast_value_copy(var);
4963 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4964 tmp->expression.next = (ast_expression*)*storebase;
4969 /* there may be a name now */
4970 if (parser->tok == TOKEN_IDENT) {
4971 name = util_strdup(parser_tokval(parser));
4973 if (!parser_next(parser)) {
4975 parseerror(parser, "error after variable or field declaration");
4980 /* now this may be an array */
4981 if (parser->tok == '[') {
4983 var = parse_arraysize(parser, var);
4988 /* This is the point where we can turn it into a field */
4990 /* turn it into a field if desired */
4991 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4992 tmp->expression.next = (ast_expression*)var;
4996 /* now there may be function parens again */
4997 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4998 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4999 if (parser->tok == '(' && wasarray)
5000 parseerror(parser, "arrays as part of a return type is not supported");
5001 while (parser->tok == '(') {
5002 var = parse_parameter_list(parser, var);
5010 /* finally name it */
5012 if (!ast_value_set_name(var, name)) {
5014 parseerror(parser, "internal error: failed to set name");
5017 /* free the name, ast_value_set_name duplicates */
5024 static bool parse_typedef(parser_t *parser)
5026 ast_value *typevar, *oldtype;
5027 ast_expression *old;
5029 typevar = parse_typename(parser, NULL, NULL);
5034 if ( (old = parser_find_var(parser, typevar->name)) ) {
5035 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5036 " -> `%s` has been declared here: %s:%i",
5037 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5038 ast_delete(typevar);
5042 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5043 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5044 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5045 ast_delete(typevar);
5049 vec_push(parser->_typedefs, typevar);
5050 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5052 if (parser->tok != ';') {
5053 parseerror(parser, "expected semicolon after typedef");
5056 if (!parser_next(parser)) {
5057 parseerror(parser, "parse error after typedef");
5064 static const char *cvq_to_str(int cvq) {
5066 case CV_NONE: return "none";
5067 case CV_VAR: return "`var`";
5068 case CV_CONST: return "`const`";
5069 default: return "<INVALID>";
5073 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5076 if (proto->cvq != var->cvq) {
5077 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5078 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5079 parser->tok == '='))
5081 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5082 "`%s` declared with different qualifiers: %s\n"
5083 " -> previous declaration here: %s:%i uses %s",
5084 var->name, cvq_to_str(var->cvq),
5085 ast_ctx(proto).file, ast_ctx(proto).line,
5086 cvq_to_str(proto->cvq));
5089 av = (var ->expression.flags & AST_FLAG_NORETURN);
5090 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5092 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5093 "`%s` declared with different attributes%s\n"
5094 " -> previous declaration here: %s:%i",
5095 var->name, (av ? ": noreturn" : ""),
5096 ast_ctx(proto).file, ast_ctx(proto).line,
5097 (ao ? ": noreturn" : ""));
5102 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)
5106 ast_expression *old;
5110 ast_value *basetype = NULL;
5112 bool isparam = false;
5113 bool isvector = false;
5114 bool cleanvar = true;
5115 bool wasarray = false;
5119 if (!localblock && is_static)
5120 parseerror(parser, "`static` qualifier is not supported in global scope");
5122 /* get the first complete variable */
5123 var = parse_typename(parser, &basetype, cached_typedef);
5126 ast_delete(basetype);
5134 /* Part 0: finish the type */
5135 if (parser->tok == '(') {
5136 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5137 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5138 var = parse_parameter_list(parser, var);
5144 /* we only allow 1-dimensional arrays */
5145 if (parser->tok == '[') {
5147 var = parse_arraysize(parser, var);
5153 if (parser->tok == '(' && wasarray) {
5154 parseerror(parser, "arrays as part of a return type is not supported");
5155 /* we'll still parse the type completely for now */
5157 /* for functions returning functions */
5158 while (parser->tok == '(') {
5159 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5160 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5161 var = parse_parameter_list(parser, var);
5168 var->cvq = qualifier;
5169 var->expression.flags |= qflags;
5172 * store the vstring back to var for alias and
5173 * deprecation messages.
5175 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5176 var->expression.flags & AST_FLAG_ALIAS)
5177 var->desc = vstring;
5180 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5181 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5182 * is then filled with the previous definition and the parameter-names replaced.
5184 if (!strcmp(var->name, "nil")) {
5185 if (OPTS_FLAG(UNTYPED_NIL)) {
5186 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5187 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5189 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5192 /* Deal with end_sys_ vars */
5194 if (!strcmp(var->name, "end_sys_globals")) {
5196 parser->crc_globals = vec_size(parser->globals);
5199 else if (!strcmp(var->name, "end_sys_fields")) {
5201 parser->crc_fields = vec_size(parser->fields);
5204 if (was_end && var->expression.vtype == TYPE_FIELD) {
5205 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5206 "global '%s' hint should not be a field",
5207 parser_tokval(parser)))
5214 if (!nofields && var->expression.vtype == TYPE_FIELD)
5216 /* deal with field declarations */
5217 old = parser_find_field(parser, var->name);
5219 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5220 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5229 parseerror(parser, "field `%s` already declared here: %s:%i",
5230 var->name, ast_ctx(old).file, ast_ctx(old).line);
5235 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5236 (old = parser_find_global(parser, var->name)))
5238 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5239 parseerror(parser, "field `%s` already declared here: %s:%i",
5240 var->name, ast_ctx(old).file, ast_ctx(old).line);
5247 /* deal with other globals */
5248 old = parser_find_global(parser, var->name);
5249 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5251 /* This is a function which had a prototype */
5252 if (!ast_istype(old, ast_value)) {
5253 parseerror(parser, "internal error: prototype is not an ast_value");
5257 proto = (ast_value*)old;
5258 proto->desc = var->desc;
5259 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5260 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5262 ast_ctx(proto).file, ast_ctx(proto).line);
5266 /* we need the new parameter-names */
5267 for (i = 0; i < vec_size(proto->expression.params); ++i)
5268 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5269 if (!parser_check_qualifiers(parser, var, proto)) {
5276 proto->expression.flags |= var->expression.flags;
5284 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5285 "global `%s` already declared here: %s:%i",
5286 var->name, ast_ctx(old).file, ast_ctx(old).line))
5291 proto = (ast_value*)old;
5292 if (!ast_istype(old, ast_value)) {
5293 parseerror(parser, "internal error: not an ast_value");
5298 if (!parser_check_qualifiers(parser, var, proto)) {
5303 proto->expression.flags |= var->expression.flags;
5307 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5308 (old = parser_find_field(parser, var->name)))
5310 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5311 parseerror(parser, "global `%s` already declared here: %s:%i",
5312 var->name, ast_ctx(old).file, ast_ctx(old).line);
5319 else /* it's not a global */
5321 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5322 if (old && !isparam) {
5323 parseerror(parser, "local `%s` already declared here: %s:%i",
5324 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5328 old = parser_find_local(parser, var->name, 0, &isparam);
5329 if (old && isparam) {
5330 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5331 "local `%s` is shadowing a parameter", var->name))
5333 parseerror(parser, "local `%s` already declared here: %s:%i",
5334 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5338 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5346 /* in a noref section we simply bump the usecount */
5347 if (noref || parser->noref)
5351 * Create the global/local, and deal with vector types.
5354 if (var->expression.vtype == TYPE_VECTOR)
5356 else if (var->expression.vtype == TYPE_FIELD &&
5357 var->expression.next->expression.vtype == TYPE_VECTOR)
5361 if (!create_vector_members(var, me)) {
5368 /* deal with global variables, fields, functions */
5369 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5370 var->isfield = true;
5371 vec_push(parser->fields, (ast_expression*)var);
5372 util_htset(parser->htfields, var->name, var);
5374 for (i = 0; i < 3; ++i) {
5375 vec_push(parser->fields, (ast_expression*)me[i]);
5376 util_htset(parser->htfields, me[i]->name, me[i]);
5381 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5382 parser_addglobal(parser, var->name, (ast_expression*)var);
5384 for (i = 0; i < 3; ++i) {
5385 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5389 ast_expression *find = parser_find_global(parser, var->desc);
5392 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5396 if (var->expression.vtype != find->expression.vtype) {
5400 ast_type_to_string(find, ty1, sizeof(ty1));
5401 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5403 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5410 * add alias to aliases table and to corrector
5411 * so corrections can apply for aliases as well.
5413 util_htset(parser->aliases, var->name, find);
5416 * add to corrector so corrections can work
5417 * even for aliases too.
5420 vec_last(parser->correct_variables),
5421 &vec_last(parser->correct_variables_score),
5425 /* generate aliases for vector components */
5429 util_asprintf(&buffer[0], "%s_x", var->desc);
5430 util_asprintf(&buffer[1], "%s_y", var->desc);
5431 util_asprintf(&buffer[2], "%s_z", var->desc);
5433 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5434 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5435 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5442 * add to corrector so corrections can work
5443 * even for aliases too.
5446 vec_last(parser->correct_variables),
5447 &vec_last(parser->correct_variables_score),
5451 vec_last(parser->correct_variables),
5452 &vec_last(parser->correct_variables_score),
5456 vec_last(parser->correct_variables),
5457 &vec_last(parser->correct_variables_score),
5465 /* a static adds itself to be generated like any other global
5466 * but is added to the local namespace instead
5468 char *defname = NULL;
5469 size_t prefix_len, ln;
5471 ln = strlen(parser->function->name);
5472 vec_append(defname, ln, parser->function->name);
5474 vec_append(defname, 2, "::");
5475 /* remember the length up to here */
5476 prefix_len = vec_size(defname);
5478 /* Add it to the local scope */
5479 util_htset(vec_last(parser->variables), var->name, (void*)var);
5483 vec_last(parser->correct_variables),
5484 &vec_last(parser->correct_variables_score),
5488 /* now rename the global */
5489 ln = strlen(var->name);
5490 vec_append(defname, ln, var->name);
5491 ast_value_set_name(var, defname);
5493 /* push it to the to-be-generated globals */
5494 vec_push(parser->globals, (ast_expression*)var);
5496 /* same game for the vector members */
5498 for (i = 0; i < 3; ++i) {
5499 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5503 vec_last(parser->correct_variables),
5504 &vec_last(parser->correct_variables_score),
5508 vec_shrinkto(defname, prefix_len);
5509 ln = strlen(me[i]->name);
5510 vec_append(defname, ln, me[i]->name);
5511 ast_member_set_name(me[i], defname);
5513 vec_push(parser->globals, (ast_expression*)me[i]);
5518 vec_push(localblock->locals, var);
5519 parser_addlocal(parser, var->name, (ast_expression*)var);
5521 for (i = 0; i < 3; ++i) {
5522 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5523 ast_block_collect(localblock, (ast_expression*)me[i]);
5529 me[0] = me[1] = me[2] = NULL;
5534 if (var->expression.vtype == TYPE_ARRAY) {
5536 snprintf(name, sizeof(name), "%s##SET", var->name);
5537 if (!parser_create_array_setter(parser, var, name))
5539 snprintf(name, sizeof(name), "%s##GET", var->name);
5540 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5543 else if (!localblock && !nofields &&
5544 var->expression.vtype == TYPE_FIELD &&
5545 var->expression.next->expression.vtype == TYPE_ARRAY)
5548 ast_expression *telem;
5550 ast_value *array = (ast_value*)var->expression.next;
5552 if (!ast_istype(var->expression.next, ast_value)) {
5553 parseerror(parser, "internal error: field element type must be an ast_value");
5557 snprintf(name, sizeof(name), "%s##SETF", var->name);
5558 if (!parser_create_array_field_setter(parser, array, name))
5561 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5562 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5563 tfield->expression.next = telem;
5564 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5565 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5573 if (parser->tok == ';') {
5574 ast_delete(basetype);
5575 if (!parser_next(parser)) {
5576 parseerror(parser, "error after variable declaration");
5582 if (parser->tok == ',')
5586 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5589 parseerror(parser, "missing comma or semicolon while parsing variables");
5593 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5594 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5595 "initializing expression turns variable `%s` into a constant in this standard",
5602 if (parser->tok != '{') {
5603 if (parser->tok != '=') {
5604 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5608 if (!parser_next(parser)) {
5609 parseerror(parser, "error parsing initializer");
5613 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5614 parseerror(parser, "expected '=' before function body in this standard");
5617 if (parser->tok == '#') {
5618 ast_function *func = NULL;
5621 parseerror(parser, "cannot declare builtins within functions");
5624 if (var->expression.vtype != TYPE_FUNCTION) {
5625 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5628 if (!parser_next(parser)) {
5629 parseerror(parser, "expected builtin number");
5632 if (parser->tok != TOKEN_INTCONST) {
5633 parseerror(parser, "builtin number must be an integer constant");
5636 if (parser_token(parser)->constval.i < 0) {
5637 parseerror(parser, "builtin number must be an integer greater than zero");
5641 if (var->hasvalue) {
5642 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5643 "builtin `%s` has already been defined\n"
5644 " -> previous declaration here: %s:%i",
5645 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5649 func = ast_function_new(ast_ctx(var), var->name, var);
5651 parseerror(parser, "failed to allocate function for `%s`", var->name);
5654 vec_push(parser->functions, func);
5656 func->builtin = -parser_token(parser)->constval.i-1;
5659 if (!parser_next(parser)) {
5660 parseerror(parser, "expected comma or semicolon");
5662 ast_function_delete(func);
5663 var->constval.vfunc = NULL;
5667 else if (parser->tok == '{' || parser->tok == '[')
5670 parseerror(parser, "cannot declare functions within functions");
5675 ast_ctx(proto) = parser_ctx(parser);
5677 if (!parse_function_body(parser, var))
5679 ast_delete(basetype);
5680 for (i = 0; i < vec_size(parser->gotos); ++i)
5681 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5682 vec_free(parser->gotos);
5683 vec_free(parser->labels);
5686 ast_expression *cexp;
5689 cexp = parse_expression_leave(parser, true, false, false);
5694 cval = (ast_value*)cexp;
5695 if (cval != parser->nil &&
5696 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5699 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5703 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5704 qualifier != CV_VAR)
5706 var->cvq = CV_CONST;
5708 if (cval == parser->nil)
5709 var->expression.flags |= AST_FLAG_INITIALIZED;
5712 var->hasvalue = true;
5713 if (cval->expression.vtype == TYPE_STRING)
5714 var->constval.vstring = parser_strdup(cval->constval.vstring);
5715 else if (cval->expression.vtype == TYPE_FIELD)
5716 var->constval.vfield = cval;
5718 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5724 shunt sy = { NULL, NULL, NULL, NULL };
5727 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5728 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5729 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5730 if (!parser_sy_apply_operator(parser, &sy))
5733 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5734 parseerror(parser, "internal error: leaked operands");
5735 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5745 if (parser->tok == ',') {
5746 if (!parser_next(parser)) {
5747 parseerror(parser, "expected another variable");
5751 if (parser->tok != TOKEN_IDENT) {
5752 parseerror(parser, "expected another variable");
5755 var = ast_value_copy(basetype);
5757 ast_value_set_name(var, parser_tokval(parser));
5758 if (!parser_next(parser)) {
5759 parseerror(parser, "error parsing variable declaration");
5765 if (parser->tok != ';') {
5766 parseerror(parser, "missing semicolon after variables");
5770 if (!parser_next(parser)) {
5771 parseerror(parser, "parse error after variable declaration");
5775 ast_delete(basetype);
5779 if (cleanvar && var)
5781 ast_delete(basetype);
5785 ast_delete(basetype);
5786 if (cleanvar && var)
5788 if (me[0]) ast_member_delete(me[0]);
5789 if (me[1]) ast_member_delete(me[1]);
5790 if (me[2]) ast_member_delete(me[2]);
5794 static bool parser_global_statement(parser_t *parser)
5798 bool is_static = false;
5799 uint32_t qflags = 0;
5800 ast_value *istype = NULL;
5801 char *vstring = NULL;
5803 if (parser->tok == TOKEN_IDENT)
5804 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5806 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5808 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5810 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5812 if (cvq == CV_WRONG)
5814 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5816 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5818 return parse_enum(parser);
5820 else if (parser->tok == TOKEN_KEYWORD)
5822 if (!strcmp(parser_tokval(parser), "typedef")) {
5823 if (!parser_next(parser)) {
5824 parseerror(parser, "expected type definition after 'typedef'");
5827 return parse_typedef(parser);
5829 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5832 else if (parser->tok == '#')
5834 return parse_pragma(parser);
5836 else if (parser->tok == '$')
5838 if (!parser_next(parser)) {
5839 parseerror(parser, "parse error");
5845 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5851 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5853 return util_crc16(old, str, strlen(str));
5856 static void progdefs_crc_file(const char *str)
5858 /* write to progdefs.h here */
5862 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5864 old = progdefs_crc_sum(old, str);
5865 progdefs_crc_file(str);
5869 static void generate_checksum(parser_t *parser)
5871 uint16_t crc = 0xFFFF;
5875 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5876 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5878 progdefs_crc_file("\tint\tpad;\n");
5879 progdefs_crc_file("\tint\tofs_return[3];\n");
5880 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5881 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5882 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5883 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5884 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5885 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5886 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5887 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5889 for (i = 0; i < parser->crc_globals; ++i) {
5890 if (!ast_istype(parser->globals[i], ast_value))
5892 value = (ast_value*)(parser->globals[i]);
5893 switch (value->expression.vtype) {
5894 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5895 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5896 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5897 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5899 crc = progdefs_crc_both(crc, "\tint\t");
5902 crc = progdefs_crc_both(crc, value->name);
5903 crc = progdefs_crc_both(crc, ";\n");
5905 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5906 for (i = 0; i < parser->crc_fields; ++i) {
5907 if (!ast_istype(parser->fields[i], ast_value))
5909 value = (ast_value*)(parser->fields[i]);
5910 switch (value->expression.next->expression.vtype) {
5911 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5912 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5913 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5914 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5916 crc = progdefs_crc_both(crc, "\tint\t");
5919 crc = progdefs_crc_both(crc, value->name);
5920 crc = progdefs_crc_both(crc, ";\n");
5922 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5927 parser_t *parser_create()
5933 parser = (parser_t*)mem_a(sizeof(parser_t));
5937 memset(parser, 0, sizeof(*parser));
5939 for (i = 0; i < operator_count; ++i) {
5940 if (operators[i].id == opid1('=')) {
5941 parser->assign_op = operators+i;
5945 if (!parser->assign_op) {
5946 printf("internal error: initializing parser: failed to find assign operator\n");
5951 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5952 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5953 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5954 vec_push(parser->_blocktypedefs, 0);
5956 parser->aliases = util_htnew(PARSER_HT_SIZE);
5958 parser->ht_imm_string = util_htnew(512);
5961 vec_push(parser->correct_variables, correct_trie_new());
5962 vec_push(parser->correct_variables_score, NULL);
5964 empty_ctx.file = "<internal>";
5966 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5967 parser->nil->cvq = CV_CONST;
5968 if (OPTS_FLAG(UNTYPED_NIL))
5969 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5971 parser->max_param_count = 1;
5973 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5974 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5975 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5977 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5978 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5979 parser->reserved_version->cvq = CV_CONST;
5980 parser->reserved_version->hasvalue = true;
5981 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5982 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5984 parser->reserved_version = NULL;
5990 bool parser_compile(parser_t *parser)
5992 /* initial lexer/parser state */
5993 parser->lex->flags.noops = true;
5995 if (parser_next(parser))
5997 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5999 if (!parser_global_statement(parser)) {
6000 if (parser->tok == TOKEN_EOF)
6001 parseerror(parser, "unexpected eof");
6002 else if (compile_errors)
6003 parseerror(parser, "there have been errors, bailing out");
6004 lex_close(parser->lex);
6010 parseerror(parser, "parse error");
6011 lex_close(parser->lex);
6016 lex_close(parser->lex);
6019 return !compile_errors;
6022 bool parser_compile_file(parser_t *parser, const char *filename)
6024 parser->lex = lex_open(filename);
6026 con_err("failed to open file \"%s\"\n", filename);
6029 return parser_compile(parser);
6032 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6034 parser->lex = lex_open_string(str, len, name);
6036 con_err("failed to create lexer for string \"%s\"\n", name);
6039 return parser_compile(parser);
6042 void parser_cleanup(parser_t *parser)
6045 for (i = 0; i < vec_size(parser->accessors); ++i) {
6046 ast_delete(parser->accessors[i]->constval.vfunc);
6047 parser->accessors[i]->constval.vfunc = NULL;
6048 ast_delete(parser->accessors[i]);
6050 for (i = 0; i < vec_size(parser->functions); ++i) {
6051 ast_delete(parser->functions[i]);
6053 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6054 ast_delete(parser->imm_vector[i]);
6056 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6057 ast_delete(parser->imm_string[i]);
6059 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6060 ast_delete(parser->imm_float[i]);
6062 for (i = 0; i < vec_size(parser->fields); ++i) {
6063 ast_delete(parser->fields[i]);
6065 for (i = 0; i < vec_size(parser->globals); ++i) {
6066 ast_delete(parser->globals[i]);
6068 vec_free(parser->accessors);
6069 vec_free(parser->functions);
6070 vec_free(parser->imm_vector);
6071 vec_free(parser->imm_string);
6072 util_htdel(parser->ht_imm_string);
6073 vec_free(parser->imm_float);
6074 vec_free(parser->globals);
6075 vec_free(parser->fields);
6077 for (i = 0; i < vec_size(parser->variables); ++i)
6078 util_htdel(parser->variables[i]);
6079 vec_free(parser->variables);
6080 vec_free(parser->_blocklocals);
6081 vec_free(parser->_locals);
6084 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6085 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6087 vec_free(parser->correct_variables);
6088 vec_free(parser->correct_variables_score);
6091 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6092 ast_delete(parser->_typedefs[i]);
6093 vec_free(parser->_typedefs);
6094 for (i = 0; i < vec_size(parser->typedefs); ++i)
6095 util_htdel(parser->typedefs[i]);
6096 vec_free(parser->typedefs);
6097 vec_free(parser->_blocktypedefs);
6099 vec_free(parser->_block_ctx);
6101 vec_free(parser->labels);
6102 vec_free(parser->gotos);
6103 vec_free(parser->breaks);
6104 vec_free(parser->continues);
6106 ast_value_delete(parser->nil);
6108 ast_value_delete(parser->const_vec[0]);
6109 ast_value_delete(parser->const_vec[1]);
6110 ast_value_delete(parser->const_vec[2]);
6112 util_htdel(parser->aliases);
6114 intrin_intrinsics_destroy(parser);
6119 bool parser_finish(parser_t *parser, const char *output)
6125 if (compile_errors) {
6126 con_out("*** there were compile errors\n");
6130 ir = ir_builder_new("gmqcc_out");
6132 con_out("failed to allocate builder\n");
6136 for (i = 0; i < vec_size(parser->fields); ++i) {
6139 if (!ast_istype(parser->fields[i], ast_value))
6141 field = (ast_value*)parser->fields[i];
6142 hasvalue = field->hasvalue;
6143 field->hasvalue = false;
6144 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6145 con_out("failed to generate field %s\n", field->name);
6146 ir_builder_delete(ir);
6151 ast_expression *subtype;
6152 field->hasvalue = true;
6153 subtype = field->expression.next;
6154 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6155 if (subtype->expression.vtype == TYPE_FIELD)
6156 ifld->fieldtype = subtype->expression.next->expression.vtype;
6157 else if (subtype->expression.vtype == TYPE_FUNCTION)
6158 ifld->outtype = subtype->expression.next->expression.vtype;
6159 (void)!ir_value_set_field(field->ir_v, ifld);
6162 for (i = 0; i < vec_size(parser->globals); ++i) {
6164 if (!ast_istype(parser->globals[i], ast_value))
6166 asvalue = (ast_value*)(parser->globals[i]);
6167 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6168 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6169 "unused global: `%s`", asvalue->name);
6171 if (!ast_global_codegen(asvalue, ir, false)) {
6172 con_out("failed to generate global %s\n", asvalue->name);
6173 ir_builder_delete(ir);
6177 /* Build function vararg accessor ast tree now before generating
6178 * immediates, because the accessors may add new immediates
6180 for (i = 0; i < vec_size(parser->functions); ++i) {
6181 ast_function *f = parser->functions[i];
6183 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6184 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6185 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6186 con_out("failed to generate vararg setter for %s\n", f->name);
6187 ir_builder_delete(ir);
6190 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6191 con_out("failed to generate vararg getter for %s\n", f->name);
6192 ir_builder_delete(ir);
6196 ast_delete(f->varargs);
6201 /* Now we can generate immediates */
6202 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6203 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6204 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6205 ir_builder_delete(ir);
6209 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6210 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6211 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6212 ir_builder_delete(ir);
6216 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6217 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6218 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6219 ir_builder_delete(ir);
6223 for (i = 0; i < vec_size(parser->globals); ++i) {
6225 if (!ast_istype(parser->globals[i], ast_value))
6227 asvalue = (ast_value*)(parser->globals[i]);
6228 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6230 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6231 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6232 "uninitialized constant: `%s`",
6234 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6235 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6236 "uninitialized global: `%s`",
6239 if (!ast_generate_accessors(asvalue, ir)) {
6240 ir_builder_delete(ir);
6244 for (i = 0; i < vec_size(parser->fields); ++i) {
6246 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6248 if (!ast_istype((ast_expression*)asvalue, ast_value))
6250 if (asvalue->expression.vtype != TYPE_ARRAY)
6252 if (!ast_generate_accessors(asvalue, ir)) {
6253 ir_builder_delete(ir);
6257 if (parser->reserved_version &&
6258 !ast_global_codegen(parser->reserved_version, ir, false))
6260 con_out("failed to generate reserved::version");
6261 ir_builder_delete(ir);
6264 for (i = 0; i < vec_size(parser->functions); ++i) {
6265 ast_function *f = parser->functions[i];
6266 if (!ast_function_codegen(f, ir)) {
6267 con_out("failed to generate function %s\n", f->name);
6268 ir_builder_delete(ir);
6272 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6273 ir_builder_dump(ir, con_out);
6274 for (i = 0; i < vec_size(parser->functions); ++i) {
6275 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6276 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6277 ir_builder_delete(ir);
6282 if (compile_Werrors) {
6283 con_out("*** there were warnings treated as errors\n");
6284 compile_show_werrors();
6289 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6290 ir_builder_dump(ir, con_out);
6292 generate_checksum(parser);
6294 if (!ir_builder_generate(ir, output)) {
6295 con_out("*** failed to generate output file\n");
6296 ir_builder_delete(ir);
6301 ir_builder_delete(ir);