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
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;
50 /* must be deleted first, they reference immediates and values */
51 ast_value **accessors;
53 ast_value *imm_float_zero;
54 ast_value *imm_float_one;
55 ast_value *imm_float_neg_one;
57 ast_value *imm_vector_zero;
60 ast_value *reserved_version;
65 ast_function *function;
68 /* All the labels the function defined...
69 * Should they be in ast_function instead?
74 const char **continues;
76 /* A list of hashtables for each scope */
82 /* same as above but for the spelling corrector */
83 correct_trie_t **correct_variables;
84 size_t ***correct_variables_score; /* vector of vector of size_t* */
86 /* not to be used directly, we use the hash table */
87 ast_expression **_locals;
89 ast_value **_typedefs;
90 size_t *_blocktypedefs;
93 /* we store the '=' operator info */
94 const oper_info *assign_op;
97 ast_value *const_vec[3];
102 /* collected information */
103 size_t max_param_count;
106 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
108 static void parser_enterblock(parser_t *parser);
109 static bool parser_leaveblock(parser_t *parser);
110 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
111 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
112 static bool parse_typedef(parser_t *parser);
113 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);
114 static ast_block* parse_block(parser_t *parser);
115 static bool parse_block_into(parser_t *parser, ast_block *block);
116 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
117 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
118 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
119 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
120 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
121 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
122 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
124 static void parseerror(parser_t *parser, const char *fmt, ...)
128 vcompile_error(parser->lex->tok.ctx, fmt, ap);
132 /* returns true if it counts as an error */
133 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
138 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
143 /**********************************************************************
144 * some maths used for constant folding
147 vector vec3_add(vector a, vector b)
156 vector vec3_sub(vector a, vector b)
165 qcfloat vec3_mulvv(vector a, vector b)
167 return (a.x * b.x + a.y * b.y + a.z * b.z);
170 vector vec3_mulvf(vector a, float b)
179 /**********************************************************************
183 bool parser_next(parser_t *parser)
185 /* lex_do kills the previous token */
186 parser->tok = lex_do(parser->lex);
187 if (parser->tok == TOKEN_EOF)
189 if (parser->tok >= TOKEN_ERROR) {
190 parseerror(parser, "lex error");
196 #define parser_tokval(p) ((p)->lex->tok.value)
197 #define parser_token(p) (&((p)->lex->tok))
198 #define parser_ctx(p) ((p)->lex->tok.ctx)
200 static ast_value* parser_const_float(parser_t *parser, double d)
205 for (i = 0; i < vec_size(parser->imm_float); ++i) {
206 const double compare = parser->imm_float[i]->constval.vfloat;
207 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
208 return parser->imm_float[i];
211 ctx = parser_ctx(parser);
213 memset(&ctx, 0, sizeof(ctx));
215 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
217 out->hasvalue = true;
218 out->constval.vfloat = d;
219 vec_push(parser->imm_float, out);
223 static ast_value* parser_const_float_0(parser_t *parser)
225 if (!parser->imm_float_zero)
226 parser->imm_float_zero = parser_const_float(parser, 0);
227 return parser->imm_float_zero;
230 static ast_value* parser_const_float_neg1(parser_t *parser) {
231 if (!parser->imm_float_neg_one)
232 parser->imm_float_neg_one = parser_const_float(parser, -1);
233 return parser->imm_float_neg_one;
236 static ast_value* parser_const_float_1(parser_t *parser)
238 if (!parser->imm_float_one)
239 parser->imm_float_one = parser_const_float(parser, 1);
240 return parser->imm_float_one;
243 static char *parser_strdup(const char *str)
246 /* actually dup empty strings */
247 char *out = (char*)mem_a(1);
251 return util_strdup(str);
254 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
258 for (i = 0; i < vec_size(parser->imm_string); ++i) {
259 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
260 return parser->imm_string[i];
264 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
265 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
267 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
269 out->hasvalue = true;
270 out->constval.vstring = parser_strdup(str);
271 vec_push(parser->imm_string, out);
275 static ast_value* parser_const_vector(parser_t *parser, vector v)
279 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
280 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
281 return parser->imm_vector[i];
283 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
285 out->hasvalue = true;
286 out->constval.vvec = v;
287 vec_push(parser->imm_vector, out);
291 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
297 return parser_const_vector(parser, v);
300 static ast_value* parser_const_vector_0(parser_t *parser)
302 if (!parser->imm_vector_zero)
303 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
304 return parser->imm_vector_zero;
307 static ast_expression* parser_find_field(parser_t *parser, const char *name)
309 return ( ast_expression*)util_htget(parser->htfields, name);
312 static ast_expression* parser_find_label(parser_t *parser, const char *name)
315 for(i = 0; i < vec_size(parser->labels); i++)
316 if (!strcmp(parser->labels[i]->name, name))
317 return (ast_expression*)parser->labels[i];
321 static ast_expression* parser_find_global(parser_t *parser, const char *name)
323 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
326 return (ast_expression*)util_htget(parser->htglobals, name);
329 static ast_expression* parser_find_param(parser_t *parser, const char *name)
333 if (!parser->function)
335 fun = parser->function->vtype;
336 for (i = 0; i < vec_size(fun->expression.params); ++i) {
337 if (!strcmp(fun->expression.params[i]->name, name))
338 return (ast_expression*)(fun->expression.params[i]);
343 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
348 hash = util_hthash(parser->htglobals, name);
351 for (i = vec_size(parser->variables); i > upto;) {
353 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
357 return parser_find_param(parser, name);
360 static ast_expression* parser_find_var(parser_t *parser, const char *name)
364 v = parser_find_local(parser, name, 0, &dummy);
365 if (!v) v = parser_find_global(parser, name);
369 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
373 hash = util_hthash(parser->typedefs[0], name);
375 for (i = vec_size(parser->typedefs); i > upto;) {
377 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
383 /* include intrinsics */
388 size_t etype; /* 0 = expression, others are operators */
392 ast_block *block; /* for commas and function calls */
411 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
422 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
426 e.out = (ast_expression*)v;
433 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
435 e.etype = 1 + (op - operators);
444 static sy_elem syparen(lex_ctx ctx, size_t off) {
455 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
456 * so we need to rotate it to become ent.(foo[n]).
458 static bool rotate_entfield_array_index_nodes(ast_expression **out)
460 ast_array_index *index, *oldindex;
461 ast_entfield *entfield;
465 ast_expression *entity;
467 lex_ctx ctx = ast_ctx(*out);
469 if (!ast_istype(*out, ast_array_index))
471 index = (ast_array_index*)*out;
473 if (!ast_istype(index->array, ast_entfield))
475 entfield = (ast_entfield*)index->array;
477 if (!ast_istype(entfield->field, ast_value))
479 field = (ast_value*)entfield->field;
482 entity = entfield->entity;
486 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
487 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
488 *out = (ast_expression*)entfield;
490 oldindex->array = NULL;
491 oldindex->index = NULL;
492 ast_delete(oldindex);
497 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
499 switch (v->expression.vtype) {
501 return !!v->constval.vfloat;
503 return !!v->constval.vint;
505 if (OPTS_FLAG(CORRECT_LOGIC))
506 return v->constval.vvec.x &&
507 v->constval.vvec.y &&
510 return !!(v->constval.vvec.x);
512 if (!v->constval.vstring)
514 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
516 return !!v->constval.vstring[0];
518 compile_error(ctx, "internal error: immediate_is_true on invalid type");
519 return !!v->constval.vfunc;
523 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
527 ast_expression *out = NULL;
528 ast_expression *exprs[3];
529 ast_block *blocks[3];
530 ast_value *asvalue[3];
531 ast_binstore *asbinstore;
532 size_t i, assignop, addop, subop;
533 qcint generated_op = 0;
538 if (!vec_size(sy->ops)) {
539 parseerror(parser, "internal error: missing operator");
543 if (vec_last(sy->ops).isparen) {
544 parseerror(parser, "unmatched parenthesis");
548 op = &operators[vec_last(sy->ops).etype - 1];
549 ctx = vec_last(sy->ops).ctx;
551 if (vec_size(sy->out) < op->operands) {
552 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
553 op->op, (int)op->id);
557 vec_shrinkby(sy->ops, 1);
559 /* op(:?) has no input and no output */
563 vec_shrinkby(sy->out, op->operands);
564 for (i = 0; i < op->operands; ++i) {
565 exprs[i] = sy->out[vec_size(sy->out)+i].out;
566 blocks[i] = sy->out[vec_size(sy->out)+i].block;
567 asvalue[i] = (ast_value*)exprs[i];
569 if (exprs[i]->expression.vtype == TYPE_NOEXPR &&
570 !(i != 0 && op->id == opid2('?',':')) &&
571 !(i == 1 && op->id == opid1('.')))
573 if (ast_istype(exprs[i], ast_label))
574 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
576 compile_error(ast_ctx(exprs[i]), "not an expression");
577 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
581 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
582 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
586 #define NotSameType(T) \
587 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
588 exprs[0]->expression.vtype != T)
589 #define CanConstFold1(A) \
590 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
591 (A)->expression.vtype != TYPE_FUNCTION)
592 #define CanConstFold(A, B) \
593 (CanConstFold1(A) && CanConstFold1(B))
594 #define ConstV(i) (asvalue[(i)]->constval.vvec)
595 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
596 #define ConstS(i) (asvalue[(i)]->constval.vstring)
600 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
604 if (exprs[0]->expression.vtype == TYPE_VECTOR &&
605 exprs[1]->expression.vtype == TYPE_NOEXPR)
607 if (exprs[1] == (ast_expression*)parser->const_vec[0])
608 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
609 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
610 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
611 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
612 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
614 compile_error(ctx, "access to invalid vector component");
618 else if (exprs[0]->expression.vtype == TYPE_ENTITY) {
619 if (exprs[1]->expression.vtype != TYPE_FIELD) {
620 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
623 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
625 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
626 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
630 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
636 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
637 !(exprs[0]->expression.vtype == TYPE_FIELD &&
638 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
640 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
641 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
644 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
645 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
646 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
649 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
650 if (rotate_entfield_array_index_nodes(&out))
653 /* This is not broken in fteqcc anymore */
654 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
655 /* this error doesn't need to make us bail out */
656 (void)!parsewarning(parser, WARN_EXTENSIONS,
657 "accessing array-field members of an entity without parenthesis\n"
658 " -> this is an extension from -std=gmqcc");
665 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
666 vec_push(sy->out, syexp(ctx, exprs[0]));
667 vec_push(sy->out, syexp(ctx, exprs[1]));
668 vec_last(sy->argc)++;
672 if (!ast_block_add_expr(blocks[0], exprs[1]))
675 blocks[0] = ast_block_new(ctx);
676 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
677 !ast_block_add_expr(blocks[0], exprs[1]))
682 ast_block_set_type(blocks[0], exprs[1]);
684 vec_push(sy->out, syblock(ctx, blocks[0]));
691 switch (exprs[0]->expression.vtype) {
693 if (CanConstFold1(exprs[0]))
694 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
696 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
697 (ast_expression*)parser_const_float_0(parser),
701 if (CanConstFold1(exprs[0]))
702 out = (ast_expression*)parser_const_vector_f(parser,
703 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
705 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
706 (ast_expression*)parser_const_vector_0(parser),
710 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
711 type_name[exprs[0]->expression.vtype]);
717 switch (exprs[0]->expression.vtype) {
719 if (CanConstFold1(exprs[0]))
720 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
722 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
725 if (CanConstFold1(exprs[0]))
726 out = (ast_expression*)parser_const_float(parser,
727 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
729 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
732 if (CanConstFold1(exprs[0])) {
733 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
734 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
736 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
738 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
739 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
741 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
744 /* we don't constant-fold NOT for these types */
746 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
749 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
752 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
753 type_name[exprs[0]->expression.vtype]);
759 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
760 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
762 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
763 type_name[exprs[0]->expression.vtype],
764 type_name[exprs[1]->expression.vtype]);
767 switch (exprs[0]->expression.vtype) {
769 if (CanConstFold(exprs[0], exprs[1]))
771 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
774 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
777 if (CanConstFold(exprs[0], exprs[1]))
778 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
780 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
783 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
784 type_name[exprs[0]->expression.vtype],
785 type_name[exprs[1]->expression.vtype]);
790 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
791 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
793 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
794 type_name[exprs[1]->expression.vtype],
795 type_name[exprs[0]->expression.vtype]);
798 switch (exprs[0]->expression.vtype) {
800 if (CanConstFold(exprs[0], exprs[1]))
801 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
803 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
806 if (CanConstFold(exprs[0], exprs[1]))
807 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
809 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
812 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
813 type_name[exprs[1]->expression.vtype],
814 type_name[exprs[0]->expression.vtype]);
819 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
820 !(exprs[0]->expression.vtype == TYPE_VECTOR &&
821 exprs[1]->expression.vtype == TYPE_FLOAT) &&
822 !(exprs[1]->expression.vtype == TYPE_VECTOR &&
823 exprs[0]->expression.vtype == TYPE_FLOAT)
826 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
827 type_name[exprs[1]->expression.vtype],
828 type_name[exprs[0]->expression.vtype]);
831 switch (exprs[0]->expression.vtype) {
833 if (exprs[1]->expression.vtype == TYPE_VECTOR)
835 if (CanConstFold(exprs[0], exprs[1]))
836 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
838 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
842 if (CanConstFold(exprs[0], exprs[1]))
843 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
845 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
849 if (exprs[1]->expression.vtype == TYPE_FLOAT)
851 if (CanConstFold(exprs[0], exprs[1]))
852 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
854 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
858 if (CanConstFold(exprs[0], exprs[1]))
859 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
860 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
861 vector vec = ConstV(0);
862 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
863 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
864 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
865 out->expression.node.keep = false;
866 ((ast_member*)out)->rvalue = true;
868 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
870 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
871 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
872 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
873 out->expression.node.keep = false;
874 ((ast_member*)out)->rvalue = true;
876 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
878 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
879 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
880 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
881 out->expression.node.keep = false;
882 ((ast_member*)out)->rvalue = true;
884 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
887 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
889 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
890 vector vec = ConstV(1);
891 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
892 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
893 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
894 out->expression.node.keep = false;
895 ((ast_member*)out)->rvalue = true;
897 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
899 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
900 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
901 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
902 out->expression.node.keep = false;
903 ((ast_member*)out)->rvalue = true;
905 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
907 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
908 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
909 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
910 out->expression.node.keep = false;
911 ((ast_member*)out)->rvalue = true;
913 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
916 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
919 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
923 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
924 type_name[exprs[1]->expression.vtype],
925 type_name[exprs[0]->expression.vtype]);
930 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
931 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
932 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
933 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
936 if (exprs[0]->expression.vtype == TYPE_FLOAT) {
937 if (CanConstFold(exprs[0], exprs[1]))
938 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
940 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
942 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
943 if (CanConstFold(exprs[0], exprs[1]))
944 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
946 if (CanConstFold1(exprs[1])) {
947 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
949 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
950 (ast_expression*)parser_const_float_1(parser),
954 compile_error(ctx, "internal error: failed to generate division");
957 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
962 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
963 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
964 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
970 if (NotSameType(TYPE_FLOAT)) {
971 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
972 type_name[exprs[0]->expression.vtype],
973 type_name[exprs[1]->expression.vtype]);
976 if (CanConstFold(exprs[0], exprs[1])) {
977 out = (ast_expression*)parser_const_float(parser,
978 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
980 /* generate a call to __builtin_mod */
981 ast_expression *mod = intrin_func(parser, "mod");
982 ast_call *call = NULL;
983 if (!mod) return false; /* can return null for missing floor */
985 call = ast_call_new(parser_ctx(parser), mod);
986 vec_push(call->params, exprs[0]);
987 vec_push(call->params, exprs[1]);
989 out = (ast_expression*)call;
994 compile_error(ctx, "%= is unimplemented");
999 if (NotSameType(TYPE_FLOAT)) {
1000 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1001 type_name[exprs[0]->expression.vtype],
1002 type_name[exprs[1]->expression.vtype]);
1005 if (CanConstFold(exprs[0], exprs[1]))
1006 out = (ast_expression*)parser_const_float(parser,
1007 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1008 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1010 out = (ast_expression*)ast_binary_new(ctx,
1011 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1012 exprs[0], exprs[1]);
1015 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-xor via ^");
1018 case opid2('<','<'):
1019 case opid2('>','>'):
1020 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1021 if (op->id == opid2('<','<'))
1022 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) << (int)(ConstF(1))));
1024 out = (ast_expression*)parser_const_float(parser, (double)((int)(ConstF(0)) >> (int)(ConstF(1))));
1027 case opid3('<','<','='):
1028 case opid3('>','>','='):
1029 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1032 case opid2('|','|'):
1033 generated_op += 1; /* INSTR_OR */
1034 case opid2('&','&'):
1035 generated_op += INSTR_AND;
1036 if (CanConstFold(exprs[0], exprs[1]))
1038 if (OPTS_FLAG(PERL_LOGIC)) {
1039 if (immediate_is_true(ctx, asvalue[0]))
1043 out = (ast_expression*)parser_const_float(parser,
1044 ( (generated_op == INSTR_OR)
1045 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1046 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1051 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1052 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1053 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1054 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1057 for (i = 0; i < 2; ++i) {
1058 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
1059 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1061 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1063 exprs[i] = out; out = NULL;
1064 if (OPTS_FLAG(PERL_LOGIC)) {
1065 /* here we want to keep the right expressions' type */
1069 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
1070 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1072 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1074 exprs[i] = out; out = NULL;
1075 if (OPTS_FLAG(PERL_LOGIC)) {
1076 /* here we want to keep the right expressions' type */
1081 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1085 case opid2('?',':'):
1086 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1087 compile_error(ctx, "mismatched parenthesis/ternary");
1091 if (!ast_compare_type(exprs[1], exprs[2])) {
1092 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1093 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1094 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1097 if (CanConstFold1(exprs[0]))
1098 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1100 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1103 case opid2('*', '*'):
1104 if (NotSameType(TYPE_FLOAT)) {
1105 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1106 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1107 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1113 if (CanConstFold(exprs[0], exprs[1])) {
1114 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1116 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1117 vec_push(gencall->params, exprs[0]);
1118 vec_push(gencall->params, exprs[1]);
1119 out = (ast_expression*)gencall;
1123 case opid3('<','=','>'): /* -1, 0, or 1 */
1124 if (NotSameType(TYPE_FLOAT)) {
1125 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1126 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1127 compile_error(ctx, "invalid types used in comparision: %s and %s",
1133 if (CanConstFold(exprs[0], exprs[1])) {
1134 if (ConstF(0) < ConstF(1))
1135 out = (ast_expression*)parser_const_float_neg1(parser);
1136 else if (ConstF(0) == ConstF(1))
1137 out = (ast_expression*)parser_const_float_0(parser);
1138 else if (ConstF(0) > ConstF(1))
1139 out = (ast_expression*)parser_const_float_1(parser);
1141 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1143 eq->refs = (ast_binary_ref)false; /* references nothing */
1146 out = (ast_expression*)ast_ternary_new(ctx,
1147 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1149 (ast_expression*)parser_const_float_neg1(parser),
1152 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1154 (ast_expression*)parser_const_float_0(parser),
1157 (ast_expression*)parser_const_float_1(parser)
1167 generated_op += 1; /* INSTR_GT */
1169 generated_op += 1; /* INSTR_LT */
1170 case opid2('>', '='):
1171 generated_op += 1; /* INSTR_GE */
1172 case opid2('<', '='):
1173 generated_op += INSTR_LE;
1174 if (NotSameType(TYPE_FLOAT)) {
1175 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1176 type_name[exprs[0]->expression.vtype],
1177 type_name[exprs[1]->expression.vtype]);
1180 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1182 case opid2('!', '='):
1183 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1184 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1185 type_name[exprs[0]->expression.vtype],
1186 type_name[exprs[1]->expression.vtype]);
1189 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1191 case opid2('=', '='):
1192 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
1193 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1194 type_name[exprs[0]->expression.vtype],
1195 type_name[exprs[1]->expression.vtype]);
1198 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
1202 if (ast_istype(exprs[0], ast_entfield)) {
1203 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1204 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1205 exprs[0]->expression.vtype == TYPE_FIELD &&
1206 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1208 assignop = type_storep_instr[TYPE_VECTOR];
1211 assignop = type_storep_instr[exprs[0]->expression.vtype];
1212 if (assignop == VINSTR_END || !ast_compare_type(field->expression.next, exprs[1]))
1214 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
1215 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1216 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1217 field->expression.next->expression.vtype == TYPE_FUNCTION &&
1218 exprs[1]->expression.vtype == TYPE_FUNCTION)
1220 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1221 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1224 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1229 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1230 exprs[0]->expression.vtype == TYPE_FIELD &&
1231 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1233 assignop = type_store_instr[TYPE_VECTOR];
1236 assignop = type_store_instr[exprs[0]->expression.vtype];
1239 if (assignop == VINSTR_END) {
1240 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1241 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1242 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1244 else if (!ast_compare_type(exprs[0], exprs[1]))
1246 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1247 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1248 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1249 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1250 exprs[1]->expression.vtype == TYPE_FUNCTION)
1252 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1253 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1256 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1259 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1260 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1262 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1264 case opid3('+','+','P'):
1265 case opid3('-','-','P'):
1267 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1268 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1269 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1272 if (op->id == opid3('+','+','P'))
1273 addop = INSTR_ADD_F;
1275 addop = INSTR_SUB_F;
1276 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1277 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1279 if (ast_istype(exprs[0], ast_entfield)) {
1280 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1282 (ast_expression*)parser_const_float_1(parser));
1284 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1286 (ast_expression*)parser_const_float_1(parser));
1289 case opid3('S','+','+'):
1290 case opid3('S','-','-'):
1292 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1293 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1294 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1297 if (op->id == opid3('S','+','+')) {
1298 addop = INSTR_ADD_F;
1299 subop = INSTR_SUB_F;
1301 addop = INSTR_SUB_F;
1302 subop = INSTR_ADD_F;
1304 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1305 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1307 if (ast_istype(exprs[0], ast_entfield)) {
1308 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1310 (ast_expression*)parser_const_float_1(parser));
1312 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1314 (ast_expression*)parser_const_float_1(parser));
1318 out = (ast_expression*)ast_binary_new(ctx, subop,
1320 (ast_expression*)parser_const_float_1(parser));
1322 case opid2('+','='):
1323 case opid2('-','='):
1324 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1325 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1327 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1328 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1329 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1333 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1334 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1336 if (ast_istype(exprs[0], ast_entfield))
1337 assignop = type_storep_instr[exprs[0]->expression.vtype];
1339 assignop = type_store_instr[exprs[0]->expression.vtype];
1340 switch (exprs[0]->expression.vtype) {
1342 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1343 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1344 exprs[0], exprs[1]);
1347 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1348 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1349 exprs[0], exprs[1]);
1352 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1353 type_name[exprs[0]->expression.vtype],
1354 type_name[exprs[1]->expression.vtype]);
1358 case opid2('*','='):
1359 case opid2('/','='):
1360 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1361 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1362 exprs[0]->expression.vtype == TYPE_VECTOR))
1364 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1365 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1366 compile_error(ctx, "invalid types used in expression: %s and %s",
1370 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1371 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1373 if (ast_istype(exprs[0], ast_entfield))
1374 assignop = type_storep_instr[exprs[0]->expression.vtype];
1376 assignop = type_store_instr[exprs[0]->expression.vtype];
1377 switch (exprs[0]->expression.vtype) {
1379 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1380 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1381 exprs[0], exprs[1]);
1384 if (op->id == opid2('*','=')) {
1385 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1386 exprs[0], exprs[1]);
1388 /* there's no DIV_VF */
1389 if (CanConstFold1(exprs[1])) {
1390 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1392 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1393 (ast_expression*)parser_const_float_1(parser),
1397 compile_error(ctx, "internal error: failed to generate division");
1400 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1405 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1406 type_name[exprs[0]->expression.vtype],
1407 type_name[exprs[1]->expression.vtype]);
1411 case opid2('&','='):
1412 case opid2('|','='):
1413 if (NotSameType(TYPE_FLOAT)) {
1414 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1415 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1416 compile_error(ctx, "invalid types used in expression: %s and %s",
1420 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1421 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1423 if (ast_istype(exprs[0], ast_entfield))
1424 assignop = type_storep_instr[exprs[0]->expression.vtype];
1426 assignop = type_store_instr[exprs[0]->expression.vtype];
1427 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1428 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1429 exprs[0], exprs[1]);
1431 case opid3('&','~','='):
1432 /* This is like: a &= ~(b);
1433 * But QC has no bitwise-not, so we implement it as
1436 if (NotSameType(TYPE_FLOAT)) {
1437 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1438 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1439 compile_error(ctx, "invalid types used in expression: %s and %s",
1443 if (ast_istype(exprs[0], ast_entfield))
1444 assignop = type_storep_instr[exprs[0]->expression.vtype];
1446 assignop = type_store_instr[exprs[0]->expression.vtype];
1447 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1450 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1451 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1453 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1454 asbinstore->keep_dest = true;
1455 out = (ast_expression*)asbinstore;
1458 case opid2('~', 'P'):
1459 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1460 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1461 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1465 if(CanConstFold1(exprs[0]))
1466 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1468 out = (ast_expression*)
1469 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1475 compile_error(ctx, "failed to apply operator %s", op->op);
1479 vec_push(sy->out, syexp(ctx, out));
1483 static bool parser_close_call(parser_t *parser, shunt *sy)
1485 /* was a function call */
1486 ast_expression *fun;
1487 ast_value *funval = NULL;
1491 size_t paramcount, i;
1493 fid = vec_last(sy->ops).off;
1494 vec_shrinkby(sy->ops, 1);
1496 /* out[fid] is the function
1497 * everything above is parameters...
1499 if (!vec_size(sy->argc)) {
1500 parseerror(parser, "internal error: no argument counter available");
1504 paramcount = vec_last(sy->argc);
1507 if (vec_size(sy->out) < fid) {
1508 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1509 (unsigned long)vec_size(sy->out),
1511 (unsigned long)paramcount);
1515 fun = sy->out[fid].out;
1517 if (fun == intrinsic_debug_typestring) {
1519 if (fid+2 != vec_size(sy->out) ||
1520 vec_last(sy->out).block)
1522 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1525 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1526 ast_unref(vec_last(sy->out).out);
1527 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1528 (ast_expression*)parser_const_string(parser, ty, false));
1529 vec_shrinkby(sy->out, 1);
1533 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1537 if (fid+1 < vec_size(sy->out))
1540 if (fid+1 + paramcount != vec_size(sy->out)) {
1541 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1542 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1546 for (i = 0; i < paramcount; ++i)
1547 vec_push(call->params, sy->out[fid+1 + i].out);
1548 vec_shrinkby(sy->out, paramcount);
1549 (void)!ast_call_check_types(call);
1550 if (parser->max_param_count < paramcount)
1551 parser->max_param_count = paramcount;
1553 if (ast_istype(fun, ast_value)) {
1554 funval = (ast_value*)fun;
1555 if ((fun->expression.flags & AST_FLAG_VARIADIC) &&
1556 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1558 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1562 /* overwrite fid, the function, with a call */
1563 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1565 if (fun->expression.vtype != TYPE_FUNCTION) {
1566 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1570 if (!fun->expression.next) {
1571 parseerror(parser, "could not determine function return type");
1574 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1576 if (fun->expression.flags & AST_FLAG_DEPRECATED) {
1578 return !parsewarning(parser, WARN_DEPRECATED,
1579 "call to function (which is marked deprecated)\n",
1580 "-> it has been declared here: %s:%i",
1581 ast_ctx(fun).file, ast_ctx(fun).line);
1584 return !parsewarning(parser, WARN_DEPRECATED,
1585 "call to `%s` (which is marked deprecated)\n"
1586 "-> `%s` declared here: %s:%i",
1587 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1589 return !parsewarning(parser, WARN_DEPRECATED,
1590 "call to `%s` (deprecated: %s)\n"
1591 "-> `%s` declared here: %s:%i",
1592 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1596 if (vec_size(fun->expression.params) != paramcount &&
1597 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1598 vec_size(fun->expression.params) < paramcount))
1600 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1602 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1603 "too %s parameters for call to %s: expected %i, got %i\n"
1604 " -> `%s` has been declared here: %s:%i",
1605 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1606 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1608 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1609 "too %s parameters for function call: expected %i, got %i\n"
1610 " -> it has been declared here: %s:%i",
1611 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1612 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1619 static bool parser_close_paren(parser_t *parser, shunt *sy)
1621 if (!vec_size(sy->ops)) {
1622 parseerror(parser, "unmatched closing paren");
1626 while (vec_size(sy->ops)) {
1627 if (vec_last(sy->ops).isparen) {
1628 if (vec_last(sy->paren) == PAREN_FUNC) {
1630 if (!parser_close_call(parser, sy))
1634 if (vec_last(sy->paren) == PAREN_EXPR) {
1636 if (!vec_size(sy->out)) {
1637 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1638 vec_shrinkby(sy->ops, 1);
1641 vec_shrinkby(sy->ops, 1);
1644 if (vec_last(sy->paren) == PAREN_INDEX) {
1646 /* pop off the parenthesis */
1647 vec_shrinkby(sy->ops, 1);
1648 /* then apply the index operator */
1649 if (!parser_sy_apply_operator(parser, sy))
1653 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1654 vec_last(sy->paren) = PAREN_TERNARY2;
1655 /* pop off the parenthesis */
1656 vec_shrinkby(sy->ops, 1);
1659 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1662 if (!parser_sy_apply_operator(parser, sy))
1668 static void parser_reclassify_token(parser_t *parser)
1671 for (i = 0; i < operator_count; ++i) {
1672 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1673 parser->tok = TOKEN_OPERATOR;
1679 static ast_expression* parse_vararg_do(parser_t *parser)
1681 ast_expression *idx, *out;
1683 ast_value *funtype = parser->function->vtype;
1685 lex_ctx ctx = parser_ctx(parser);
1687 if (!parser_next(parser) || parser->tok != '(') {
1688 parseerror(parser, "expected parameter index and type in parenthesis");
1691 if (!parser_next(parser)) {
1692 parseerror(parser, "error parsing parameter index");
1696 idx = parse_expression_leave(parser, true, false, false);
1700 if (parser->tok != ',') {
1702 parseerror(parser, "expected comma after parameter index");
1706 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1708 parseerror(parser, "expected typename for vararg");
1712 typevar = parse_typename(parser, NULL, NULL);
1718 if (parser->tok != ')') {
1720 ast_delete(typevar);
1721 parseerror(parser, "expected closing paren");
1726 if (!parser_next(parser)) {
1728 ast_delete(typevar);
1729 parseerror(parser, "parse error after vararg");
1734 if (!parser->function->varargs) {
1736 ast_delete(typevar);
1737 parseerror(parser, "function has no variable argument list");
1741 if (funtype->expression.varparam &&
1742 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1746 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1747 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1748 compile_error(ast_ctx(typevar),
1749 "function was declared to take varargs of type `%s`, requested type is: %s",
1753 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1754 ast_type_adopt(out, typevar);
1755 ast_delete(typevar);
1759 static ast_expression* parse_vararg(parser_t *parser)
1761 bool old_noops = parser->lex->flags.noops;
1763 ast_expression *out;
1765 parser->lex->flags.noops = true;
1766 out = parse_vararg_do(parser);
1768 parser->lex->flags.noops = old_noops;
1772 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1774 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1775 parser->tok == TOKEN_IDENT &&
1776 !strcmp(parser_tokval(parser), "_"))
1778 /* a translatable string */
1781 parser->lex->flags.noops = true;
1782 if (!parser_next(parser) || parser->tok != '(') {
1783 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1786 parser->lex->flags.noops = false;
1787 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1788 parseerror(parser, "expected a constant string in translatable-string extension");
1791 val = parser_const_string(parser, parser_tokval(parser), true);
1794 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1796 if (!parser_next(parser) || parser->tok != ')') {
1797 parseerror(parser, "expected closing paren after translatable string");
1802 else if (parser->tok == TOKEN_DOTS)
1805 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1806 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1809 va = parse_vararg(parser);
1812 vec_push(sy->out, syexp(parser_ctx(parser), va));
1815 else if (parser->tok == TOKEN_FLOATCONST) {
1817 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1820 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1823 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1825 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1828 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1831 else if (parser->tok == TOKEN_STRINGCONST) {
1833 val = parser_const_string(parser, parser_tokval(parser), false);
1836 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1839 else if (parser->tok == TOKEN_VECTORCONST) {
1841 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1844 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1847 else if (parser->tok == TOKEN_IDENT)
1849 const char *ctoken = parser_tokval(parser);
1850 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1851 ast_expression *var;
1852 /* a_vector.{x,y,z} */
1853 if (!vec_size(sy->ops) ||
1854 !vec_last(sy->ops).etype ||
1855 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1856 (prev >= intrinsic_debug_typestring &&
1857 prev <= intrinsic_debug_typestring))
1859 /* When adding more intrinsics, fix the above condition */
1862 if (prev && prev->expression.vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1864 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1866 var = parser_find_var(parser, parser_tokval(parser));
1868 var = parser_find_field(parser, parser_tokval(parser));
1870 if (!var && with_labels) {
1871 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1873 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1874 var = (ast_expression*)lbl;
1875 vec_push(parser->labels, lbl);
1880 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1881 var = (ast_expression*)intrinsic_debug_typestring;
1883 /* now we try for the real intrinsic hashtable. If the string
1884 * begins with __builtin, we simply skip past it, otherwise we
1885 * use the identifier as is.
1887 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1888 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1890 var = intrin_func(parser, parser_tokval(parser));
1894 char *correct = NULL;
1898 * sometimes people use preprocessing predefs without enabling them
1899 * i've done this thousands of times already myself. Lets check for
1900 * it in the predef table. And diagnose it better :)
1902 if (!OPTS_FLAG(FTEPP_PREDEFS)) {
1903 for (i = 0; i < sizeof(ftepp_predefs)/sizeof(*ftepp_predefs); i++) {
1904 if (!strcmp(ftepp_predefs[i].name, parser_tokval(parser))) {
1905 parseerror(parser, "unexpected ident: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1912 * TODO: determine the best score for the identifier: be it
1913 * a variable, a field.
1915 * We should also consider adding correction tables for
1916 * other things as well.
1918 if (OPTS_OPTION_BOOL(OPTION_CORRECTION)) {
1920 correct_init(&corr);
1922 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1923 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1924 if (strcmp(correct, parser_tokval(parser))) {
1926 } else if (correct) {
1931 correct_free(&corr);
1934 parseerror(parser, "unexpected ident: %s (did you mean %s?)", parser_tokval(parser), correct);
1939 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1945 if (ast_istype(var, ast_value)) {
1946 ((ast_value*)var)->uses++;
1948 else if (ast_istype(var, ast_member)) {
1949 ast_member *mem = (ast_member*)var;
1950 if (ast_istype(mem->owner, ast_value))
1951 ((ast_value*)(mem->owner))->uses++;
1954 vec_push(sy->out, syexp(parser_ctx(parser), var));
1957 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
1961 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
1963 ast_expression *expr = NULL;
1966 bool wantop = false;
1967 /* only warn once about an assignment in a truth value because the current code
1968 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
1970 bool warn_truthvalue = true;
1972 /* count the parens because an if starts with one, so the
1973 * end of a condition is an unmatched closing paren
1977 memset(&sy, 0, sizeof(sy));
1979 parser->lex->flags.noops = false;
1981 parser_reclassify_token(parser);
1985 if (parser->tok == TOKEN_TYPENAME) {
1986 parseerror(parser, "unexpected typename");
1990 if (parser->tok == TOKEN_OPERATOR)
1992 /* classify the operator */
1993 const oper_info *op;
1994 const oper_info *olast = NULL;
1996 for (o = 0; o < operator_count; ++o) {
1997 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
1998 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1999 !strcmp(parser_tokval(parser), operators[o].op))
2004 if (o == operator_count) {
2005 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2008 /* found an operator */
2011 /* when declaring variables, a comma starts a new variable */
2012 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2013 /* fixup the token */
2018 /* a colon without a pervious question mark cannot be a ternary */
2019 if (!ternaries && op->id == opid2(':','?')) {
2024 if (op->id == opid1(',')) {
2025 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2026 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2030 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2031 olast = &operators[vec_last(sy.ops).etype-1];
2033 #define IsAssignOp(x) (\
2034 (x) == opid1('=') || \
2035 (x) == opid2('+','=') || \
2036 (x) == opid2('-','=') || \
2037 (x) == opid2('*','=') || \
2038 (x) == opid2('/','=') || \
2039 (x) == opid2('%','=') || \
2040 (x) == opid2('&','=') || \
2041 (x) == opid2('|','=') || \
2042 (x) == opid3('&','~','=') \
2044 if (warn_truthvalue) {
2045 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2046 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2047 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2050 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2051 warn_truthvalue = false;
2056 (op->prec < olast->prec) ||
2057 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2059 if (!parser_sy_apply_operator(parser, &sy))
2061 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2062 olast = &operators[vec_last(sy.ops).etype-1];
2067 if (op->id == opid1('(')) {
2069 size_t sycount = vec_size(sy.out);
2070 /* we expected an operator, this is the function-call operator */
2071 vec_push(sy.paren, PAREN_FUNC);
2072 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2073 vec_push(sy.argc, 0);
2075 vec_push(sy.paren, PAREN_EXPR);
2076 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2079 } else if (op->id == opid1('[')) {
2081 parseerror(parser, "unexpected array subscript");
2084 vec_push(sy.paren, PAREN_INDEX);
2085 /* push both the operator and the paren, this makes life easier */
2086 vec_push(sy.ops, syop(parser_ctx(parser), op));
2087 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2089 } else if (op->id == opid2('?',':')) {
2090 vec_push(sy.ops, syop(parser_ctx(parser), op));
2091 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2094 vec_push(sy.paren, PAREN_TERNARY1);
2095 } else if (op->id == opid2(':','?')) {
2096 if (!vec_size(sy.paren)) {
2097 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2100 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2101 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2104 if (!parser_close_paren(parser, &sy))
2106 vec_push(sy.ops, syop(parser_ctx(parser), op));
2110 vec_push(sy.ops, syop(parser_ctx(parser), op));
2111 wantop = !!(op->flags & OP_SUFFIX);
2114 else if (parser->tok == ')') {
2115 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2116 if (!parser_sy_apply_operator(parser, &sy))
2119 if (!vec_size(sy.paren))
2122 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2123 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2126 if (!parser_close_paren(parser, &sy))
2129 /* must be a function call without parameters */
2130 if (vec_last(sy.paren) != PAREN_FUNC) {
2131 parseerror(parser, "closing paren in invalid position");
2134 if (!parser_close_paren(parser, &sy))
2139 else if (parser->tok == '(') {
2140 parseerror(parser, "internal error: '(' should be classified as operator");
2143 else if (parser->tok == '[') {
2144 parseerror(parser, "internal error: '[' should be classified as operator");
2147 else if (parser->tok == ']') {
2148 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2149 if (!parser_sy_apply_operator(parser, &sy))
2152 if (!vec_size(sy.paren))
2154 if (vec_last(sy.paren) != PAREN_INDEX) {
2155 parseerror(parser, "mismatched parentheses, unexpected ']'");
2158 if (!parser_close_paren(parser, &sy))
2163 if (!parse_sya_operand(parser, &sy, with_labels))
2166 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2167 vec_last(sy.argc)++;
2172 parseerror(parser, "expected operator or end of statement");
2176 if (!parser_next(parser)) {
2179 if (parser->tok == ';' ||
2180 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2181 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2187 while (vec_size(sy.ops)) {
2188 if (!parser_sy_apply_operator(parser, &sy))
2192 parser->lex->flags.noops = true;
2193 if (!vec_size(sy.out)) {
2194 parseerror(parser, "empty expression");
2197 expr = sy.out[0].out;
2200 if (vec_size(sy.paren)) {
2201 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2209 parser->lex->flags.noops = true;
2210 for (i = 0; i < vec_size(sy.out); ++i) {
2212 ast_unref(sy.out[i].out);
2221 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2223 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2226 if (parser->tok != ';') {
2227 parseerror(parser, "semicolon expected after expression");
2231 if (!parser_next(parser)) {
2238 static void parser_enterblock(parser_t *parser)
2240 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2241 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2242 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2243 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2244 vec_push(parser->_block_ctx, parser_ctx(parser));
2247 vec_push(parser->correct_variables, correct_trie_new());
2248 vec_push(parser->correct_variables_score, NULL);
2251 static bool parser_leaveblock(parser_t *parser)
2254 size_t locals, typedefs;
2256 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2257 parseerror(parser, "internal error: parser_leaveblock with no block");
2261 util_htdel(vec_last(parser->variables));
2262 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2264 vec_pop(parser->variables);
2265 vec_pop(parser->correct_variables);
2266 vec_pop(parser->correct_variables_score);
2267 if (!vec_size(parser->_blocklocals)) {
2268 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2272 locals = vec_last(parser->_blocklocals);
2273 vec_pop(parser->_blocklocals);
2274 while (vec_size(parser->_locals) != locals) {
2275 ast_expression *e = vec_last(parser->_locals);
2276 ast_value *v = (ast_value*)e;
2277 vec_pop(parser->_locals);
2278 if (ast_istype(e, ast_value) && !v->uses) {
2279 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2284 typedefs = vec_last(parser->_blocktypedefs);
2285 while (vec_size(parser->_typedefs) != typedefs) {
2286 ast_delete(vec_last(parser->_typedefs));
2287 vec_pop(parser->_typedefs);
2289 util_htdel(vec_last(parser->typedefs));
2290 vec_pop(parser->typedefs);
2292 vec_pop(parser->_block_ctx);
2297 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2299 vec_push(parser->_locals, e);
2300 util_htset(vec_last(parser->variables), name, (void*)e);
2304 vec_last(parser->correct_variables),
2305 &vec_last(parser->correct_variables_score),
2310 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2312 vec_push(parser->globals, e);
2313 util_htset(parser->htglobals, name, e);
2317 parser->correct_variables[0],
2318 &parser->correct_variables_score[0],
2323 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2327 ast_expression *prev;
2329 if (cond->expression.vtype == TYPE_VOID || cond->expression.vtype >= TYPE_VARIANT) {
2331 ast_type_to_string(cond, ty, sizeof(ty));
2332 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2335 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
2338 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2341 parseerror(parser, "internal error: failed to process condition");
2346 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
2348 /* vector types need to be cast to true booleans */
2349 ast_binary *bin = (ast_binary*)cond;
2350 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2352 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2354 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2357 parseerror(parser, "internal error: failed to process condition");
2364 unary = (ast_unary*)cond;
2365 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2367 cond = unary->operand;
2368 unary->operand = NULL;
2371 unary = (ast_unary*)cond;
2375 parseerror(parser, "internal error: failed to process condition");
2377 if (ifnot) *_ifnot = !*_ifnot;
2381 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2384 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2387 lex_ctx ctx = parser_ctx(parser);
2389 (void)block; /* not touching */
2391 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2392 if (!parser_next(parser)) {
2393 parseerror(parser, "expected condition or 'not'");
2396 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2398 if (!parser_next(parser)) {
2399 parseerror(parser, "expected condition in parenthesis");
2403 if (parser->tok != '(') {
2404 parseerror(parser, "expected 'if' condition in parenthesis");
2407 /* parse into the expression */
2408 if (!parser_next(parser)) {
2409 parseerror(parser, "expected 'if' condition after opening paren");
2412 /* parse the condition */
2413 cond = parse_expression_leave(parser, false, true, false);
2417 if (parser->tok != ')') {
2418 parseerror(parser, "expected closing paren after 'if' condition");
2422 /* parse into the 'then' branch */
2423 if (!parser_next(parser)) {
2424 parseerror(parser, "expected statement for on-true branch of 'if'");
2428 if (!parse_statement_or_block(parser, &ontrue)) {
2433 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2434 /* check for an else */
2435 if (!strcmp(parser_tokval(parser), "else")) {
2436 /* parse into the 'else' branch */
2437 if (!parser_next(parser)) {
2438 parseerror(parser, "expected on-false branch after 'else'");
2443 if (!parse_statement_or_block(parser, &onfalse)) {
2450 cond = process_condition(parser, cond, &ifnot);
2452 if (ontrue) ast_delete(ontrue);
2453 if (onfalse) ast_delete(onfalse);
2458 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2460 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2461 *out = (ast_expression*)ifthen;
2465 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2466 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2471 /* skip the 'while' and get the body */
2472 if (!parser_next(parser)) {
2473 if (OPTS_FLAG(LOOP_LABELS))
2474 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2476 parseerror(parser, "expected 'while' condition in parenthesis");
2480 if (parser->tok == ':') {
2481 if (!OPTS_FLAG(LOOP_LABELS))
2482 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2483 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2484 parseerror(parser, "expected loop label");
2487 label = util_strdup(parser_tokval(parser));
2488 if (!parser_next(parser)) {
2490 parseerror(parser, "expected 'while' condition in parenthesis");
2495 if (parser->tok != '(') {
2496 parseerror(parser, "expected 'while' condition in parenthesis");
2500 vec_push(parser->breaks, label);
2501 vec_push(parser->continues, label);
2503 rv = parse_while_go(parser, block, out);
2506 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2507 parseerror(parser, "internal error: label stack corrupted");
2513 vec_pop(parser->breaks);
2514 vec_pop(parser->continues);
2519 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2522 ast_expression *cond, *ontrue;
2526 lex_ctx ctx = parser_ctx(parser);
2528 (void)block; /* not touching */
2530 /* parse into the expression */
2531 if (!parser_next(parser)) {
2532 parseerror(parser, "expected 'while' condition after opening paren");
2535 /* parse the condition */
2536 cond = parse_expression_leave(parser, false, true, false);
2540 if (parser->tok != ')') {
2541 parseerror(parser, "expected closing paren after 'while' condition");
2545 /* parse into the 'then' branch */
2546 if (!parser_next(parser)) {
2547 parseerror(parser, "expected while-loop body");
2551 if (!parse_statement_or_block(parser, &ontrue)) {
2556 cond = process_condition(parser, cond, &ifnot);
2561 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2562 *out = (ast_expression*)aloop;
2566 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2567 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2572 /* skip the 'do' and get the body */
2573 if (!parser_next(parser)) {
2574 if (OPTS_FLAG(LOOP_LABELS))
2575 parseerror(parser, "expected loop label or body");
2577 parseerror(parser, "expected loop body");
2581 if (parser->tok == ':') {
2582 if (!OPTS_FLAG(LOOP_LABELS))
2583 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2584 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2585 parseerror(parser, "expected loop label");
2588 label = util_strdup(parser_tokval(parser));
2589 if (!parser_next(parser)) {
2591 parseerror(parser, "expected loop body");
2596 vec_push(parser->breaks, label);
2597 vec_push(parser->continues, label);
2599 rv = parse_dowhile_go(parser, block, out);
2602 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2603 parseerror(parser, "internal error: label stack corrupted");
2609 vec_pop(parser->breaks);
2610 vec_pop(parser->continues);
2615 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2618 ast_expression *cond, *ontrue;
2622 lex_ctx ctx = parser_ctx(parser);
2624 (void)block; /* not touching */
2626 if (!parse_statement_or_block(parser, &ontrue))
2629 /* expect the "while" */
2630 if (parser->tok != TOKEN_KEYWORD ||
2631 strcmp(parser_tokval(parser), "while"))
2633 parseerror(parser, "expected 'while' and condition");
2638 /* skip the 'while' and check for opening paren */
2639 if (!parser_next(parser) || parser->tok != '(') {
2640 parseerror(parser, "expected 'while' condition in parenthesis");
2644 /* parse into the expression */
2645 if (!parser_next(parser)) {
2646 parseerror(parser, "expected 'while' condition after opening paren");
2650 /* parse the condition */
2651 cond = parse_expression_leave(parser, false, true, false);
2655 if (parser->tok != ')') {
2656 parseerror(parser, "expected closing paren after 'while' condition");
2662 if (!parser_next(parser) || parser->tok != ';') {
2663 parseerror(parser, "expected semicolon after condition");
2669 if (!parser_next(parser)) {
2670 parseerror(parser, "parse error");
2676 cond = process_condition(parser, cond, &ifnot);
2681 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2682 *out = (ast_expression*)aloop;
2686 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2687 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2692 /* skip the 'for' and check for opening paren */
2693 if (!parser_next(parser)) {
2694 if (OPTS_FLAG(LOOP_LABELS))
2695 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2697 parseerror(parser, "expected 'for' expressions in parenthesis");
2701 if (parser->tok == ':') {
2702 if (!OPTS_FLAG(LOOP_LABELS))
2703 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2704 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2705 parseerror(parser, "expected loop label");
2708 label = util_strdup(parser_tokval(parser));
2709 if (!parser_next(parser)) {
2711 parseerror(parser, "expected 'for' expressions in parenthesis");
2716 if (parser->tok != '(') {
2717 parseerror(parser, "expected 'for' expressions in parenthesis");
2721 vec_push(parser->breaks, label);
2722 vec_push(parser->continues, label);
2724 rv = parse_for_go(parser, block, out);
2727 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2728 parseerror(parser, "internal error: label stack corrupted");
2734 vec_pop(parser->breaks);
2735 vec_pop(parser->continues);
2739 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2742 ast_expression *initexpr, *cond, *increment, *ontrue;
2748 lex_ctx ctx = parser_ctx(parser);
2750 parser_enterblock(parser);
2757 /* parse into the expression */
2758 if (!parser_next(parser)) {
2759 parseerror(parser, "expected 'for' initializer after opening paren");
2764 if (parser->tok == TOKEN_IDENT)
2765 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2767 if (typevar || parser->tok == TOKEN_TYPENAME) {
2769 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2770 if (parsewarning(parser, WARN_EXTENSIONS,
2771 "current standard does not allow variable declarations in for-loop initializers"))
2775 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2778 else if (parser->tok != ';')
2780 initexpr = parse_expression_leave(parser, false, false, false);
2785 /* move on to condition */
2786 if (parser->tok != ';') {
2787 parseerror(parser, "expected semicolon after for-loop initializer");
2790 if (!parser_next(parser)) {
2791 parseerror(parser, "expected for-loop condition");
2795 /* parse the condition */
2796 if (parser->tok != ';') {
2797 cond = parse_expression_leave(parser, false, true, false);
2802 /* move on to incrementor */
2803 if (parser->tok != ';') {
2804 parseerror(parser, "expected semicolon after for-loop initializer");
2807 if (!parser_next(parser)) {
2808 parseerror(parser, "expected for-loop condition");
2812 /* parse the incrementor */
2813 if (parser->tok != ')') {
2814 lex_ctx condctx = parser_ctx(parser);
2815 increment = parse_expression_leave(parser, false, false, false);
2818 if (!ast_side_effects(increment)) {
2819 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2825 if (parser->tok != ')') {
2826 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2829 /* parse into the 'then' branch */
2830 if (!parser_next(parser)) {
2831 parseerror(parser, "expected for-loop body");
2834 if (!parse_statement_or_block(parser, &ontrue))
2838 cond = process_condition(parser, cond, &ifnot);
2842 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2843 *out = (ast_expression*)aloop;
2845 if (!parser_leaveblock(parser))
2849 if (initexpr) ast_delete(initexpr);
2850 if (cond) ast_delete(cond);
2851 if (increment) ast_delete(increment);
2852 (void)!parser_leaveblock(parser);
2856 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2858 ast_expression *exp = NULL;
2859 ast_return *ret = NULL;
2860 ast_value *expected = parser->function->vtype;
2862 lex_ctx ctx = parser_ctx(parser);
2864 (void)block; /* not touching */
2866 if (!parser_next(parser)) {
2867 parseerror(parser, "expected return expression");
2871 if (parser->tok != ';') {
2872 exp = parse_expression(parser, false, false);
2876 if (exp->expression.vtype != TYPE_NIL &&
2877 exp->expression.vtype != expected->expression.next->expression.vtype)
2879 parseerror(parser, "return with invalid expression");
2882 ret = ast_return_new(ctx, exp);
2888 if (!parser_next(parser))
2889 parseerror(parser, "parse error");
2890 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2891 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2893 ret = ast_return_new(ctx, NULL);
2895 *out = (ast_expression*)ret;
2899 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2902 unsigned int levels = 0;
2903 lex_ctx ctx = parser_ctx(parser);
2904 const char **loops = (is_continue ? parser->continues : parser->breaks);
2906 (void)block; /* not touching */
2907 if (!parser_next(parser)) {
2908 parseerror(parser, "expected semicolon or loop label");
2912 if (!vec_size(loops)) {
2914 parseerror(parser, "`continue` can only be used inside loops");
2916 parseerror(parser, "`break` can only be used inside loops or switches");
2919 if (parser->tok == TOKEN_IDENT) {
2920 if (!OPTS_FLAG(LOOP_LABELS))
2921 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2922 i = vec_size(loops);
2924 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2927 parseerror(parser, "no such loop to %s: `%s`",
2928 (is_continue ? "continue" : "break out of"),
2929 parser_tokval(parser));
2934 if (!parser_next(parser)) {
2935 parseerror(parser, "expected semicolon");
2940 if (parser->tok != ';') {
2941 parseerror(parser, "expected semicolon");
2945 if (!parser_next(parser))
2946 parseerror(parser, "parse error");
2948 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2952 /* returns true when it was a variable qualifier, false otherwise!
2953 * on error, cvq is set to CV_WRONG
2955 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
2957 bool had_const = false;
2958 bool had_var = false;
2959 bool had_noref = false;
2960 bool had_attrib = false;
2961 bool had_static = false;
2966 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2968 /* parse an attribute */
2969 if (!parser_next(parser)) {
2970 parseerror(parser, "expected attribute after `[[`");
2974 if (!strcmp(parser_tokval(parser), "noreturn")) {
2975 flags |= AST_FLAG_NORETURN;
2976 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2977 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2982 else if (!strcmp(parser_tokval(parser), "noref")) {
2984 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2985 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2990 else if (!strcmp(parser_tokval(parser), "inline")) {
2991 flags |= AST_FLAG_INLINE;
2992 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2993 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2998 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
2999 flags |= AST_FLAG_ALIAS;
3002 if (!parser_next(parser)) {
3003 parseerror(parser, "parse error in attribute");
3007 if (parser->tok == '(') {
3008 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3009 parseerror(parser, "`alias` attribute missing parameter");
3013 *message = util_strdup(parser_tokval(parser));
3015 if (!parser_next(parser)) {
3016 parseerror(parser, "parse error in attribute");
3020 if (parser->tok != ')') {
3021 parseerror(parser, "`alias` attribute expected `)` after parameter");
3025 if (!parser_next(parser)) {
3026 parseerror(parser, "parse error in attribute");
3031 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3032 parseerror(parser, "`alias` attribute expected `]]`");
3036 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3037 flags |= AST_FLAG_DEPRECATED;
3040 if (!parser_next(parser)) {
3041 parseerror(parser, "parse error in attribute");
3045 if (parser->tok == '(') {
3046 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3047 parseerror(parser, "`deprecated` attribute missing parameter");
3051 *message = util_strdup(parser_tokval(parser));
3053 if (!parser_next(parser)) {
3054 parseerror(parser, "parse error in attribute");
3058 if(parser->tok != ')') {
3059 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3063 if (!parser_next(parser)) {
3064 parseerror(parser, "parse error in attribute");
3069 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3070 parseerror(parser, "`deprecated` attribute expected `]]`");
3073 if (*message) mem_d(*message);
3081 /* Skip tokens until we hit a ]] */
3082 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3083 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3084 if (!parser_next(parser)) {
3085 parseerror(parser, "error inside attribute");
3092 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3094 else if (!strcmp(parser_tokval(parser), "const"))
3096 else if (!strcmp(parser_tokval(parser), "var"))
3098 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3100 else if (!strcmp(parser_tokval(parser), "noref"))
3102 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3107 if (!parser_next(parser))
3117 *is_static = had_static;
3121 parseerror(parser, "parse error after variable qualifier");
3126 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3127 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3132 /* skip the 'while' and get the body */
3133 if (!parser_next(parser)) {
3134 if (OPTS_FLAG(LOOP_LABELS))
3135 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3137 parseerror(parser, "expected 'switch' operand in parenthesis");
3141 if (parser->tok == ':') {
3142 if (!OPTS_FLAG(LOOP_LABELS))
3143 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3144 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3145 parseerror(parser, "expected loop label");
3148 label = util_strdup(parser_tokval(parser));
3149 if (!parser_next(parser)) {
3151 parseerror(parser, "expected 'switch' operand in parenthesis");
3156 if (parser->tok != '(') {
3157 parseerror(parser, "expected 'switch' operand in parenthesis");
3161 vec_push(parser->breaks, label);
3163 rv = parse_switch_go(parser, block, out);
3166 if (vec_last(parser->breaks) != label) {
3167 parseerror(parser, "internal error: label stack corrupted");
3173 vec_pop(parser->breaks);
3178 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3180 ast_expression *operand;
3183 ast_switch *switchnode;
3184 ast_switch_case swcase;
3187 bool noref, is_static;
3188 uint32_t qflags = 0;
3190 lex_ctx ctx = parser_ctx(parser);
3192 (void)block; /* not touching */
3195 /* parse into the expression */
3196 if (!parser_next(parser)) {
3197 parseerror(parser, "expected switch operand");
3200 /* parse the operand */
3201 operand = parse_expression_leave(parser, false, false, false);
3205 switchnode = ast_switch_new(ctx, operand);
3208 if (parser->tok != ')') {
3209 ast_delete(switchnode);
3210 parseerror(parser, "expected closing paren after 'switch' operand");
3214 /* parse over the opening paren */
3215 if (!parser_next(parser) || parser->tok != '{') {
3216 ast_delete(switchnode);
3217 parseerror(parser, "expected list of cases");
3221 if (!parser_next(parser)) {
3222 ast_delete(switchnode);
3223 parseerror(parser, "expected 'case' or 'default'");
3227 /* new block; allow some variables to be declared here */
3228 parser_enterblock(parser);
3231 if (parser->tok == TOKEN_IDENT)
3232 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3233 if (typevar || parser->tok == TOKEN_TYPENAME) {
3234 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3235 ast_delete(switchnode);
3240 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3242 if (cvq == CV_WRONG) {
3243 ast_delete(switchnode);
3246 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3247 ast_delete(switchnode);
3256 while (parser->tok != '}') {
3257 ast_block *caseblock;
3259 if (!strcmp(parser_tokval(parser), "case")) {
3260 if (!parser_next(parser)) {
3261 ast_delete(switchnode);
3262 parseerror(parser, "expected expression for case");
3265 swcase.value = parse_expression_leave(parser, false, false, false);
3266 if (!swcase.value) {
3267 ast_delete(switchnode);
3268 parseerror(parser, "expected expression for case");
3271 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3272 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3273 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3279 else if (!strcmp(parser_tokval(parser), "default")) {
3280 swcase.value = NULL;
3281 if (!parser_next(parser)) {
3282 ast_delete(switchnode);
3283 parseerror(parser, "expected colon");
3288 ast_delete(switchnode);
3289 parseerror(parser, "expected 'case' or 'default'");
3293 /* Now the colon and body */
3294 if (parser->tok != ':') {
3295 if (swcase.value) ast_unref(swcase.value);
3296 ast_delete(switchnode);
3297 parseerror(parser, "expected colon");
3301 if (!parser_next(parser)) {
3302 if (swcase.value) ast_unref(swcase.value);
3303 ast_delete(switchnode);
3304 parseerror(parser, "expected statements or case");
3307 caseblock = ast_block_new(parser_ctx(parser));
3309 if (swcase.value) ast_unref(swcase.value);
3310 ast_delete(switchnode);
3313 swcase.code = (ast_expression*)caseblock;
3314 vec_push(switchnode->cases, swcase);
3316 ast_expression *expr;
3317 if (parser->tok == '}')
3319 if (parser->tok == TOKEN_KEYWORD) {
3320 if (!strcmp(parser_tokval(parser), "case") ||
3321 !strcmp(parser_tokval(parser), "default"))
3326 if (!parse_statement(parser, caseblock, &expr, true)) {
3327 ast_delete(switchnode);
3332 if (!ast_block_add_expr(caseblock, expr)) {
3333 ast_delete(switchnode);
3339 parser_leaveblock(parser);
3342 if (parser->tok != '}') {
3343 ast_delete(switchnode);
3344 parseerror(parser, "expected closing paren of case list");
3347 if (!parser_next(parser)) {
3348 ast_delete(switchnode);
3349 parseerror(parser, "parse error after switch");
3352 *out = (ast_expression*)switchnode;
3356 /* parse computed goto sides */
3357 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3358 ast_expression *on_true;
3359 ast_expression *on_false;
3360 ast_expression *cond;
3365 if (ast_istype(*side, ast_ternary)) {
3366 ast_ternary *tern = (ast_ternary*)*side;
3367 on_true = parse_goto_computed(parser, &tern->on_true);
3368 on_false = parse_goto_computed(parser, &tern->on_false);
3370 if (!on_true || !on_false) {
3371 parseerror(parser, "expected label or expression in ternary");
3372 if (on_true) ast_unref(on_true);
3373 if (on_false) ast_unref(on_false);
3381 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3382 } else if (ast_istype(*side, ast_label)) {
3383 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3384 ast_goto_set_label(gt, ((ast_label*)*side));
3386 return (ast_expression*)gt;
3391 static bool parse_goto(parser_t *parser, ast_expression **out)
3393 ast_goto *gt = NULL;
3394 ast_expression *lbl;
3396 if (!parser_next(parser))
3399 if (parser->tok != TOKEN_IDENT) {
3400 ast_expression *expression;
3402 /* could be an expression i.e computed goto :-) */
3403 if (parser->tok != '(') {
3404 parseerror(parser, "expected label name after `goto`");
3408 /* failed to parse expression for goto */
3409 if (!(expression = parse_expression(parser, false, true)) ||
3410 !(*out = parse_goto_computed(parser, &expression))) {
3411 parseerror(parser, "invalid goto expression");
3412 ast_unref(expression);
3419 /* not computed goto */
3420 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3421 lbl = parser_find_label(parser, gt->name);
3423 if (!ast_istype(lbl, ast_label)) {
3424 parseerror(parser, "internal error: label is not an ast_label");
3428 ast_goto_set_label(gt, (ast_label*)lbl);
3431 vec_push(parser->gotos, gt);
3433 if (!parser_next(parser) || parser->tok != ';') {
3434 parseerror(parser, "semicolon expected after goto label");
3437 if (!parser_next(parser)) {
3438 parseerror(parser, "parse error after goto");
3442 *out = (ast_expression*)gt;
3446 static bool parse_skipwhite(parser_t *parser)
3449 if (!parser_next(parser))
3451 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3452 return parser->tok < TOKEN_ERROR;
3455 static bool parse_eol(parser_t *parser)
3457 if (!parse_skipwhite(parser))
3459 return parser->tok == TOKEN_EOL;
3462 static bool parse_pragma_do(parser_t *parser)
3464 if (!parser_next(parser) ||
3465 parser->tok != TOKEN_IDENT ||
3466 strcmp(parser_tokval(parser), "pragma"))
3468 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3471 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3472 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3476 if (!strcmp(parser_tokval(parser), "noref")) {
3477 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3478 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3481 parser->noref = !!parser_token(parser)->constval.i;
3482 if (!parse_eol(parser)) {
3483 parseerror(parser, "parse error after `noref` pragma");
3489 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3496 static bool parse_pragma(parser_t *parser)
3499 parser->lex->flags.preprocessing = true;
3500 parser->lex->flags.mergelines = true;
3501 rv = parse_pragma_do(parser);
3502 if (parser->tok != TOKEN_EOL) {
3503 parseerror(parser, "junk after pragma");
3506 parser->lex->flags.preprocessing = false;
3507 parser->lex->flags.mergelines = false;
3508 if (!parser_next(parser)) {
3509 parseerror(parser, "parse error after pragma");
3515 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3517 bool noref, is_static;
3519 uint32_t qflags = 0;
3520 ast_value *typevar = NULL;
3521 char *vstring = NULL;
3525 if (parser->tok == TOKEN_IDENT)
3526 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3528 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3530 /* local variable */
3532 parseerror(parser, "cannot declare a variable from here");
3535 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3536 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3539 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3543 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3545 if (cvq == CV_WRONG)
3547 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3549 else if (parser->tok == TOKEN_KEYWORD)
3551 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3556 if (!parser_next(parser)) {
3557 parseerror(parser, "parse error after __builtin_debug_printtype");
3561 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3563 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3564 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3565 if (!parser_next(parser)) {
3566 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3572 if (!parse_statement(parser, block, out, allow_cases))
3575 con_out("__builtin_debug_printtype: got no output node\n");
3578 ast_type_to_string(*out, ty, sizeof(ty));
3579 con_out("__builtin_debug_printtype: `%s`\n", ty);
3584 else if (!strcmp(parser_tokval(parser), "return"))
3586 return parse_return(parser, block, out);
3588 else if (!strcmp(parser_tokval(parser), "if"))
3590 return parse_if(parser, block, out);
3592 else if (!strcmp(parser_tokval(parser), "while"))
3594 return parse_while(parser, block, out);
3596 else if (!strcmp(parser_tokval(parser), "do"))
3598 return parse_dowhile(parser, block, out);
3600 else if (!strcmp(parser_tokval(parser), "for"))
3602 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3603 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3606 return parse_for(parser, block, out);
3608 else if (!strcmp(parser_tokval(parser), "break"))
3610 return parse_break_continue(parser, block, out, false);
3612 else if (!strcmp(parser_tokval(parser), "continue"))
3614 return parse_break_continue(parser, block, out, true);
3616 else if (!strcmp(parser_tokval(parser), "switch"))
3618 return parse_switch(parser, block, out);
3620 else if (!strcmp(parser_tokval(parser), "case") ||
3621 !strcmp(parser_tokval(parser), "default"))
3624 parseerror(parser, "unexpected 'case' label");
3629 else if (!strcmp(parser_tokval(parser), "goto"))
3631 return parse_goto(parser, out);
3633 else if (!strcmp(parser_tokval(parser), "typedef"))
3635 if (!parser_next(parser)) {
3636 parseerror(parser, "expected type definition after 'typedef'");
3639 return parse_typedef(parser);
3641 parseerror(parser, "Unexpected keyword");
3644 else if (parser->tok == '{')
3647 inner = parse_block(parser);
3650 *out = (ast_expression*)inner;
3653 else if (parser->tok == ':')
3657 if (!parser_next(parser)) {
3658 parseerror(parser, "expected label name");
3661 if (parser->tok != TOKEN_IDENT) {
3662 parseerror(parser, "label must be an identifier");
3665 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3667 if (!label->undefined) {
3668 parseerror(parser, "label `%s` already defined", label->name);
3671 label->undefined = false;
3674 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3675 vec_push(parser->labels, label);
3677 *out = (ast_expression*)label;
3678 if (!parser_next(parser)) {
3679 parseerror(parser, "parse error after label");
3682 for (i = 0; i < vec_size(parser->gotos); ++i) {
3683 if (!strcmp(parser->gotos[i]->name, label->name)) {
3684 ast_goto_set_label(parser->gotos[i], label);
3685 vec_remove(parser->gotos, i, 1);
3691 else if (parser->tok == ';')
3693 if (!parser_next(parser)) {
3694 parseerror(parser, "parse error after empty statement");
3701 lex_ctx ctx = parser_ctx(parser);
3702 ast_expression *exp = parse_expression(parser, false, false);
3706 if (!ast_side_effects(exp)) {
3707 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3714 static bool parse_enum(parser_t *parser)
3717 bool reverse = false;
3719 ast_value **values = NULL;
3720 ast_value *var = NULL;
3723 ast_expression *old;
3725 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3726 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3730 /* enumeration attributes (can add more later) */
3731 if (parser->tok == ':') {
3732 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3733 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3738 if (!strcmp(parser_tokval(parser), "flag")) {
3742 else if (!strcmp(parser_tokval(parser), "reverse")) {
3746 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3750 if (!parser_next(parser) || parser->tok != '{') {
3751 parseerror(parser, "expected `{` after enum attribute ");
3757 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3758 if (parser->tok == '}') {
3759 /* allow an empty enum */
3762 parseerror(parser, "expected identifier or `}`");
3766 old = parser_find_field(parser, parser_tokval(parser));
3768 old = parser_find_global(parser, parser_tokval(parser));
3770 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3771 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3775 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3776 vec_push(values, var);
3777 var->cvq = CV_CONST;
3778 var->hasvalue = true;
3780 /* for flagged enumerations increment in POTs of TWO */
3781 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3782 parser_addglobal(parser, var->name, (ast_expression*)var);
3784 if (!parser_next(parser)) {
3785 parseerror(parser, "expected `=`, `}` or comma after identifier");
3789 if (parser->tok == ',')
3791 if (parser->tok == '}')
3793 if (parser->tok != '=') {
3794 parseerror(parser, "expected `=`, `}` or comma after identifier");
3798 if (!parser_next(parser)) {
3799 parseerror(parser, "expected expression after `=`");
3803 /* We got a value! */
3804 old = parse_expression_leave(parser, true, false, false);
3805 asvalue = (ast_value*)old;
3806 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3807 compile_error(ast_ctx(var), "constant value or expression expected");
3810 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3812 if (parser->tok == '}')
3814 if (parser->tok != ',') {
3815 parseerror(parser, "expected `}` or comma after expression");
3820 /* patch them all (for reversed attribute) */
3823 for (i = 0; i < vec_size(values); i++)
3824 values[i]->constval.vfloat = vec_size(values) - i - 1;
3827 if (parser->tok != '}') {
3828 parseerror(parser, "internal error: breaking without `}`");
3832 if (!parser_next(parser) || parser->tok != ';') {
3833 parseerror(parser, "expected semicolon after enumeration");
3837 if (!parser_next(parser)) {
3838 parseerror(parser, "parse error after enumeration");
3850 static bool parse_block_into(parser_t *parser, ast_block *block)
3854 parser_enterblock(parser);
3856 if (!parser_next(parser)) { /* skip the '{' */
3857 parseerror(parser, "expected function body");
3861 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3863 ast_expression *expr = NULL;
3864 if (parser->tok == '}')
3867 if (!parse_statement(parser, block, &expr, false)) {
3868 /* parseerror(parser, "parse error"); */
3874 if (!ast_block_add_expr(block, expr)) {
3881 if (parser->tok != '}') {
3884 (void)parser_next(parser);
3888 if (!parser_leaveblock(parser))
3890 return retval && !!block;
3893 static ast_block* parse_block(parser_t *parser)
3896 block = ast_block_new(parser_ctx(parser));
3899 if (!parse_block_into(parser, block)) {
3900 ast_block_delete(block);
3906 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3908 if (parser->tok == '{') {
3909 *out = (ast_expression*)parse_block(parser);
3912 return parse_statement(parser, NULL, out, false);
3915 static bool create_vector_members(ast_value *var, ast_member **me)
3918 size_t len = strlen(var->name);
3920 for (i = 0; i < 3; ++i) {
3921 char *name = (char*)mem_a(len+3);
3922 memcpy(name, var->name, len);
3924 name[len+1] = 'x'+i;
3926 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3935 do { ast_member_delete(me[--i]); } while(i);
3939 static bool parse_function_body(parser_t *parser, ast_value *var)
3941 ast_block *block = NULL;
3946 ast_expression *framenum = NULL;
3947 ast_expression *nextthink = NULL;
3948 /* None of the following have to be deleted */
3949 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3950 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3951 bool has_frame_think;
3955 has_frame_think = false;
3956 old = parser->function;
3958 if (var->expression.flags & AST_FLAG_ALIAS) {
3959 parseerror(parser, "function aliases cannot have bodies");
3963 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3964 parseerror(parser, "gotos/labels leaking");
3968 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
3969 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3970 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
3976 if (parser->tok == '[') {
3977 /* got a frame definition: [ framenum, nextthink ]
3978 * this translates to:
3979 * self.frame = framenum;
3980 * self.nextthink = time + 0.1;
3981 * self.think = nextthink;
3985 fld_think = parser_find_field(parser, "think");
3986 fld_nextthink = parser_find_field(parser, "nextthink");
3987 fld_frame = parser_find_field(parser, "frame");
3988 if (!fld_think || !fld_nextthink || !fld_frame) {
3989 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3990 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3993 gbl_time = parser_find_global(parser, "time");
3994 gbl_self = parser_find_global(parser, "self");
3995 if (!gbl_time || !gbl_self) {
3996 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3997 parseerror(parser, "please declare the following globals: `time`, `self`");
4001 if (!parser_next(parser))
4004 framenum = parse_expression_leave(parser, true, false, false);
4006 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4009 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4010 ast_unref(framenum);
4011 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4015 if (parser->tok != ',') {
4016 ast_unref(framenum);
4017 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4018 parseerror(parser, "Got a %i\n", parser->tok);
4022 if (!parser_next(parser)) {
4023 ast_unref(framenum);
4027 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4029 /* qc allows the use of not-yet-declared functions here
4030 * - this automatically creates a prototype */
4031 ast_value *thinkfunc;
4032 ast_expression *functype = fld_think->expression.next;
4034 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
4035 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4036 ast_unref(framenum);
4037 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4040 ast_type_adopt(thinkfunc, functype);
4042 if (!parser_next(parser)) {
4043 ast_unref(framenum);
4044 ast_delete(thinkfunc);
4048 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4050 nextthink = (ast_expression*)thinkfunc;
4053 nextthink = parse_expression_leave(parser, true, false, false);
4055 ast_unref(framenum);
4056 parseerror(parser, "expected a think-function in [frame,think] notation");
4061 if (!ast_istype(nextthink, ast_value)) {
4062 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4066 if (retval && parser->tok != ']') {
4067 parseerror(parser, "expected closing `]` for [frame,think] notation");
4071 if (retval && !parser_next(parser)) {
4075 if (retval && parser->tok != '{') {
4076 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4081 ast_unref(nextthink);
4082 ast_unref(framenum);
4086 has_frame_think = true;
4089 block = ast_block_new(parser_ctx(parser));
4091 parseerror(parser, "failed to allocate block");
4092 if (has_frame_think) {
4093 ast_unref(nextthink);
4094 ast_unref(framenum);
4099 if (has_frame_think) {
4101 ast_expression *self_frame;
4102 ast_expression *self_nextthink;
4103 ast_expression *self_think;
4104 ast_expression *time_plus_1;
4105 ast_store *store_frame;
4106 ast_store *store_nextthink;
4107 ast_store *store_think;
4109 ctx = parser_ctx(parser);
4110 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4111 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4112 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4114 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4115 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4117 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4118 if (self_frame) ast_delete(self_frame);
4119 if (self_nextthink) ast_delete(self_nextthink);
4120 if (self_think) ast_delete(self_think);
4121 if (time_plus_1) ast_delete(time_plus_1);
4127 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4128 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4129 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4132 ast_delete(self_frame);
4135 if (!store_nextthink) {
4136 ast_delete(self_nextthink);
4140 ast_delete(self_think);
4144 if (store_frame) ast_delete(store_frame);
4145 if (store_nextthink) ast_delete(store_nextthink);
4146 if (store_think) ast_delete(store_think);
4149 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4150 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4151 !ast_block_add_expr(block, (ast_expression*)store_think))
4158 parseerror(parser, "failed to generate code for [frame,think]");
4159 ast_unref(nextthink);
4160 ast_unref(framenum);
4166 if (var->hasvalue) {
4167 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4168 ast_block_delete(block);
4172 func = ast_function_new(ast_ctx(var), var->name, var);
4174 parseerror(parser, "failed to allocate function for `%s`", var->name);
4175 ast_block_delete(block);
4178 vec_push(parser->functions, func);
4180 parser_enterblock(parser);
4182 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4184 ast_value *param = var->expression.params[parami];
4187 if (param->expression.vtype != TYPE_VECTOR &&
4188 (param->expression.vtype != TYPE_FIELD ||
4189 param->expression.next->expression.vtype != TYPE_VECTOR))
4194 if (!create_vector_members(param, me)) {
4195 ast_block_delete(block);
4199 for (e = 0; e < 3; ++e) {
4200 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4201 ast_block_collect(block, (ast_expression*)me[e]);
4205 if (var->argcounter) {
4206 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4207 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4211 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4213 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4214 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4215 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4216 varargs->expression.count = 0;
4217 snprintf(name, sizeof(name), "%s##va##SET", var->name);
4218 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4219 ast_delete(varargs);
4220 ast_block_delete(block);
4223 snprintf(name, sizeof(name), "%s##va##GET", var->name);
4224 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4225 ast_delete(varargs);
4226 ast_block_delete(block);
4229 func->varargs = varargs;
4231 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4234 parser->function = func;
4235 if (!parse_block_into(parser, block)) {
4236 ast_block_delete(block);
4240 vec_push(func->blocks, block);
4242 parser->function = old;
4243 if (!parser_leaveblock(parser))
4245 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4246 parseerror(parser, "internal error: local scopes left");
4250 if (parser->tok == ';')
4251 return parser_next(parser);
4252 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4253 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4257 (void)!parser_leaveblock(parser);
4258 vec_pop(parser->functions);
4259 ast_function_delete(func);
4260 var->constval.vfunc = NULL;
4263 parser->function = old;
4267 static ast_expression *array_accessor_split(
4272 ast_expression *left,
4273 ast_expression *right
4279 lex_ctx ctx = ast_ctx(array);
4281 if (!left || !right) {
4282 if (left) ast_delete(left);
4283 if (right) ast_delete(right);
4287 cmp = ast_binary_new(ctx, INSTR_LT,
4288 (ast_expression*)index,
4289 (ast_expression*)parser_const_float(parser, middle));
4293 parseerror(parser, "internal error: failed to create comparison for array setter");
4297 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4299 ast_delete(cmp); /* will delete left and right */
4300 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4304 return (ast_expression*)ifthen;
4307 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4309 lex_ctx ctx = ast_ctx(array);
4311 if (from+1 == afterend) {
4312 /* set this value */
4315 ast_array_index *subscript;
4317 int assignop = type_store_instr[value->expression.vtype];
4319 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4320 assignop = INSTR_STORE_V;
4322 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4326 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4328 ast_delete(subscript);
4332 block = ast_block_new(ctx);
4338 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4343 ret = ast_return_new(ctx, NULL);
4349 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4354 return (ast_expression*)block;
4356 ast_expression *left, *right;
4357 size_t diff = afterend - from;
4358 size_t middle = from + diff/2;
4359 left = array_setter_node(parser, array, index, value, from, middle);
4360 right = array_setter_node(parser, array, index, value, middle, afterend);
4361 return array_accessor_split(parser, array, index, middle, left, right);
4365 static ast_expression *array_field_setter_node(
4374 lex_ctx ctx = ast_ctx(array);
4376 if (from+1 == afterend) {
4377 /* set this value */
4380 ast_entfield *entfield;
4381 ast_array_index *subscript;
4383 int assignop = type_storep_instr[value->expression.vtype];
4385 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
4386 assignop = INSTR_STOREP_V;
4388 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4392 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4393 subscript->expression.vtype = TYPE_FIELD;
4395 entfield = ast_entfield_new_force(ctx,
4396 (ast_expression*)entity,
4397 (ast_expression*)subscript,
4398 (ast_expression*)subscript);
4400 ast_delete(subscript);
4404 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4406 ast_delete(entfield);
4410 block = ast_block_new(ctx);
4416 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4421 ret = ast_return_new(ctx, NULL);
4427 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4432 return (ast_expression*)block;
4434 ast_expression *left, *right;
4435 size_t diff = afterend - from;
4436 size_t middle = from + diff/2;
4437 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4438 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4439 return array_accessor_split(parser, array, index, middle, left, right);
4443 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4445 lex_ctx ctx = ast_ctx(array);
4447 if (from+1 == afterend) {
4449 ast_array_index *subscript;
4451 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4455 ret = ast_return_new(ctx, (ast_expression*)subscript);
4457 ast_delete(subscript);
4461 return (ast_expression*)ret;
4463 ast_expression *left, *right;
4464 size_t diff = afterend - from;
4465 size_t middle = from + diff/2;
4466 left = array_getter_node(parser, array, index, from, middle);
4467 right = array_getter_node(parser, array, index, middle, afterend);
4468 return array_accessor_split(parser, array, index, middle, left, right);
4472 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4474 ast_function *func = NULL;
4475 ast_value *fval = NULL;
4476 ast_block *body = NULL;
4478 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4480 parseerror(parser, "failed to create accessor function value");
4484 func = ast_function_new(ast_ctx(array), funcname, fval);
4487 parseerror(parser, "failed to create accessor function node");
4491 body = ast_block_new(ast_ctx(array));
4493 parseerror(parser, "failed to create block for array accessor");
4499 vec_push(func->blocks, body);
4502 vec_push(parser->accessors, fval);
4507 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4509 ast_value *index = NULL;
4510 ast_value *value = NULL;
4514 if (!ast_istype(array->expression.next, ast_value)) {
4515 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4519 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4521 func = fval->constval.vfunc;
4522 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4524 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4525 value = ast_value_copy((ast_value*)array->expression.next);
4527 if (!index || !value) {
4528 parseerror(parser, "failed to create locals for array accessor");
4531 (void)!ast_value_set_name(value, "value"); /* not important */
4532 vec_push(fval->expression.params, index);
4533 vec_push(fval->expression.params, value);
4535 array->setter = fval;
4538 if (index) ast_delete(index);
4539 if (value) ast_delete(value);
4545 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4547 ast_expression *root = NULL;
4548 root = array_setter_node(parser, array,
4549 array->setter->expression.params[0],
4550 array->setter->expression.params[1],
4551 0, array->expression.count);
4553 parseerror(parser, "failed to build accessor search tree");
4556 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4563 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4565 if (!parser_create_array_setter_proto(parser, array, funcname))
4567 return parser_create_array_setter_impl(parser, array);
4570 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4572 ast_expression *root = NULL;
4573 ast_value *entity = NULL;
4574 ast_value *index = NULL;
4575 ast_value *value = NULL;
4579 if (!ast_istype(array->expression.next, ast_value)) {
4580 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4584 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4586 func = fval->constval.vfunc;
4587 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4589 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4590 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4591 value = ast_value_copy((ast_value*)array->expression.next);
4592 if (!entity || !index || !value) {
4593 parseerror(parser, "failed to create locals for array accessor");
4596 (void)!ast_value_set_name(value, "value"); /* not important */
4597 vec_push(fval->expression.params, entity);
4598 vec_push(fval->expression.params, index);
4599 vec_push(fval->expression.params, value);
4601 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4603 parseerror(parser, "failed to build accessor search tree");
4607 array->setter = fval;
4608 return ast_block_add_expr(func->blocks[0], root);
4610 if (entity) ast_delete(entity);
4611 if (index) ast_delete(index);
4612 if (value) ast_delete(value);
4613 if (root) ast_delete(root);
4619 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4621 ast_value *index = NULL;
4625 /* NOTE: checking array->expression.next rather than elemtype since
4626 * for fields elemtype is a temporary fieldtype.
4628 if (!ast_istype(array->expression.next, ast_value)) {
4629 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4633 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4635 func = fval->constval.vfunc;
4636 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4638 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4641 parseerror(parser, "failed to create locals for array accessor");
4644 vec_push(fval->expression.params, index);
4646 array->getter = fval;
4649 if (index) ast_delete(index);
4655 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4657 ast_expression *root = NULL;
4659 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4661 parseerror(parser, "failed to build accessor search tree");
4664 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4671 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4673 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4675 return parser_create_array_getter_impl(parser, array);
4678 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4679 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4687 bool variadic = false;
4688 ast_value *varparam = NULL;
4689 char *argcounter = NULL;
4691 ctx = parser_ctx(parser);
4693 /* for the sake of less code we parse-in in this function */
4694 if (!parser_next(parser)) {
4695 parseerror(parser, "expected parameter list");
4701 /* parse variables until we hit a closing paren */
4702 while (parser->tok != ')') {
4704 /* there must be commas between them */
4705 if (parser->tok != ',') {
4706 parseerror(parser, "expected comma or end of parameter list");
4709 if (!parser_next(parser)) {
4710 parseerror(parser, "expected parameter");
4716 if (parser->tok == TOKEN_DOTS) {
4717 /* '...' indicates a varargs function */
4719 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4720 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4723 if (parser->tok == TOKEN_IDENT) {
4724 argcounter = util_strdup(parser_tokval(parser));
4725 if (!parser_next(parser) || parser->tok != ')') {
4726 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4733 /* for anything else just parse a typename */
4734 param = parse_typename(parser, NULL, NULL);
4737 vec_push(params, param);
4738 if (param->expression.vtype >= TYPE_VARIANT) {
4739 char tname[1024]; /* typename is reserved in C++ */
4740 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4741 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4744 /* type-restricted varargs */
4745 if (parser->tok == TOKEN_DOTS) {
4747 varparam = vec_last(params);
4749 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4750 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4753 if (parser->tok == TOKEN_IDENT) {
4754 argcounter = util_strdup(parser_tokval(parser));
4755 if (!parser_next(parser) || parser->tok != ')') {
4756 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4764 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4768 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4769 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4772 if (!parser_next(parser)) {
4773 parseerror(parser, "parse error after typename");
4777 /* now turn 'var' into a function type */
4778 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4779 fval->expression.next = (ast_expression*)var;
4781 fval->expression.flags |= AST_FLAG_VARIADIC;
4784 var->expression.params = params;
4785 var->expression.varparam = (ast_expression*)varparam;
4786 var->argcounter = argcounter;
4795 for (i = 0; i < vec_size(params); ++i)
4796 ast_delete(params[i]);
4801 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4803 ast_expression *cexp;
4804 ast_value *cval, *tmp;
4807 ctx = parser_ctx(parser);
4809 if (!parser_next(parser)) {
4811 parseerror(parser, "expected array-size");
4815 cexp = parse_expression_leave(parser, true, false, false);
4817 if (!cexp || !ast_istype(cexp, ast_value)) {
4821 parseerror(parser, "expected array-size as constant positive integer");
4824 cval = (ast_value*)cexp;
4826 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4827 tmp->expression.next = (ast_expression*)var;
4830 if (cval->expression.vtype == TYPE_INTEGER)
4831 tmp->expression.count = cval->constval.vint;
4832 else if (cval->expression.vtype == TYPE_FLOAT)
4833 tmp->expression.count = cval->constval.vfloat;
4837 parseerror(parser, "array-size must be a positive integer constant");
4842 if (parser->tok != ']') {
4844 parseerror(parser, "expected ']' after array-size");
4847 if (!parser_next(parser)) {
4849 parseerror(parser, "error after parsing array size");
4855 /* Parse a complete typename.
4856 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4857 * but when parsing variables separated by comma
4858 * 'storebase' should point to where the base-type should be kept.
4859 * The base type makes up every bit of type information which comes *before* the
4862 * The following will be parsed in its entirety:
4864 * The 'basetype' in this case is 'void()'
4865 * and if there's a comma after it, say:
4867 * then the type-information 'void()' can be stored in 'storebase'
4869 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4871 ast_value *var, *tmp;
4874 const char *name = NULL;
4875 bool isfield = false;
4876 bool wasarray = false;
4877 size_t morefields = 0;
4879 ctx = parser_ctx(parser);
4881 /* types may start with a dot */
4882 if (parser->tok == '.') {
4884 /* if we parsed a dot we need a typename now */
4885 if (!parser_next(parser)) {
4886 parseerror(parser, "expected typename for field definition");
4890 /* Further dots are handled seperately because they won't be part of the
4893 while (parser->tok == '.') {
4895 if (!parser_next(parser)) {
4896 parseerror(parser, "expected typename for field definition");
4901 if (parser->tok == TOKEN_IDENT)
4902 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4903 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4904 parseerror(parser, "expected typename");
4908 /* generate the basic type value */
4909 if (cached_typedef) {
4910 var = ast_value_copy(cached_typedef);
4911 ast_value_set_name(var, "<type(from_def)>");
4913 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4915 for (; morefields; --morefields) {
4916 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4917 tmp->expression.next = (ast_expression*)var;
4921 /* do not yet turn into a field - remember:
4922 * .void() foo; is a field too
4923 * .void()() foo; is a function
4927 if (!parser_next(parser)) {
4929 parseerror(parser, "parse error after typename");
4933 /* an opening paren now starts the parameter-list of a function
4934 * this is where original-QC has parameter lists.
4935 * We allow a single parameter list here.
4936 * Much like fteqcc we don't allow `float()() x`
4938 if (parser->tok == '(') {
4939 var = parse_parameter_list(parser, var);
4944 /* store the base if requested */
4946 *storebase = ast_value_copy(var);
4948 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4949 tmp->expression.next = (ast_expression*)*storebase;
4954 /* there may be a name now */
4955 if (parser->tok == TOKEN_IDENT) {
4956 name = util_strdup(parser_tokval(parser));
4958 if (!parser_next(parser)) {
4960 parseerror(parser, "error after variable or field declaration");
4965 /* now this may be an array */
4966 if (parser->tok == '[') {
4968 var = parse_arraysize(parser, var);
4973 /* This is the point where we can turn it into a field */
4975 /* turn it into a field if desired */
4976 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4977 tmp->expression.next = (ast_expression*)var;
4981 /* now there may be function parens again */
4982 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4983 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4984 if (parser->tok == '(' && wasarray)
4985 parseerror(parser, "arrays as part of a return type is not supported");
4986 while (parser->tok == '(') {
4987 var = parse_parameter_list(parser, var);
4995 /* finally name it */
4997 if (!ast_value_set_name(var, name)) {
4999 parseerror(parser, "internal error: failed to set name");
5002 /* free the name, ast_value_set_name duplicates */
5009 static bool parse_typedef(parser_t *parser)
5011 ast_value *typevar, *oldtype;
5012 ast_expression *old;
5014 typevar = parse_typename(parser, NULL, NULL);
5019 if ( (old = parser_find_var(parser, typevar->name)) ) {
5020 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5021 " -> `%s` has been declared here: %s:%i",
5022 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5023 ast_delete(typevar);
5027 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5028 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5029 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5030 ast_delete(typevar);
5034 vec_push(parser->_typedefs, typevar);
5035 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5037 if (parser->tok != ';') {
5038 parseerror(parser, "expected semicolon after typedef");
5041 if (!parser_next(parser)) {
5042 parseerror(parser, "parse error after typedef");
5049 static const char *cvq_to_str(int cvq) {
5051 case CV_NONE: return "none";
5052 case CV_VAR: return "`var`";
5053 case CV_CONST: return "`const`";
5054 default: return "<INVALID>";
5058 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5061 if (proto->cvq != var->cvq) {
5062 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5063 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5064 parser->tok == '='))
5066 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5067 "`%s` declared with different qualifiers: %s\n"
5068 " -> previous declaration here: %s:%i uses %s",
5069 var->name, cvq_to_str(var->cvq),
5070 ast_ctx(proto).file, ast_ctx(proto).line,
5071 cvq_to_str(proto->cvq));
5074 av = (var ->expression.flags & AST_FLAG_NORETURN);
5075 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5077 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5078 "`%s` declared with different attributes%s\n"
5079 " -> previous declaration here: %s:%i",
5080 var->name, (av ? ": noreturn" : ""),
5081 ast_ctx(proto).file, ast_ctx(proto).line,
5082 (ao ? ": noreturn" : ""));
5087 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)
5091 ast_expression *old;
5095 ast_value *basetype = NULL;
5097 bool isparam = false;
5098 bool isvector = false;
5099 bool cleanvar = true;
5100 bool wasarray = false;
5104 if (!localblock && is_static)
5105 parseerror(parser, "`static` qualifier is not supported in global scope");
5107 /* get the first complete variable */
5108 var = parse_typename(parser, &basetype, cached_typedef);
5111 ast_delete(basetype);
5119 /* Part 0: finish the type */
5120 if (parser->tok == '(') {
5121 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5122 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5123 var = parse_parameter_list(parser, var);
5129 /* we only allow 1-dimensional arrays */
5130 if (parser->tok == '[') {
5132 var = parse_arraysize(parser, var);
5138 if (parser->tok == '(' && wasarray) {
5139 parseerror(parser, "arrays as part of a return type is not supported");
5140 /* we'll still parse the type completely for now */
5142 /* for functions returning functions */
5143 while (parser->tok == '(') {
5144 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5145 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5146 var = parse_parameter_list(parser, var);
5153 var->cvq = qualifier;
5154 var->expression.flags |= qflags;
5157 * store the vstring back to var for alias and
5158 * deprecation messages.
5160 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5161 var->expression.flags & AST_FLAG_ALIAS)
5162 var->desc = vstring;
5165 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5166 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5167 * is then filled with the previous definition and the parameter-names replaced.
5169 if (!strcmp(var->name, "nil")) {
5170 if (OPTS_FLAG(UNTYPED_NIL)) {
5171 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5172 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5174 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5177 /* Deal with end_sys_ vars */
5179 if (!strcmp(var->name, "end_sys_globals")) {
5181 parser->crc_globals = vec_size(parser->globals);
5184 else if (!strcmp(var->name, "end_sys_fields")) {
5186 parser->crc_fields = vec_size(parser->fields);
5189 if (was_end && var->expression.vtype == TYPE_FIELD) {
5190 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5191 "global '%s' hint should not be a field",
5192 parser_tokval(parser)))
5199 if (!nofields && var->expression.vtype == TYPE_FIELD)
5201 /* deal with field declarations */
5202 old = parser_find_field(parser, var->name);
5204 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5205 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5214 parseerror(parser, "field `%s` already declared here: %s:%i",
5215 var->name, ast_ctx(old).file, ast_ctx(old).line);
5220 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5221 (old = parser_find_global(parser, var->name)))
5223 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5224 parseerror(parser, "field `%s` already declared here: %s:%i",
5225 var->name, ast_ctx(old).file, ast_ctx(old).line);
5232 /* deal with other globals */
5233 old = parser_find_global(parser, var->name);
5234 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
5236 /* This is a function which had a prototype */
5237 if (!ast_istype(old, ast_value)) {
5238 parseerror(parser, "internal error: prototype is not an ast_value");
5242 proto = (ast_value*)old;
5243 proto->desc = var->desc;
5244 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5245 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5247 ast_ctx(proto).file, ast_ctx(proto).line);
5251 /* we need the new parameter-names */
5252 for (i = 0; i < vec_size(proto->expression.params); ++i)
5253 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5254 if (!parser_check_qualifiers(parser, var, proto)) {
5261 proto->expression.flags |= var->expression.flags;
5269 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5270 "global `%s` already declared here: %s:%i",
5271 var->name, ast_ctx(old).file, ast_ctx(old).line))
5276 proto = (ast_value*)old;
5277 if (!ast_istype(old, ast_value)) {
5278 parseerror(parser, "internal error: not an ast_value");
5283 if (!parser_check_qualifiers(parser, var, proto)) {
5288 proto->expression.flags |= var->expression.flags;
5292 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5293 (old = parser_find_field(parser, var->name)))
5295 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5296 parseerror(parser, "global `%s` already declared here: %s:%i",
5297 var->name, ast_ctx(old).file, ast_ctx(old).line);
5304 else /* it's not a global */
5306 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5307 if (old && !isparam) {
5308 parseerror(parser, "local `%s` already declared here: %s:%i",
5309 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5313 old = parser_find_local(parser, var->name, 0, &isparam);
5314 if (old && isparam) {
5315 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5316 "local `%s` is shadowing a parameter", var->name))
5318 parseerror(parser, "local `%s` already declared here: %s:%i",
5319 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5323 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5331 /* in a noref section we simply bump the usecount */
5332 if (noref || parser->noref)
5336 * Create the global/local, and deal with vector types.
5339 if (var->expression.vtype == TYPE_VECTOR)
5341 else if (var->expression.vtype == TYPE_FIELD &&
5342 var->expression.next->expression.vtype == TYPE_VECTOR)
5346 if (!create_vector_members(var, me)) {
5353 /* deal with global variables, fields, functions */
5354 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5355 var->isfield = true;
5356 vec_push(parser->fields, (ast_expression*)var);
5357 util_htset(parser->htfields, var->name, var);
5359 for (i = 0; i < 3; ++i) {
5360 vec_push(parser->fields, (ast_expression*)me[i]);
5361 util_htset(parser->htfields, me[i]->name, me[i]);
5366 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5367 parser_addglobal(parser, var->name, (ast_expression*)var);
5369 for (i = 0; i < 3; ++i) {
5370 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5374 ast_expression *find = parser_find_global(parser, var->desc);
5377 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5381 if (var->expression.vtype != find->expression.vtype) {
5385 ast_type_to_string(find, ty1, sizeof(ty1));
5386 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5388 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5395 * add alias to aliases table and to corrector
5396 * so corrections can apply for aliases as well.
5398 util_htset(parser->aliases, var->name, find);
5401 * add to corrector so corrections can work
5402 * even for aliases too.
5405 vec_last(parser->correct_variables),
5406 &vec_last(parser->correct_variables_score),
5410 /* generate aliases for vector components */
5414 util_asprintf(&buffer[0], "%s_x", var->desc);
5415 util_asprintf(&buffer[1], "%s_y", var->desc);
5416 util_asprintf(&buffer[2], "%s_z", var->desc);
5418 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5419 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5420 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5427 * add to corrector so corrections can work
5428 * even for aliases too.
5431 vec_last(parser->correct_variables),
5432 &vec_last(parser->correct_variables_score),
5436 vec_last(parser->correct_variables),
5437 &vec_last(parser->correct_variables_score),
5441 vec_last(parser->correct_variables),
5442 &vec_last(parser->correct_variables_score),
5450 /* a static adds itself to be generated like any other global
5451 * but is added to the local namespace instead
5453 char *defname = NULL;
5454 size_t prefix_len, ln;
5456 ln = strlen(parser->function->name);
5457 vec_append(defname, ln, parser->function->name);
5459 vec_append(defname, 2, "::");
5460 /* remember the length up to here */
5461 prefix_len = vec_size(defname);
5463 /* Add it to the local scope */
5464 util_htset(vec_last(parser->variables), var->name, (void*)var);
5468 vec_last(parser->correct_variables),
5469 &vec_last(parser->correct_variables_score),
5473 /* now rename the global */
5474 ln = strlen(var->name);
5475 vec_append(defname, ln, var->name);
5476 ast_value_set_name(var, defname);
5478 /* push it to the to-be-generated globals */
5479 vec_push(parser->globals, (ast_expression*)var);
5481 /* same game for the vector members */
5483 for (i = 0; i < 3; ++i) {
5484 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5488 vec_last(parser->correct_variables),
5489 &vec_last(parser->correct_variables_score),
5493 vec_shrinkto(defname, prefix_len);
5494 ln = strlen(me[i]->name);
5495 vec_append(defname, ln, me[i]->name);
5496 ast_member_set_name(me[i], defname);
5498 vec_push(parser->globals, (ast_expression*)me[i]);
5503 vec_push(localblock->locals, var);
5504 parser_addlocal(parser, var->name, (ast_expression*)var);
5506 for (i = 0; i < 3; ++i) {
5507 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5508 ast_block_collect(localblock, (ast_expression*)me[i]);
5514 me[0] = me[1] = me[2] = NULL;
5519 if (var->expression.vtype == TYPE_ARRAY) {
5521 snprintf(name, sizeof(name), "%s##SET", var->name);
5522 if (!parser_create_array_setter(parser, var, name))
5524 snprintf(name, sizeof(name), "%s##GET", var->name);
5525 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5528 else if (!localblock && !nofields &&
5529 var->expression.vtype == TYPE_FIELD &&
5530 var->expression.next->expression.vtype == TYPE_ARRAY)
5533 ast_expression *telem;
5535 ast_value *array = (ast_value*)var->expression.next;
5537 if (!ast_istype(var->expression.next, ast_value)) {
5538 parseerror(parser, "internal error: field element type must be an ast_value");
5542 snprintf(name, sizeof(name), "%s##SETF", var->name);
5543 if (!parser_create_array_field_setter(parser, array, name))
5546 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5547 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5548 tfield->expression.next = telem;
5549 snprintf(name, sizeof(name), "%s##GETFP", var->name);
5550 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5558 if (parser->tok == ';') {
5559 ast_delete(basetype);
5560 if (!parser_next(parser)) {
5561 parseerror(parser, "error after variable declaration");
5567 if (parser->tok == ',')
5571 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5574 parseerror(parser, "missing comma or semicolon while parsing variables");
5578 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5579 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5580 "initializing expression turns variable `%s` into a constant in this standard",
5587 if (parser->tok != '{') {
5588 if (parser->tok != '=') {
5589 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5593 if (!parser_next(parser)) {
5594 parseerror(parser, "error parsing initializer");
5598 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5599 parseerror(parser, "expected '=' before function body in this standard");
5602 if (parser->tok == '#') {
5603 ast_function *func = NULL;
5606 parseerror(parser, "cannot declare builtins within functions");
5609 if (var->expression.vtype != TYPE_FUNCTION) {
5610 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5613 if (!parser_next(parser)) {
5614 parseerror(parser, "expected builtin number");
5617 if (parser->tok != TOKEN_INTCONST) {
5618 parseerror(parser, "builtin number must be an integer constant");
5621 if (parser_token(parser)->constval.i < 0) {
5622 parseerror(parser, "builtin number must be an integer greater than zero");
5626 if (var->hasvalue) {
5627 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5628 "builtin `%s` has already been defined\n"
5629 " -> previous declaration here: %s:%i",
5630 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5634 func = ast_function_new(ast_ctx(var), var->name, var);
5636 parseerror(parser, "failed to allocate function for `%s`", var->name);
5639 vec_push(parser->functions, func);
5641 func->builtin = -parser_token(parser)->constval.i-1;
5644 if (!parser_next(parser)) {
5645 parseerror(parser, "expected comma or semicolon");
5647 ast_function_delete(func);
5648 var->constval.vfunc = NULL;
5652 else if (parser->tok == '{' || parser->tok == '[')
5655 parseerror(parser, "cannot declare functions within functions");
5660 ast_ctx(proto) = parser_ctx(parser);
5662 if (!parse_function_body(parser, var))
5664 ast_delete(basetype);
5665 for (i = 0; i < vec_size(parser->gotos); ++i)
5666 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5667 vec_free(parser->gotos);
5668 vec_free(parser->labels);
5671 ast_expression *cexp;
5674 cexp = parse_expression_leave(parser, true, false, false);
5679 cval = (ast_value*)cexp;
5680 if (cval != parser->nil &&
5681 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5684 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5688 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5689 qualifier != CV_VAR)
5691 var->cvq = CV_CONST;
5693 if (cval == parser->nil)
5694 var->expression.flags |= AST_FLAG_INITIALIZED;
5697 var->hasvalue = true;
5698 if (cval->expression.vtype == TYPE_STRING)
5699 var->constval.vstring = parser_strdup(cval->constval.vstring);
5700 else if (cval->expression.vtype == TYPE_FIELD)
5701 var->constval.vfield = cval;
5703 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5709 shunt sy = { NULL, NULL, NULL, NULL };
5712 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5713 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5714 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5715 if (!parser_sy_apply_operator(parser, &sy))
5718 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5719 parseerror(parser, "internal error: leaked operands");
5720 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
5730 if (parser->tok == ',') {
5731 if (!parser_next(parser)) {
5732 parseerror(parser, "expected another variable");
5736 if (parser->tok != TOKEN_IDENT) {
5737 parseerror(parser, "expected another variable");
5740 var = ast_value_copy(basetype);
5742 ast_value_set_name(var, parser_tokval(parser));
5743 if (!parser_next(parser)) {
5744 parseerror(parser, "error parsing variable declaration");
5750 if (parser->tok != ';') {
5751 parseerror(parser, "missing semicolon after variables");
5755 if (!parser_next(parser)) {
5756 parseerror(parser, "parse error after variable declaration");
5760 ast_delete(basetype);
5764 if (cleanvar && var)
5766 ast_delete(basetype);
5770 ast_delete(basetype);
5771 if (cleanvar && var)
5773 if (me[0]) ast_member_delete(me[0]);
5774 if (me[1]) ast_member_delete(me[1]);
5775 if (me[2]) ast_member_delete(me[2]);
5779 static bool parser_global_statement(parser_t *parser)
5783 bool is_static = false;
5784 uint32_t qflags = 0;
5785 ast_value *istype = NULL;
5786 char *vstring = NULL;
5788 if (parser->tok == TOKEN_IDENT)
5789 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
5791 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
5793 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
5795 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
5797 if (cvq == CV_WRONG)
5799 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
5801 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
5803 return parse_enum(parser);
5805 else if (parser->tok == TOKEN_KEYWORD)
5807 if (!strcmp(parser_tokval(parser), "typedef")) {
5808 if (!parser_next(parser)) {
5809 parseerror(parser, "expected type definition after 'typedef'");
5812 return parse_typedef(parser);
5814 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
5817 else if (parser->tok == '#')
5819 return parse_pragma(parser);
5821 else if (parser->tok == '$')
5823 if (!parser_next(parser)) {
5824 parseerror(parser, "parse error");
5830 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
5836 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
5838 return util_crc16(old, str, strlen(str));
5841 static void progdefs_crc_file(const char *str)
5843 /* write to progdefs.h here */
5847 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
5849 old = progdefs_crc_sum(old, str);
5850 progdefs_crc_file(str);
5854 static void generate_checksum(parser_t *parser)
5856 uint16_t crc = 0xFFFF;
5860 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
5861 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
5863 progdefs_crc_file("\tint\tpad;\n");
5864 progdefs_crc_file("\tint\tofs_return[3];\n");
5865 progdefs_crc_file("\tint\tofs_parm0[3];\n");
5866 progdefs_crc_file("\tint\tofs_parm1[3];\n");
5867 progdefs_crc_file("\tint\tofs_parm2[3];\n");
5868 progdefs_crc_file("\tint\tofs_parm3[3];\n");
5869 progdefs_crc_file("\tint\tofs_parm4[3];\n");
5870 progdefs_crc_file("\tint\tofs_parm5[3];\n");
5871 progdefs_crc_file("\tint\tofs_parm6[3];\n");
5872 progdefs_crc_file("\tint\tofs_parm7[3];\n");
5874 for (i = 0; i < parser->crc_globals; ++i) {
5875 if (!ast_istype(parser->globals[i], ast_value))
5877 value = (ast_value*)(parser->globals[i]);
5878 switch (value->expression.vtype) {
5879 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5880 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5881 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5882 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5884 crc = progdefs_crc_both(crc, "\tint\t");
5887 crc = progdefs_crc_both(crc, value->name);
5888 crc = progdefs_crc_both(crc, ";\n");
5890 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
5891 for (i = 0; i < parser->crc_fields; ++i) {
5892 if (!ast_istype(parser->fields[i], ast_value))
5894 value = (ast_value*)(parser->fields[i]);
5895 switch (value->expression.next->expression.vtype) {
5896 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
5897 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
5898 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
5899 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
5901 crc = progdefs_crc_both(crc, "\tint\t");
5904 crc = progdefs_crc_both(crc, value->name);
5905 crc = progdefs_crc_both(crc, ";\n");
5907 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
5912 static parser_t *parser;
5919 parser = (parser_t*)mem_a(sizeof(parser_t));
5923 memset(parser, 0, sizeof(*parser));
5925 for (i = 0; i < operator_count; ++i) {
5926 if (operators[i].id == opid1('=')) {
5927 parser->assign_op = operators+i;
5931 if (!parser->assign_op) {
5932 printf("internal error: initializing parser: failed to find assign operator\n");
5937 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
5938 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
5939 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
5940 vec_push(parser->_blocktypedefs, 0);
5942 parser->aliases = util_htnew(PARSER_HT_SIZE);
5945 vec_push(parser->correct_variables, correct_trie_new());
5946 vec_push(parser->correct_variables_score, NULL);
5948 empty_ctx.file = "<internal>";
5950 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
5951 parser->nil->cvq = CV_CONST;
5952 if (OPTS_FLAG(UNTYPED_NIL))
5953 util_htset(parser->htglobals, "nil", (void*)parser->nil);
5955 parser->max_param_count = 1;
5957 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
5958 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
5959 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
5961 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
5962 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
5963 parser->reserved_version->cvq = CV_CONST;
5964 parser->reserved_version->hasvalue = true;
5965 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
5966 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
5968 parser->reserved_version = NULL;
5973 bool parser_compile()
5975 /* initial lexer/parser state */
5976 parser->lex->flags.noops = true;
5978 if (parser_next(parser))
5980 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
5982 if (!parser_global_statement(parser)) {
5983 if (parser->tok == TOKEN_EOF)
5984 parseerror(parser, "unexpected eof");
5985 else if (compile_errors)
5986 parseerror(parser, "there have been errors, bailing out");
5987 lex_close(parser->lex);
5993 parseerror(parser, "parse error");
5994 lex_close(parser->lex);
5999 lex_close(parser->lex);
6002 return !compile_errors;
6005 bool parser_compile_file(const char *filename)
6007 parser->lex = lex_open(filename);
6009 con_err("failed to open file \"%s\"\n", filename);
6012 return parser_compile();
6015 bool parser_compile_string(const char *name, const char *str, size_t len)
6017 parser->lex = lex_open_string(str, len, name);
6019 con_err("failed to create lexer for string \"%s\"\n", name);
6022 return parser_compile();
6025 void parser_cleanup()
6028 for (i = 0; i < vec_size(parser->accessors); ++i) {
6029 ast_delete(parser->accessors[i]->constval.vfunc);
6030 parser->accessors[i]->constval.vfunc = NULL;
6031 ast_delete(parser->accessors[i]);
6033 for (i = 0; i < vec_size(parser->functions); ++i) {
6034 ast_delete(parser->functions[i]);
6036 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6037 ast_delete(parser->imm_vector[i]);
6039 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6040 ast_delete(parser->imm_string[i]);
6042 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6043 ast_delete(parser->imm_float[i]);
6045 for (i = 0; i < vec_size(parser->fields); ++i) {
6046 ast_delete(parser->fields[i]);
6048 for (i = 0; i < vec_size(parser->globals); ++i) {
6049 ast_delete(parser->globals[i]);
6051 vec_free(parser->accessors);
6052 vec_free(parser->functions);
6053 vec_free(parser->imm_vector);
6054 vec_free(parser->imm_string);
6055 vec_free(parser->imm_float);
6056 vec_free(parser->globals);
6057 vec_free(parser->fields);
6059 for (i = 0; i < vec_size(parser->variables); ++i)
6060 util_htdel(parser->variables[i]);
6061 vec_free(parser->variables);
6062 vec_free(parser->_blocklocals);
6063 vec_free(parser->_locals);
6066 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6067 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6069 vec_free(parser->correct_variables);
6070 vec_free(parser->correct_variables_score);
6073 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6074 ast_delete(parser->_typedefs[i]);
6075 vec_free(parser->_typedefs);
6076 for (i = 0; i < vec_size(parser->typedefs); ++i)
6077 util_htdel(parser->typedefs[i]);
6078 vec_free(parser->typedefs);
6079 vec_free(parser->_blocktypedefs);
6081 vec_free(parser->_block_ctx);
6083 vec_free(parser->labels);
6084 vec_free(parser->gotos);
6085 vec_free(parser->breaks);
6086 vec_free(parser->continues);
6088 ast_value_delete(parser->nil);
6090 ast_value_delete(parser->const_vec[0]);
6091 ast_value_delete(parser->const_vec[1]);
6092 ast_value_delete(parser->const_vec[2]);
6094 util_htdel(parser->aliases);
6096 intrin_intrinsics_destroy();
6101 bool parser_finish(const char *output)
6107 if (compile_errors) {
6108 con_out("*** there were compile errors\n");
6112 ir = ir_builder_new("gmqcc_out");
6114 con_out("failed to allocate builder\n");
6118 for (i = 0; i < vec_size(parser->fields); ++i) {
6121 if (!ast_istype(parser->fields[i], ast_value))
6123 field = (ast_value*)parser->fields[i];
6124 hasvalue = field->hasvalue;
6125 field->hasvalue = false;
6126 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6127 con_out("failed to generate field %s\n", field->name);
6128 ir_builder_delete(ir);
6133 ast_expression *subtype;
6134 field->hasvalue = true;
6135 subtype = field->expression.next;
6136 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
6137 if (subtype->expression.vtype == TYPE_FIELD)
6138 ifld->fieldtype = subtype->expression.next->expression.vtype;
6139 else if (subtype->expression.vtype == TYPE_FUNCTION)
6140 ifld->outtype = subtype->expression.next->expression.vtype;
6141 (void)!ir_value_set_field(field->ir_v, ifld);
6144 for (i = 0; i < vec_size(parser->globals); ++i) {
6146 if (!ast_istype(parser->globals[i], ast_value))
6148 asvalue = (ast_value*)(parser->globals[i]);
6149 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6150 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6151 "unused global: `%s`", asvalue->name);
6153 if (!ast_global_codegen(asvalue, ir, false)) {
6154 con_out("failed to generate global %s\n", asvalue->name);
6155 ir_builder_delete(ir);
6159 /* Build function vararg accessor ast tree now before generating
6160 * immediates, because the accessors may add new immediates
6162 for (i = 0; i < vec_size(parser->functions); ++i) {
6163 ast_function *f = parser->functions[i];
6165 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6166 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6167 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6168 con_out("failed to generate vararg setter for %s\n", f->name);
6169 ir_builder_delete(ir);
6172 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6173 con_out("failed to generate vararg getter for %s\n", f->name);
6174 ir_builder_delete(ir);
6178 ast_delete(f->varargs);
6183 /* Now we can generate immediates */
6184 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6185 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6186 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6187 ir_builder_delete(ir);
6191 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6192 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6193 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6194 ir_builder_delete(ir);
6198 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6199 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6200 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6201 ir_builder_delete(ir);
6205 for (i = 0; i < vec_size(parser->globals); ++i) {
6207 if (!ast_istype(parser->globals[i], ast_value))
6209 asvalue = (ast_value*)(parser->globals[i]);
6210 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6212 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6213 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6214 "uninitialized constant: `%s`",
6216 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6217 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6218 "uninitialized global: `%s`",
6221 if (!ast_generate_accessors(asvalue, ir)) {
6222 ir_builder_delete(ir);
6226 for (i = 0; i < vec_size(parser->fields); ++i) {
6228 asvalue = (ast_value*)(parser->fields[i]->expression.next);
6230 if (!ast_istype((ast_expression*)asvalue, ast_value))
6232 if (asvalue->expression.vtype != TYPE_ARRAY)
6234 if (!ast_generate_accessors(asvalue, ir)) {
6235 ir_builder_delete(ir);
6239 if (parser->reserved_version &&
6240 !ast_global_codegen(parser->reserved_version, ir, false))
6242 con_out("failed to generate reserved::version");
6243 ir_builder_delete(ir);
6246 for (i = 0; i < vec_size(parser->functions); ++i) {
6247 ast_function *f = parser->functions[i];
6248 if (!ast_function_codegen(f, ir)) {
6249 con_out("failed to generate function %s\n", f->name);
6250 ir_builder_delete(ir);
6254 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6255 ir_builder_dump(ir, con_out);
6256 for (i = 0; i < vec_size(parser->functions); ++i) {
6257 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6258 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6259 ir_builder_delete(ir);
6264 if (compile_Werrors) {
6265 con_out("*** there were warnings treated as errors\n");
6266 compile_show_werrors();
6271 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6272 ir_builder_dump(ir, con_out);
6274 generate_checksum(parser);
6276 if (!ir_builder_generate(ir, output)) {
6277 con_out("*** failed to generate output file\n");
6278 ir_builder_delete(ir);
6283 ir_builder_delete(ir);