2 * Copyright (C) 2012, 2013
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of
7 * this software and associated documentation files (the "Software"), to deal in
8 * the Software without restriction, including without limitation the rights to
9 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10 * of the Software, and to permit persons to whom the Software is furnished to do
11 * so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 /* beginning of locals */
32 #define PARSER_HT_LOCALS 2
34 #define PARSER_HT_SIZE 128
35 #define TYPEDEF_HT_SIZE 16
37 typedef struct parser_s {
43 ast_expression **globals;
44 ast_expression **fields;
45 ast_function **functions;
46 ast_value **imm_float;
47 ast_value **imm_string;
48 ast_value **imm_vector;
53 /* must be deleted first, they reference immediates and values */
54 ast_value **accessors;
56 ast_value *imm_float_zero;
57 ast_value *imm_float_one;
58 ast_value *imm_float_neg_one;
60 ast_value *imm_vector_zero;
63 ast_value *reserved_version;
68 ast_function *function;
71 /* All the labels the function defined...
72 * Should they be in ast_function instead?
77 const char **continues;
79 /* A list of hashtables for each scope */
85 /* same as above but for the spelling corrector */
86 correct_trie_t **correct_variables;
87 size_t ***correct_variables_score; /* vector of vector of size_t* */
89 /* not to be used directly, we use the hash table */
90 ast_expression **_locals;
92 ast_value **_typedefs;
93 size_t *_blocktypedefs;
96 /* we store the '=' operator info */
97 const oper_info *assign_op;
100 ast_value *const_vec[3];
105 /* collected information */
106 size_t max_param_count;
112 static ast_expression * const intrinsic_debug_typestring = (ast_expression*)0x1;
114 static void parser_enterblock(parser_t *parser);
115 static bool parser_leaveblock(parser_t *parser);
116 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
117 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e);
118 static bool parse_typedef(parser_t *parser);
119 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);
120 static ast_block* parse_block(parser_t *parser);
121 static bool parse_block_into(parser_t *parser, ast_block *block);
122 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
123 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
124 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels);
125 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels);
126 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname);
127 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname);
128 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
130 static void parseerror(parser_t *parser, const char *fmt, ...)
134 vcompile_error(parser->lex->tok.ctx, fmt, ap);
138 /* returns true if it counts as an error */
139 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
144 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
149 /**********************************************************************
150 * some maths used for constant folding
153 vector vec3_add(vector a, vector b)
162 vector vec3_sub(vector a, vector b)
171 qcfloat vec3_mulvv(vector a, vector b)
173 return (a.x * b.x + a.y * b.y + a.z * b.z);
176 vector vec3_mulvf(vector a, float b)
185 /**********************************************************************
189 static bool parser_next(parser_t *parser)
191 /* lex_do kills the previous token */
192 parser->tok = lex_do(parser->lex);
193 if (parser->tok == TOKEN_EOF)
195 if (parser->tok >= TOKEN_ERROR) {
196 parseerror(parser, "lex error");
202 #define parser_tokval(p) ((p)->lex->tok.value)
203 #define parser_token(p) (&((p)->lex->tok))
204 #define parser_ctx(p) ((p)->lex->tok.ctx)
206 static ast_value* parser_const_float(parser_t *parser, double d)
211 for (i = 0; i < vec_size(parser->imm_float); ++i) {
212 const double compare = parser->imm_float[i]->constval.vfloat;
213 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
214 return parser->imm_float[i];
217 ctx = parser_ctx(parser);
219 memset(&ctx, 0, sizeof(ctx));
221 out = ast_value_new(ctx, "#IMMEDIATE", TYPE_FLOAT);
223 out->hasvalue = true;
225 out->constval.vfloat = d;
226 vec_push(parser->imm_float, out);
230 static ast_value* parser_const_float_0(parser_t *parser)
232 if (!parser->imm_float_zero)
233 parser->imm_float_zero = parser_const_float(parser, 0);
234 return parser->imm_float_zero;
237 static ast_value* parser_const_float_neg1(parser_t *parser) {
238 if (!parser->imm_float_neg_one)
239 parser->imm_float_neg_one = parser_const_float(parser, -1);
240 return parser->imm_float_neg_one;
243 static ast_value* parser_const_float_1(parser_t *parser)
245 if (!parser->imm_float_one)
246 parser->imm_float_one = parser_const_float(parser, 1);
247 return parser->imm_float_one;
250 static char *parser_strdup(const char *str)
253 /* actually dup empty strings */
254 char *out = (char*)mem_a(1);
258 return util_strdup(str);
261 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
263 size_t hash = util_hthash(parser->ht_imm_string, str);
265 if ( (out = (ast_value*)util_htgeth(parser->ht_imm_string, str, hash)) ) {
266 if (dotranslate && out->name[0] == '#') {
268 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
269 ast_value_set_name(out, name);
270 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
275 for (i = 0; i < vec_size(parser->imm_string); ++i) {
276 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
277 return parser->imm_string[i];
282 util_snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
283 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
284 out->expression.flags |= AST_FLAG_INCLUDE_DEF;
286 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
288 out->hasvalue = true;
290 out->constval.vstring = parser_strdup(str);
291 vec_push(parser->imm_string, out);
292 util_htseth(parser->ht_imm_string, str, hash, out);
296 static ast_value* parser_const_vector(parser_t *parser, vector v)
300 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
301 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
302 return parser->imm_vector[i];
304 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
306 out->hasvalue = true;
308 out->constval.vvec = v;
309 vec_push(parser->imm_vector, out);
313 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
319 return parser_const_vector(parser, v);
322 static ast_value* parser_const_vector_0(parser_t *parser)
324 if (!parser->imm_vector_zero)
325 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
326 return parser->imm_vector_zero;
329 static ast_expression* parser_find_field(parser_t *parser, const char *name)
331 return ( ast_expression*)util_htget(parser->htfields, name);
334 static ast_expression* parser_find_label(parser_t *parser, const char *name)
337 for(i = 0; i < vec_size(parser->labels); i++)
338 if (!strcmp(parser->labels[i]->name, name))
339 return (ast_expression*)parser->labels[i];
343 static ast_expression* parser_find_global(parser_t *parser, const char *name)
345 ast_expression *var = (ast_expression*)util_htget(parser->aliases, parser_tokval(parser));
348 return (ast_expression*)util_htget(parser->htglobals, name);
351 static ast_expression* parser_find_param(parser_t *parser, const char *name)
355 if (!parser->function)
357 fun = parser->function->vtype;
358 for (i = 0; i < vec_size(fun->expression.params); ++i) {
359 if (!strcmp(fun->expression.params[i]->name, name))
360 return (ast_expression*)(fun->expression.params[i]);
365 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
370 hash = util_hthash(parser->htglobals, name);
373 for (i = vec_size(parser->variables); i > upto;) {
375 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
379 return parser_find_param(parser, name);
382 static ast_expression* parser_find_var(parser_t *parser, const char *name)
386 v = parser_find_local(parser, name, 0, &dummy);
387 if (!v) v = parser_find_global(parser, name);
391 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
395 hash = util_hthash(parser->typedefs[0], name);
397 for (i = vec_size(parser->typedefs); i > upto;) {
399 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
405 /* include intrinsics */
410 size_t etype; /* 0 = expression, others are operators */
414 ast_block *block; /* for commas and function calls */
433 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
444 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
448 e.out = (ast_expression*)v;
455 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
457 e.etype = 1 + (op - operators);
466 static sy_elem syparen(lex_ctx ctx, size_t off) {
477 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
478 * so we need to rotate it to become ent.(foo[n]).
480 static bool rotate_entfield_array_index_nodes(ast_expression **out)
482 ast_array_index *index, *oldindex;
483 ast_entfield *entfield;
487 ast_expression *entity;
489 lex_ctx ctx = ast_ctx(*out);
491 if (!ast_istype(*out, ast_array_index))
493 index = (ast_array_index*)*out;
495 if (!ast_istype(index->array, ast_entfield))
497 entfield = (ast_entfield*)index->array;
499 if (!ast_istype(entfield->field, ast_value))
501 field = (ast_value*)entfield->field;
504 entity = entfield->entity;
508 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
509 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
510 *out = (ast_expression*)entfield;
512 oldindex->array = NULL;
513 oldindex->index = NULL;
514 ast_delete(oldindex);
519 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
521 switch (v->expression.vtype) {
523 return !!v->constval.vfloat;
525 return !!v->constval.vint;
527 if (OPTS_FLAG(CORRECT_LOGIC))
528 return v->constval.vvec.x &&
529 v->constval.vvec.y &&
532 return !!(v->constval.vvec.x);
534 if (!v->constval.vstring)
536 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
538 return !!v->constval.vstring[0];
540 compile_error(ctx, "internal error: immediate_is_true on invalid type");
541 return !!v->constval.vfunc;
545 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
549 ast_expression *out = NULL;
550 ast_expression *exprs[3];
551 ast_block *blocks[3];
552 ast_value *asvalue[3];
553 ast_binstore *asbinstore;
554 size_t i, assignop, addop, subop;
555 qcint generated_op = 0;
560 if (!vec_size(sy->ops)) {
561 parseerror(parser, "internal error: missing operator");
565 if (vec_last(sy->ops).isparen) {
566 parseerror(parser, "unmatched parenthesis");
570 op = &operators[vec_last(sy->ops).etype - 1];
571 ctx = vec_last(sy->ops).ctx;
573 if (vec_size(sy->out) < op->operands) {
574 compile_error(ctx, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
575 op->op, (int)op->id);
579 vec_shrinkby(sy->ops, 1);
581 /* op(:?) has no input and no output */
585 vec_shrinkby(sy->out, op->operands);
586 for (i = 0; i < op->operands; ++i) {
587 exprs[i] = sy->out[vec_size(sy->out)+i].out;
588 blocks[i] = sy->out[vec_size(sy->out)+i].block;
589 asvalue[i] = (ast_value*)exprs[i];
591 if (exprs[i]->vtype == TYPE_NOEXPR &&
592 !(i != 0 && op->id == opid2('?',':')) &&
593 !(i == 1 && op->id == opid1('.')))
595 if (ast_istype(exprs[i], ast_label))
596 compile_error(ast_ctx(exprs[i]), "expected expression, got an unknown identifier");
598 compile_error(ast_ctx(exprs[i]), "not an expression");
599 (void)!compile_warning(ast_ctx(exprs[i]), WARN_DEBUG, "expression %u\n", (unsigned int)i);
603 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
604 compile_error(ctx, "internal error: operator cannot be applied on empty blocks");
608 #define NotSameType(T) \
609 (exprs[0]->vtype != exprs[1]->vtype || \
610 exprs[0]->vtype != T)
611 #define CanConstFold1(A) \
612 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
613 (A)->vtype != TYPE_FUNCTION)
614 #define CanConstFold(A, B) \
615 (CanConstFold1(A) && CanConstFold1(B))
616 #define ConstV(i) (asvalue[(i)]->constval.vvec)
617 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
618 #define ConstS(i) (asvalue[(i)]->constval.vstring)
622 compile_error(ctx, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
626 if (exprs[0]->vtype == TYPE_VECTOR &&
627 exprs[1]->vtype == TYPE_NOEXPR)
629 if (exprs[1] == (ast_expression*)parser->const_vec[0])
630 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
631 else if (exprs[1] == (ast_expression*)parser->const_vec[1])
632 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
633 else if (exprs[1] == (ast_expression*)parser->const_vec[2])
634 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
636 compile_error(ctx, "access to invalid vector component");
640 else if (exprs[0]->vtype == TYPE_ENTITY) {
641 if (exprs[1]->vtype != TYPE_FIELD) {
642 compile_error(ast_ctx(exprs[1]), "type error: right hand of member-operand should be an entity-field");
645 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
647 else if (exprs[0]->vtype == TYPE_VECTOR) {
648 compile_error(ast_ctx(exprs[1]), "vectors cannot be accessed this way");
652 compile_error(ast_ctx(exprs[1]), "type error: member-of operator on something that is not an entity or vector");
658 if (exprs[0]->vtype != TYPE_ARRAY &&
659 !(exprs[0]->vtype == TYPE_FIELD &&
660 exprs[0]->next->vtype == TYPE_ARRAY))
662 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
663 compile_error(ast_ctx(exprs[0]), "cannot index value of type %s", ty1);
666 if (exprs[1]->vtype != TYPE_FLOAT) {
667 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
668 compile_error(ast_ctx(exprs[1]), "index must be of type float, not %s", ty1);
671 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
672 if (rotate_entfield_array_index_nodes(&out))
675 /* This is not broken in fteqcc anymore */
676 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
677 /* this error doesn't need to make us bail out */
678 (void)!parsewarning(parser, WARN_EXTENSIONS,
679 "accessing array-field members of an entity without parenthesis\n"
680 " -> this is an extension from -std=gmqcc");
687 if (vec_size(sy->paren) && vec_last(sy->paren) == PAREN_FUNC) {
688 vec_push(sy->out, syexp(ctx, exprs[0]));
689 vec_push(sy->out, syexp(ctx, exprs[1]));
690 vec_last(sy->argc)++;
694 if (!ast_block_add_expr(blocks[0], exprs[1]))
697 blocks[0] = ast_block_new(ctx);
698 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
699 !ast_block_add_expr(blocks[0], exprs[1]))
704 ast_block_set_type(blocks[0], exprs[1]);
706 vec_push(sy->out, syblock(ctx, blocks[0]));
713 switch (exprs[0]->vtype) {
715 if (CanConstFold1(exprs[0]))
716 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
718 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
719 (ast_expression*)parser_const_float_0(parser),
723 if (CanConstFold1(exprs[0]))
724 out = (ast_expression*)parser_const_vector_f(parser,
725 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
727 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
728 (ast_expression*)parser_const_vector_0(parser),
732 compile_error(ctx, "invalid types used in expression: cannot negate type %s",
733 type_name[exprs[0]->vtype]);
739 switch (exprs[0]->vtype) {
741 if (CanConstFold1(exprs[0]))
742 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
744 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
747 if (CanConstFold1(exprs[0]))
748 out = (ast_expression*)parser_const_float(parser,
749 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
751 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
754 if (CanConstFold1(exprs[0])) {
755 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
756 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
758 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
760 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
761 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
763 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
766 /* we don't constant-fold NOT for these types */
768 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
771 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
774 compile_error(ctx, "invalid types used in expression: cannot logically negate type %s",
775 type_name[exprs[0]->vtype]);
781 if (exprs[0]->vtype != exprs[1]->vtype ||
782 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
784 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
785 type_name[exprs[0]->vtype],
786 type_name[exprs[1]->vtype]);
789 switch (exprs[0]->vtype) {
791 if (CanConstFold(exprs[0], exprs[1]))
793 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
796 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
799 if (CanConstFold(exprs[0], exprs[1]))
800 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
802 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
805 compile_error(ctx, "invalid types used in expression: cannot add type %s and %s",
806 type_name[exprs[0]->vtype],
807 type_name[exprs[1]->vtype]);
812 if (exprs[0]->vtype != exprs[1]->vtype ||
813 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
815 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
816 type_name[exprs[1]->vtype],
817 type_name[exprs[0]->vtype]);
820 switch (exprs[0]->vtype) {
822 if (CanConstFold(exprs[0], exprs[1]))
823 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
825 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
828 if (CanConstFold(exprs[0], exprs[1]))
829 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
831 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
834 compile_error(ctx, "invalid types used in expression: cannot subtract type %s from %s",
835 type_name[exprs[1]->vtype],
836 type_name[exprs[0]->vtype]);
841 if (exprs[0]->vtype != exprs[1]->vtype &&
842 !(exprs[0]->vtype == TYPE_VECTOR &&
843 exprs[1]->vtype == TYPE_FLOAT) &&
844 !(exprs[1]->vtype == TYPE_VECTOR &&
845 exprs[0]->vtype == TYPE_FLOAT)
848 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
849 type_name[exprs[1]->vtype],
850 type_name[exprs[0]->vtype]);
853 switch (exprs[0]->vtype) {
855 if (exprs[1]->vtype == TYPE_VECTOR)
857 if (CanConstFold(exprs[0], exprs[1]))
858 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
860 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
864 if (CanConstFold(exprs[0], exprs[1]))
865 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
867 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
871 if (exprs[1]->vtype == TYPE_FLOAT)
873 if (CanConstFold(exprs[0], exprs[1]))
874 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
876 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
880 if (CanConstFold(exprs[0], exprs[1]))
881 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
882 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[0])) {
883 vector vec = ConstV(0);
884 if (!vec.y && !vec.z) { /* 'n 0 0' * v */
885 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
886 out = (ast_expression*)ast_member_new(ctx, exprs[1], 0, NULL);
887 out->node.keep = false;
888 ((ast_member*)out)->rvalue = true;
890 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.x), out);
892 else if (!vec.x && !vec.z) { /* '0 n 0' * v */
893 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
894 out = (ast_expression*)ast_member_new(ctx, exprs[1], 1, NULL);
895 out->node.keep = false;
896 ((ast_member*)out)->rvalue = true;
898 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.y), out);
900 else if (!vec.x && !vec.y) { /* '0 n 0' * v */
901 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
902 out = (ast_expression*)ast_member_new(ctx, exprs[1], 2, NULL);
903 out->node.keep = false;
904 ((ast_member*)out)->rvalue = true;
906 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, (ast_expression*)parser_const_float(parser, vec.z), out);
909 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
911 else if (OPTS_OPTIMIZATION(OPTIM_VECTOR_COMPONENTS) && CanConstFold1(exprs[1])) {
912 vector vec = ConstV(1);
913 if (!vec.y && !vec.z) { /* v * 'n 0 0' */
914 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
915 out = (ast_expression*)ast_member_new(ctx, exprs[0], 0, NULL);
916 out->node.keep = false;
917 ((ast_member*)out)->rvalue = true;
919 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.x));
921 else if (!vec.x && !vec.z) { /* v * '0 n 0' */
922 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
923 out = (ast_expression*)ast_member_new(ctx, exprs[0], 1, NULL);
924 out->node.keep = false;
925 ((ast_member*)out)->rvalue = true;
927 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.y));
929 else if (!vec.x && !vec.y) { /* v * '0 n 0' */
930 ++opts_optimizationcount[OPTIM_VECTOR_COMPONENTS];
931 out = (ast_expression*)ast_member_new(ctx, exprs[0], 2, NULL);
932 out->node.keep = false;
933 ((ast_member*)out)->rvalue = true;
935 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, out, (ast_expression*)parser_const_float(parser, vec.z));
938 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
941 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
945 compile_error(ctx, "invalid types used in expression: cannot multiply types %s and %s",
946 type_name[exprs[1]->vtype],
947 type_name[exprs[0]->vtype]);
952 if (exprs[1]->vtype != TYPE_FLOAT) {
953 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
954 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
955 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
958 if (exprs[0]->vtype == TYPE_FLOAT) {
959 if (CanConstFold(exprs[0], exprs[1]))
960 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
962 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
964 else if (exprs[0]->vtype == TYPE_VECTOR) {
965 if (CanConstFold(exprs[0], exprs[1]))
966 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), 1.0/ConstF(1)));
968 if (CanConstFold1(exprs[1])) {
969 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
971 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
972 (ast_expression*)parser_const_float_1(parser),
976 compile_error(ctx, "internal error: failed to generate division");
979 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], out);
984 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
985 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
986 compile_error(ctx, "invalid types used in expression: cannot divide tyeps %s and %s", ty1, ty2);
992 if (NotSameType(TYPE_FLOAT)) {
993 compile_error(ctx, "invalid types used in expression: cannot perform modulo operation between types %s and %s",
994 type_name[exprs[0]->vtype],
995 type_name[exprs[1]->vtype]);
998 if (CanConstFold(exprs[0], exprs[1])) {
999 out = (ast_expression*)parser_const_float(parser,
1000 (float)(((qcint)ConstF(0)) % ((qcint)ConstF(1))));
1002 /* generate a call to __builtin_mod */
1003 ast_expression *mod = intrin_func(parser, "mod");
1004 ast_call *call = NULL;
1005 if (!mod) return false; /* can return null for missing floor */
1007 call = ast_call_new(parser_ctx(parser), mod);
1008 vec_push(call->params, exprs[0]);
1009 vec_push(call->params, exprs[1]);
1011 out = (ast_expression*)call;
1015 case opid2('%','='):
1016 compile_error(ctx, "%= is unimplemented");
1021 if (NotSameType(TYPE_FLOAT)) {
1022 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1023 type_name[exprs[0]->vtype],
1024 type_name[exprs[1]->vtype]);
1027 if (CanConstFold(exprs[0], exprs[1]))
1028 out = (ast_expression*)parser_const_float(parser,
1029 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
1030 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
1032 out = (ast_expression*)ast_binary_new(ctx,
1033 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
1034 exprs[0], exprs[1]);
1038 * ^ can be implemented as:
1039 * (LHS | RHS) & ~(LHS & RHS)
1040 * to implement ~ we need to use -1-X, as you can see the
1041 * whole process ends up becoming:
1042 * (LHS | RHS) & (-1 - (LHS & RHS))
1044 if (NotSameType(TYPE_FLOAT)) {
1045 compile_error(ctx, "invalid types used in expression: cannot perform bit operations between types %s and %s",
1046 type_name[exprs[0]->vtype],
1047 type_name[exprs[1]->vtype]);
1051 if(CanConstFold(exprs[0], exprs[1])) {
1052 out = (ast_expression*)parser_const_float(parser, (float)((qcint)(ConstF(0)) ^ ((qcint)(ConstF(1)))));
1054 ast_binary *expr = ast_binary_new(
1057 (ast_expression*)parser_const_float_neg1(parser),
1058 (ast_expression*)ast_binary_new(
1065 expr->refs = AST_REF_NONE;
1067 out = (ast_expression*)
1071 (ast_expression*)ast_binary_new(
1077 (ast_expression*)expr
1082 case opid2('<','<'):
1083 case opid2('>','>'):
1084 if (CanConstFold(exprs[0], exprs[1]) && ! NotSameType(TYPE_FLOAT)) {
1085 if (op->id == opid2('<','<'))
1086 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) << (unsigned int)(ConstF(1))));
1088 out = (ast_expression*)parser_const_float(parser, (double)((unsigned int)(ConstF(0)) >> (unsigned int)(ConstF(1))));
1091 case opid3('<','<','='):
1092 case opid3('>','>','='):
1093 compile_error(ast_ctx(exprs[0]), "Not Yet Implemented: bit-shifts");
1096 case opid2('|','|'):
1097 generated_op += 1; /* INSTR_OR */
1098 case opid2('&','&'):
1099 generated_op += INSTR_AND;
1100 if (CanConstFold(exprs[0], exprs[1]))
1102 if (OPTS_FLAG(PERL_LOGIC)) {
1103 if (immediate_is_true(ctx, asvalue[0]))
1107 out = (ast_expression*)parser_const_float(parser,
1108 ( (generated_op == INSTR_OR)
1109 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
1110 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
1115 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
1116 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1117 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1118 compile_error(ctx, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
1121 for (i = 0; i < 2; ++i) {
1122 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->vtype == TYPE_VECTOR) {
1123 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
1125 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1127 exprs[i] = out; out = NULL;
1128 if (OPTS_FLAG(PERL_LOGIC)) {
1129 /* here we want to keep the right expressions' type */
1133 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->vtype == TYPE_STRING) {
1134 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
1136 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
1138 exprs[i] = out; out = NULL;
1139 if (OPTS_FLAG(PERL_LOGIC)) {
1140 /* here we want to keep the right expressions' type */
1145 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1149 case opid2('?',':'):
1150 if (vec_last(sy->paren) != PAREN_TERNARY2) {
1151 compile_error(ctx, "mismatched parenthesis/ternary");
1155 if (!ast_compare_type(exprs[1], exprs[2])) {
1156 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
1157 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
1158 compile_error(ctx, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
1161 if (CanConstFold1(exprs[0]))
1162 out = (immediate_is_true(ctx, asvalue[0]) ? exprs[1] : exprs[2]);
1164 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
1167 case opid2('*', '*'):
1168 if (NotSameType(TYPE_FLOAT)) {
1169 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1170 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1171 compile_error(ctx, "invalid types used in exponentiation: %s and %s",
1177 if (CanConstFold(exprs[0], exprs[1])) {
1178 out = (ast_expression*)parser_const_float(parser, powf(ConstF(0), ConstF(1)));
1180 ast_call *gencall = ast_call_new(parser_ctx(parser), intrin_func(parser, "pow"));
1181 vec_push(gencall->params, exprs[0]);
1182 vec_push(gencall->params, exprs[1]);
1183 out = (ast_expression*)gencall;
1187 case opid3('<','=','>'): /* -1, 0, or 1 */
1188 if (NotSameType(TYPE_FLOAT)) {
1189 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1190 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1191 compile_error(ctx, "invalid types used in comparision: %s and %s",
1197 if (CanConstFold(exprs[0], exprs[1])) {
1198 if (ConstF(0) < ConstF(1))
1199 out = (ast_expression*)parser_const_float_neg1(parser);
1200 else if (ConstF(0) == ConstF(1))
1201 out = (ast_expression*)parser_const_float_0(parser);
1202 else if (ConstF(0) > ConstF(1))
1203 out = (ast_expression*)parser_const_float_1(parser);
1205 ast_binary *eq = ast_binary_new(ctx, INSTR_EQ_F, exprs[0], exprs[1]);
1207 eq->refs = AST_REF_NONE;
1210 out = (ast_expression*)ast_ternary_new(ctx,
1211 (ast_expression*)ast_binary_new(ctx, INSTR_LT, exprs[0], exprs[1]),
1213 (ast_expression*)parser_const_float_neg1(parser),
1216 (ast_expression*)ast_ternary_new(ctx, (ast_expression*)eq,
1218 (ast_expression*)parser_const_float_0(parser),
1221 (ast_expression*)parser_const_float_1(parser)
1231 generated_op += 1; /* INSTR_GT */
1233 generated_op += 1; /* INSTR_LT */
1234 case opid2('>', '='):
1235 generated_op += 1; /* INSTR_GE */
1236 case opid2('<', '='):
1237 generated_op += INSTR_LE;
1238 if (NotSameType(TYPE_FLOAT)) {
1239 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1240 type_name[exprs[0]->vtype],
1241 type_name[exprs[1]->vtype]);
1244 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
1246 case opid2('!', '='):
1247 if (exprs[0]->vtype != exprs[1]->vtype) {
1248 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1249 type_name[exprs[0]->vtype],
1250 type_name[exprs[1]->vtype]);
1253 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1255 case opid2('=', '='):
1256 if (exprs[0]->vtype != exprs[1]->vtype) {
1257 compile_error(ctx, "invalid types used in expression: cannot perform comparison between types %s and %s",
1258 type_name[exprs[0]->vtype],
1259 type_name[exprs[1]->vtype]);
1262 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->vtype], exprs[0], exprs[1]);
1266 if (ast_istype(exprs[0], ast_entfield)) {
1267 ast_expression *field = ((ast_entfield*)exprs[0])->field;
1268 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1269 exprs[0]->vtype == TYPE_FIELD &&
1270 exprs[0]->next->vtype == TYPE_VECTOR)
1272 assignop = type_storep_instr[TYPE_VECTOR];
1275 assignop = type_storep_instr[exprs[0]->vtype];
1276 if (assignop == VINSTR_END || !ast_compare_type(field->next, exprs[1]))
1278 ast_type_to_string(field->next, ty1, sizeof(ty1));
1279 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1280 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1281 field->next->vtype == TYPE_FUNCTION &&
1282 exprs[1]->vtype == TYPE_FUNCTION)
1284 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1285 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1288 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1293 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1294 exprs[0]->vtype == TYPE_FIELD &&
1295 exprs[0]->next->vtype == TYPE_VECTOR)
1297 assignop = type_store_instr[TYPE_VECTOR];
1300 assignop = type_store_instr[exprs[0]->vtype];
1303 if (assignop == VINSTR_END) {
1304 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1305 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1306 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1308 else if (!ast_compare_type(exprs[0], exprs[1]))
1310 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1311 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1312 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1313 exprs[0]->vtype == TYPE_FUNCTION &&
1314 exprs[1]->vtype == TYPE_FUNCTION)
1316 (void)!compile_warning(ctx, WARN_ASSIGN_FUNCTION_TYPES,
1317 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1320 compile_error(ctx, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1323 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1324 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1326 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1328 case opid3('+','+','P'):
1329 case opid3('-','-','P'):
1331 if (exprs[0]->vtype != TYPE_FLOAT) {
1332 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1333 compile_error(ast_ctx(exprs[0]), "invalid type for prefix increment: %s", ty1);
1336 if (op->id == opid3('+','+','P'))
1337 addop = INSTR_ADD_F;
1339 addop = INSTR_SUB_F;
1340 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1341 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1343 if (ast_istype(exprs[0], ast_entfield)) {
1344 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1346 (ast_expression*)parser_const_float_1(parser));
1348 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1350 (ast_expression*)parser_const_float_1(parser));
1353 case opid3('S','+','+'):
1354 case opid3('S','-','-'):
1356 if (exprs[0]->vtype != TYPE_FLOAT) {
1357 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1358 compile_error(ast_ctx(exprs[0]), "invalid type for suffix increment: %s", ty1);
1361 if (op->id == opid3('S','+','+')) {
1362 addop = INSTR_ADD_F;
1363 subop = INSTR_SUB_F;
1365 addop = INSTR_SUB_F;
1366 subop = INSTR_ADD_F;
1368 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1369 compile_error(ast_ctx(exprs[0]), "assignment to constant `%s`", asvalue[0]->name);
1371 if (ast_istype(exprs[0], ast_entfield)) {
1372 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1374 (ast_expression*)parser_const_float_1(parser));
1376 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1378 (ast_expression*)parser_const_float_1(parser));
1382 out = (ast_expression*)ast_binary_new(ctx, subop,
1384 (ast_expression*)parser_const_float_1(parser));
1386 case opid2('+','='):
1387 case opid2('-','='):
1388 if (exprs[0]->vtype != exprs[1]->vtype ||
1389 (exprs[0]->vtype != TYPE_VECTOR && exprs[0]->vtype != TYPE_FLOAT) )
1391 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1392 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1393 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1397 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1398 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1400 if (ast_istype(exprs[0], ast_entfield))
1401 assignop = type_storep_instr[exprs[0]->vtype];
1403 assignop = type_store_instr[exprs[0]->vtype];
1404 switch (exprs[0]->vtype) {
1406 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1407 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1408 exprs[0], exprs[1]);
1411 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1412 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1413 exprs[0], exprs[1]);
1416 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1417 type_name[exprs[0]->vtype],
1418 type_name[exprs[1]->vtype]);
1422 case opid2('*','='):
1423 case opid2('/','='):
1424 if (exprs[1]->vtype != TYPE_FLOAT ||
1425 !(exprs[0]->vtype == TYPE_FLOAT ||
1426 exprs[0]->vtype == TYPE_VECTOR))
1428 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1429 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1430 compile_error(ctx, "invalid types used in expression: %s and %s",
1434 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1435 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1437 if (ast_istype(exprs[0], ast_entfield))
1438 assignop = type_storep_instr[exprs[0]->vtype];
1440 assignop = type_store_instr[exprs[0]->vtype];
1441 switch (exprs[0]->vtype) {
1443 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1444 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1445 exprs[0], exprs[1]);
1448 if (op->id == opid2('*','=')) {
1449 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1450 exprs[0], exprs[1]);
1452 /* there's no DIV_VF */
1453 if (CanConstFold1(exprs[1])) {
1454 out = (ast_expression*)parser_const_float(parser, 1.0 / ConstF(1));
1456 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1457 (ast_expression*)parser_const_float_1(parser),
1461 compile_error(ctx, "internal error: failed to generate division");
1464 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1469 compile_error(ctx, "invalid types used in expression: cannot add or subtract type %s and %s",
1470 type_name[exprs[0]->vtype],
1471 type_name[exprs[1]->vtype]);
1475 case opid2('&','='):
1476 case opid2('|','='):
1477 if (NotSameType(TYPE_FLOAT)) {
1478 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1479 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1480 compile_error(ctx, "invalid types used in expression: %s and %s",
1484 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1485 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1487 if (ast_istype(exprs[0], ast_entfield))
1488 assignop = type_storep_instr[exprs[0]->vtype];
1490 assignop = type_store_instr[exprs[0]->vtype];
1491 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1492 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1493 exprs[0], exprs[1]);
1495 case opid3('&','~','='):
1496 /* This is like: a &= ~(b);
1497 * But QC has no bitwise-not, so we implement it as
1500 if (NotSameType(TYPE_FLOAT)) {
1501 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1502 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1503 compile_error(ctx, "invalid types used in expression: %s and %s",
1507 if (ast_istype(exprs[0], ast_entfield))
1508 assignop = type_storep_instr[exprs[0]->vtype];
1510 assignop = type_store_instr[exprs[0]->vtype];
1511 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1514 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1515 compile_error(ctx, "assignment to constant `%s`", asvalue[0]->name);
1517 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1518 asbinstore->keep_dest = true;
1519 out = (ast_expression*)asbinstore;
1522 case opid2('~', 'P'):
1523 if (exprs[0]->vtype != TYPE_FLOAT) {
1524 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1525 compile_error(ast_ctx(exprs[0]), "invalid type for bit not: %s", ty1);
1529 if(CanConstFold1(exprs[0]))
1530 out = (ast_expression*)parser_const_float(parser, ~(qcint)ConstF(0));
1532 out = (ast_expression*)
1533 ast_binary_new(ctx, INSTR_SUB_F, (ast_expression*)parser_const_float_neg1(parser), exprs[0]);
1539 compile_error(ctx, "failed to apply operator %s", op->op);
1543 vec_push(sy->out, syexp(ctx, out));
1547 static bool parser_close_call(parser_t *parser, shunt *sy)
1549 /* was a function call */
1550 ast_expression *fun;
1551 ast_value *funval = NULL;
1555 size_t paramcount, i;
1557 fid = vec_last(sy->ops).off;
1558 vec_shrinkby(sy->ops, 1);
1560 /* out[fid] is the function
1561 * everything above is parameters...
1563 if (!vec_size(sy->argc)) {
1564 parseerror(parser, "internal error: no argument counter available");
1568 paramcount = vec_last(sy->argc);
1571 if (vec_size(sy->out) < fid) {
1572 parseerror(parser, "internal error: broken function call%lu < %lu+%lu\n",
1573 (unsigned long)vec_size(sy->out),
1575 (unsigned long)paramcount);
1579 fun = sy->out[fid].out;
1581 if (fun == intrinsic_debug_typestring) {
1583 if (fid+2 != vec_size(sy->out) ||
1584 vec_last(sy->out).block)
1586 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1589 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1590 ast_unref(vec_last(sy->out).out);
1591 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1592 (ast_expression*)parser_const_string(parser, ty, false));
1593 vec_shrinkby(sy->out, 1);
1597 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1601 if (fid+1 < vec_size(sy->out))
1604 if (fid+1 + paramcount != vec_size(sy->out)) {
1605 parseerror(parser, "internal error: parameter count mismatch: (%lu+1+%lu), %lu",
1606 (unsigned long)fid, (unsigned long)paramcount, (unsigned long)vec_size(sy->out));
1610 for (i = 0; i < paramcount; ++i)
1611 vec_push(call->params, sy->out[fid+1 + i].out);
1612 vec_shrinkby(sy->out, paramcount);
1613 (void)!ast_call_check_types(call, parser->function->vtype->expression.varparam);
1614 if (parser->max_param_count < paramcount)
1615 parser->max_param_count = paramcount;
1617 if (ast_istype(fun, ast_value)) {
1618 funval = (ast_value*)fun;
1619 if ((fun->flags & AST_FLAG_VARIADIC) &&
1620 !(/*funval->cvq == CV_CONST && */ funval->hasvalue && funval->constval.vfunc->builtin))
1622 call->va_count = (ast_expression*)parser_const_float(parser, (double)paramcount);
1626 /* overwrite fid, the function, with a call */
1627 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1629 if (fun->vtype != TYPE_FUNCTION) {
1630 parseerror(parser, "not a function (%s)", type_name[fun->vtype]);
1635 parseerror(parser, "could not determine function return type");
1638 ast_value *fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1640 if (fun->flags & AST_FLAG_DEPRECATED) {
1642 return !parsewarning(parser, WARN_DEPRECATED,
1643 "call to function (which is marked deprecated)\n",
1644 "-> it has been declared here: %s:%i",
1645 ast_ctx(fun).file, ast_ctx(fun).line);
1648 return !parsewarning(parser, WARN_DEPRECATED,
1649 "call to `%s` (which is marked deprecated)\n"
1650 "-> `%s` declared here: %s:%i",
1651 fval->name, fval->name, ast_ctx(fun).file, ast_ctx(fun).line);
1653 return !parsewarning(parser, WARN_DEPRECATED,
1654 "call to `%s` (deprecated: %s)\n"
1655 "-> `%s` declared here: %s:%i",
1656 fval->name, fval->desc, fval->name, ast_ctx(fun).file,
1660 if (vec_size(fun->params) != paramcount &&
1661 !((fun->flags & AST_FLAG_VARIADIC) &&
1662 vec_size(fun->params) < paramcount))
1664 const char *fewmany = (vec_size(fun->params) > paramcount) ? "few" : "many";
1666 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1667 "too %s parameters for call to %s: expected %i, got %i\n"
1668 " -> `%s` has been declared here: %s:%i",
1669 fewmany, fval->name, (int)vec_size(fun->params), (int)paramcount,
1670 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1672 return !parsewarning(parser, WARN_INVALID_PARAMETER_COUNT,
1673 "too %s parameters for function call: expected %i, got %i\n"
1674 " -> it has been declared here: %s:%i",
1675 fewmany, (int)vec_size(fun->params), (int)paramcount,
1676 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1683 static bool parser_close_paren(parser_t *parser, shunt *sy)
1685 if (!vec_size(sy->ops)) {
1686 parseerror(parser, "unmatched closing paren");
1690 while (vec_size(sy->ops)) {
1691 if (vec_last(sy->ops).isparen) {
1692 if (vec_last(sy->paren) == PAREN_FUNC) {
1694 if (!parser_close_call(parser, sy))
1698 if (vec_last(sy->paren) == PAREN_EXPR) {
1700 if (!vec_size(sy->out)) {
1701 compile_error(vec_last(sy->ops).ctx, "empty paren expression");
1702 vec_shrinkby(sy->ops, 1);
1705 vec_shrinkby(sy->ops, 1);
1708 if (vec_last(sy->paren) == PAREN_INDEX) {
1710 /* pop off the parenthesis */
1711 vec_shrinkby(sy->ops, 1);
1712 /* then apply the index operator */
1713 if (!parser_sy_apply_operator(parser, sy))
1717 if (vec_last(sy->paren) == PAREN_TERNARY1) {
1718 vec_last(sy->paren) = PAREN_TERNARY2;
1719 /* pop off the parenthesis */
1720 vec_shrinkby(sy->ops, 1);
1723 compile_error(vec_last(sy->ops).ctx, "invalid parenthesis");
1726 if (!parser_sy_apply_operator(parser, sy))
1732 static void parser_reclassify_token(parser_t *parser)
1735 for (i = 0; i < operator_count; ++i) {
1736 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1737 parser->tok = TOKEN_OPERATOR;
1743 static ast_expression* parse_vararg_do(parser_t *parser)
1745 ast_expression *idx, *out;
1747 ast_value *funtype = parser->function->vtype;
1748 lex_ctx ctx = parser_ctx(parser);
1750 if (!parser->function->varargs) {
1751 parseerror(parser, "function has no variable argument list");
1755 if (!parser_next(parser) || parser->tok != '(') {
1756 parseerror(parser, "expected parameter index and type in parenthesis");
1759 if (!parser_next(parser)) {
1760 parseerror(parser, "error parsing parameter index");
1764 idx = parse_expression_leave(parser, true, false, false);
1768 if (parser->tok != ',') {
1769 if (parser->tok != ')') {
1771 parseerror(parser, "expected comma after parameter index");
1774 /* vararg piping: ...(start) */
1775 out = (ast_expression*)ast_argpipe_new(ctx, idx);
1779 if (!parser_next(parser) || (parser->tok != TOKEN_IDENT && parser->tok != TOKEN_TYPENAME)) {
1781 parseerror(parser, "expected typename for vararg");
1785 typevar = parse_typename(parser, NULL, NULL);
1791 if (parser->tok != ')') {
1793 ast_delete(typevar);
1794 parseerror(parser, "expected closing paren");
1798 if (funtype->expression.varparam &&
1799 !ast_compare_type((ast_expression*)typevar, (ast_expression*)funtype->expression.varparam))
1803 ast_type_to_string((ast_expression*)typevar, ty1, sizeof(ty1));
1804 ast_type_to_string((ast_expression*)funtype->expression.varparam, ty2, sizeof(ty2));
1805 compile_error(ast_ctx(typevar),
1806 "function was declared to take varargs of type `%s`, requested type is: %s",
1810 out = (ast_expression*)ast_array_index_new(ctx, (ast_expression*)(parser->function->varargs), idx);
1811 ast_type_adopt(out, typevar);
1812 ast_delete(typevar);
1816 static ast_expression* parse_vararg(parser_t *parser)
1818 bool old_noops = parser->lex->flags.noops;
1820 ast_expression *out;
1822 parser->lex->flags.noops = true;
1823 out = parse_vararg_do(parser);
1825 parser->lex->flags.noops = old_noops;
1829 /* not to be exposed */
1830 extern bool ftepp_predef_exists(const char *name);
1832 static bool parse_sya_operand(parser_t *parser, shunt *sy, bool with_labels)
1834 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1835 parser->tok == TOKEN_IDENT &&
1836 !strcmp(parser_tokval(parser), "_"))
1838 /* a translatable string */
1841 parser->lex->flags.noops = true;
1842 if (!parser_next(parser) || parser->tok != '(') {
1843 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1846 parser->lex->flags.noops = false;
1847 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1848 parseerror(parser, "expected a constant string in translatable-string extension");
1851 val = parser_const_string(parser, parser_tokval(parser), true);
1854 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1856 if (!parser_next(parser) || parser->tok != ')') {
1857 parseerror(parser, "expected closing paren after translatable string");
1862 else if (parser->tok == TOKEN_DOTS)
1865 if (!OPTS_FLAG(VARIADIC_ARGS)) {
1866 parseerror(parser, "cannot access varargs (try -fvariadic-args)");
1869 va = parse_vararg(parser);
1872 vec_push(sy->out, syexp(parser_ctx(parser), va));
1875 else if (parser->tok == TOKEN_FLOATCONST) {
1877 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1880 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1883 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1885 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1888 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1891 else if (parser->tok == TOKEN_STRINGCONST) {
1893 val = parser_const_string(parser, parser_tokval(parser), false);
1896 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1899 else if (parser->tok == TOKEN_VECTORCONST) {
1901 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1904 vec_push(sy->out, syexp(parser_ctx(parser), (ast_expression*)val));
1907 else if (parser->tok == TOKEN_IDENT)
1909 const char *ctoken = parser_tokval(parser);
1910 ast_expression *prev = vec_size(sy->out) ? vec_last(sy->out).out : NULL;
1911 ast_expression *var;
1912 /* a_vector.{x,y,z} */
1913 if (!vec_size(sy->ops) ||
1914 !vec_last(sy->ops).etype ||
1915 operators[vec_last(sy->ops).etype-1].id != opid1('.') ||
1916 (prev >= intrinsic_debug_typestring &&
1917 prev <= intrinsic_debug_typestring))
1919 /* When adding more intrinsics, fix the above condition */
1922 if (prev && prev->vtype == TYPE_VECTOR && ctoken[0] >= 'x' && ctoken[0] <= 'z' && !ctoken[1])
1924 var = (ast_expression*)parser->const_vec[ctoken[0]-'x'];
1926 var = parser_find_var(parser, parser_tokval(parser));
1928 var = parser_find_field(parser, parser_tokval(parser));
1930 if (!var && with_labels) {
1931 var = (ast_expression*)parser_find_label(parser, parser_tokval(parser));
1933 ast_label *lbl = ast_label_new(parser_ctx(parser), parser_tokval(parser), true);
1934 var = (ast_expression*)lbl;
1935 vec_push(parser->labels, lbl);
1938 if (!var && !strcmp(parser_tokval(parser), "__FUNC__"))
1939 var = (ast_expression*)parser_const_string(parser, parser->function->name, false);
1942 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1943 var = (ast_expression*)intrinsic_debug_typestring;
1945 /* now we try for the real intrinsic hashtable. If the string
1946 * begins with __builtin, we simply skip past it, otherwise we
1947 * use the identifier as is.
1949 else if (!strncmp(parser_tokval(parser), "__builtin_", 10)) {
1950 var = intrin_func(parser, parser_tokval(parser) + 10 /* skip __builtin */);
1954 char *correct = NULL;
1958 * sometimes people use preprocessing predefs without enabling them
1959 * i've done this thousands of times already myself. Lets check for
1960 * it in the predef table. And diagnose it better :)
1962 if (!OPTS_FLAG(FTEPP_PREDEFS) && ftepp_predef_exists(parser_tokval(parser))) {
1963 parseerror(parser, "unexpected identifier: %s (use -fftepp-predef to enable pre-defined macros)", parser_tokval(parser));
1968 * TODO: determine the best score for the identifier: be it
1969 * a variable, a field.
1971 * We should also consider adding correction tables for
1972 * other things as well.
1974 if (OPTS_OPTION_BOOL(OPTION_CORRECTION) && strlen(parser_tokval(parser)) <= 16) {
1976 correct_init(&corr);
1978 for (i = 0; i < vec_size(parser->correct_variables); i++) {
1979 correct = correct_str(&corr, parser->correct_variables[i], parser_tokval(parser));
1980 if (strcmp(correct, parser_tokval(parser))) {
1982 } else if (correct) {
1987 correct_free(&corr);
1990 parseerror(parser, "unexpected identifier: %s (did you mean %s?)", parser_tokval(parser), correct);
1995 parseerror(parser, "unexpected identifier: %s", parser_tokval(parser));
2001 if (ast_istype(var, ast_value)) {
2002 ((ast_value*)var)->uses++;
2004 else if (ast_istype(var, ast_member)) {
2005 ast_member *mem = (ast_member*)var;
2006 if (ast_istype(mem->owner, ast_value))
2007 ((ast_value*)(mem->owner))->uses++;
2010 vec_push(sy->out, syexp(parser_ctx(parser), var));
2013 parseerror(parser, "unexpected token `%s`", parser_tokval(parser));
2017 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma, bool truthvalue, bool with_labels)
2019 ast_expression *expr = NULL;
2022 bool wantop = false;
2023 /* only warn once about an assignment in a truth value because the current code
2024 * would trigger twice on: if(a = b && ...), once for the if-truth-value, once for the && part
2026 bool warn_truthvalue = true;
2028 /* count the parens because an if starts with one, so the
2029 * end of a condition is an unmatched closing paren
2033 memset(&sy, 0, sizeof(sy));
2035 parser->lex->flags.noops = false;
2037 parser_reclassify_token(parser);
2041 if (parser->tok == TOKEN_TYPENAME) {
2042 parseerror(parser, "unexpected typename `%s`", parser_tokval(parser));
2046 if (parser->tok == TOKEN_OPERATOR)
2048 /* classify the operator */
2049 const oper_info *op;
2050 const oper_info *olast = NULL;
2052 for (o = 0; o < operator_count; ++o) {
2053 if (((!(operators[o].flags & OP_PREFIX) == !!wantop)) &&
2054 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
2055 !strcmp(parser_tokval(parser), operators[o].op))
2060 if (o == operator_count) {
2061 compile_error(parser_ctx(parser), "unknown operator: %s", parser_tokval(parser));
2064 /* found an operator */
2067 /* when declaring variables, a comma starts a new variable */
2068 if (op->id == opid1(',') && !vec_size(sy.paren) && stopatcomma) {
2069 /* fixup the token */
2074 /* a colon without a pervious question mark cannot be a ternary */
2075 if (!ternaries && op->id == opid2(':','?')) {
2080 if (op->id == opid1(',')) {
2081 if (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2082 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
2086 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2087 olast = &operators[vec_last(sy.ops).etype-1];
2089 #define IsAssignOp(x) (\
2090 (x) == opid1('=') || \
2091 (x) == opid2('+','=') || \
2092 (x) == opid2('-','=') || \
2093 (x) == opid2('*','=') || \
2094 (x) == opid2('/','=') || \
2095 (x) == opid2('%','=') || \
2096 (x) == opid2('&','=') || \
2097 (x) == opid2('|','=') || \
2098 (x) == opid3('&','~','=') \
2100 if (warn_truthvalue) {
2101 if ( (olast && IsAssignOp(olast->id) && (op->id == opid2('&','&') || op->id == opid2('|','|'))) ||
2102 (olast && IsAssignOp(op->id) && (olast->id == opid2('&','&') || olast->id == opid2('|','|'))) ||
2103 (truthvalue && !vec_size(sy.paren) && IsAssignOp(op->id))
2106 (void)!parsewarning(parser, WARN_PARENTHESIS, "suggesting parenthesis around assignment used as truth value");
2107 warn_truthvalue = false;
2112 (op->prec < olast->prec) ||
2113 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
2115 if (!parser_sy_apply_operator(parser, &sy))
2117 if (vec_size(sy.ops) && !vec_last(sy.ops).isparen)
2118 olast = &operators[vec_last(sy.ops).etype-1];
2123 if (op->id == opid1('(')) {
2125 size_t sycount = vec_size(sy.out);
2126 /* we expected an operator, this is the function-call operator */
2127 vec_push(sy.paren, PAREN_FUNC);
2128 vec_push(sy.ops, syparen(parser_ctx(parser), sycount-1));
2129 vec_push(sy.argc, 0);
2131 vec_push(sy.paren, PAREN_EXPR);
2132 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2135 } else if (op->id == opid1('[')) {
2137 parseerror(parser, "unexpected array subscript");
2140 vec_push(sy.paren, PAREN_INDEX);
2141 /* push both the operator and the paren, this makes life easier */
2142 vec_push(sy.ops, syop(parser_ctx(parser), op));
2143 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2145 } else if (op->id == opid2('?',':')) {
2146 vec_push(sy.ops, syop(parser_ctx(parser), op));
2147 vec_push(sy.ops, syparen(parser_ctx(parser), 0));
2150 vec_push(sy.paren, PAREN_TERNARY1);
2151 } else if (op->id == opid2(':','?')) {
2152 if (!vec_size(sy.paren)) {
2153 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2156 if (vec_last(sy.paren) != PAREN_TERNARY1) {
2157 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
2160 if (!parser_close_paren(parser, &sy))
2162 vec_push(sy.ops, syop(parser_ctx(parser), op));
2166 vec_push(sy.ops, syop(parser_ctx(parser), op));
2167 wantop = !!(op->flags & OP_SUFFIX);
2170 else if (parser->tok == ')') {
2171 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2172 if (!parser_sy_apply_operator(parser, &sy))
2175 if (!vec_size(sy.paren))
2178 if (vec_last(sy.paren) == PAREN_TERNARY1) {
2179 parseerror(parser, "mismatched parentheses (closing paren in ternary expression?)");
2182 if (!parser_close_paren(parser, &sy))
2185 /* must be a function call without parameters */
2186 if (vec_last(sy.paren) != PAREN_FUNC) {
2187 parseerror(parser, "closing paren in invalid position");
2190 if (!parser_close_paren(parser, &sy))
2195 else if (parser->tok == '(') {
2196 parseerror(parser, "internal error: '(' should be classified as operator");
2199 else if (parser->tok == '[') {
2200 parseerror(parser, "internal error: '[' should be classified as operator");
2203 else if (parser->tok == ']') {
2204 while (vec_size(sy.paren) && vec_last(sy.paren) == PAREN_TERNARY2) {
2205 if (!parser_sy_apply_operator(parser, &sy))
2208 if (!vec_size(sy.paren))
2210 if (vec_last(sy.paren) != PAREN_INDEX) {
2211 parseerror(parser, "mismatched parentheses, unexpected ']'");
2214 if (!parser_close_paren(parser, &sy))
2219 if (!parse_sya_operand(parser, &sy, with_labels))
2222 if (vec_size(sy.paren) && vec_last(sy.ops).isparen && vec_last(sy.paren) == PAREN_FUNC)
2223 vec_last(sy.argc)++;
2228 /* in this case we might want to allow constant string concatenation */
2229 bool concatenated = false;
2230 if (parser->tok == TOKEN_STRINGCONST && vec_size(sy.out)) {
2231 ast_expression *lexpr = vec_last(sy.out).out;
2232 if (ast_istype(lexpr, ast_value)) {
2233 ast_value *last = (ast_value*)lexpr;
2234 if (last->isimm == true && last->cvq == CV_CONST &&
2235 last->hasvalue && last->expression.vtype == TYPE_STRING)
2237 char *newstr = NULL;
2238 util_asprintf(&newstr, "%s%s", last->constval.vstring, parser_tokval(parser));
2239 vec_last(sy.out).out = (ast_expression*)parser_const_string(parser, newstr, false);
2241 concatenated = true;
2245 if (!concatenated) {
2246 parseerror(parser, "expected operator or end of statement");
2251 if (!parser_next(parser)) {
2254 if (parser->tok == ';' ||
2255 ((!vec_size(sy.paren) || (vec_size(sy.paren) == 1 && vec_last(sy.paren) == PAREN_TERNARY2)) &&
2256 (parser->tok == ']' || parser->tok == ')' || parser->tok == '}')))
2262 while (vec_size(sy.ops)) {
2263 if (!parser_sy_apply_operator(parser, &sy))
2267 parser->lex->flags.noops = true;
2268 if (vec_size(sy.out) != 1) {
2269 parseerror(parser, "expression with not 1 but %lu output values...", (unsigned long) vec_size(sy.out));
2272 expr = sy.out[0].out;
2275 if (vec_size(sy.paren)) {
2276 parseerror(parser, "internal error: vec_size(sy.paren) = %lu", (unsigned long)vec_size(sy.paren));
2284 parser->lex->flags.noops = true;
2285 for (i = 0; i < vec_size(sy.out); ++i) {
2287 ast_unref(sy.out[i].out);
2296 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma, bool with_labels)
2298 ast_expression *e = parse_expression_leave(parser, stopatcomma, false, with_labels);
2301 if (parser->tok != ';') {
2302 parseerror(parser, "semicolon expected after expression");
2306 if (!parser_next(parser)) {
2313 static void parser_enterblock(parser_t *parser)
2315 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
2316 vec_push(parser->_blocklocals, vec_size(parser->_locals));
2317 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
2318 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
2319 vec_push(parser->_block_ctx, parser_ctx(parser));
2322 vec_push(parser->correct_variables, correct_trie_new());
2323 vec_push(parser->correct_variables_score, NULL);
2326 static bool parser_leaveblock(parser_t *parser)
2329 size_t locals, typedefs;
2331 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
2332 parseerror(parser, "internal error: parser_leaveblock with no block");
2336 util_htdel(vec_last(parser->variables));
2337 correct_del(vec_last(parser->correct_variables), vec_last(parser->correct_variables_score));
2339 vec_pop(parser->variables);
2340 vec_pop(parser->correct_variables);
2341 vec_pop(parser->correct_variables_score);
2342 if (!vec_size(parser->_blocklocals)) {
2343 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
2347 locals = vec_last(parser->_blocklocals);
2348 vec_pop(parser->_blocklocals);
2349 while (vec_size(parser->_locals) != locals) {
2350 ast_expression *e = vec_last(parser->_locals);
2351 ast_value *v = (ast_value*)e;
2352 vec_pop(parser->_locals);
2353 if (ast_istype(e, ast_value) && !v->uses) {
2354 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
2359 typedefs = vec_last(parser->_blocktypedefs);
2360 while (vec_size(parser->_typedefs) != typedefs) {
2361 ast_delete(vec_last(parser->_typedefs));
2362 vec_pop(parser->_typedefs);
2364 util_htdel(vec_last(parser->typedefs));
2365 vec_pop(parser->typedefs);
2367 vec_pop(parser->_block_ctx);
2372 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
2374 vec_push(parser->_locals, e);
2375 util_htset(vec_last(parser->variables), name, (void*)e);
2379 vec_last(parser->correct_variables),
2380 &vec_last(parser->correct_variables_score),
2385 static void parser_addglobal(parser_t *parser, const char *name, ast_expression *e)
2387 vec_push(parser->globals, e);
2388 util_htset(parser->htglobals, name, e);
2392 parser->correct_variables[0],
2393 &parser->correct_variables_score[0],
2398 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
2402 ast_expression *prev;
2404 if (cond->vtype == TYPE_VOID || cond->vtype >= TYPE_VARIANT) {
2406 ast_type_to_string(cond, ty, sizeof(ty));
2407 compile_error(ast_ctx(cond), "invalid type for if() condition: %s", ty);
2410 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->vtype == TYPE_STRING)
2413 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
2416 parseerror(parser, "internal error: failed to process condition");
2421 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->vtype == TYPE_VECTOR)
2423 /* vector types need to be cast to true booleans */
2424 ast_binary *bin = (ast_binary*)cond;
2425 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
2427 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
2429 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
2432 parseerror(parser, "internal error: failed to process condition");
2439 unary = (ast_unary*)cond;
2440 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
2442 cond = unary->operand;
2443 unary->operand = NULL;
2446 unary = (ast_unary*)cond;
2450 parseerror(parser, "internal error: failed to process condition");
2452 if (ifnot) *_ifnot = !*_ifnot;
2456 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
2459 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
2462 lex_ctx ctx = parser_ctx(parser);
2464 (void)block; /* not touching */
2466 /* skip the 'if', parse an optional 'not' and check for an opening paren */
2467 if (!parser_next(parser)) {
2468 parseerror(parser, "expected condition or 'not'");
2471 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
2473 if (!parser_next(parser)) {
2474 parseerror(parser, "expected condition in parenthesis");
2478 if (parser->tok != '(') {
2479 parseerror(parser, "expected 'if' condition in parenthesis");
2482 /* parse into the expression */
2483 if (!parser_next(parser)) {
2484 parseerror(parser, "expected 'if' condition after opening paren");
2487 /* parse the condition */
2488 cond = parse_expression_leave(parser, false, true, false);
2492 if (parser->tok != ')') {
2493 parseerror(parser, "expected closing paren after 'if' condition");
2497 /* parse into the 'then' branch */
2498 if (!parser_next(parser)) {
2499 parseerror(parser, "expected statement for on-true branch of 'if'");
2503 if (!parse_statement_or_block(parser, &ontrue)) {
2508 ontrue = (ast_expression*)ast_block_new(parser_ctx(parser));
2509 /* check for an else */
2510 if (!strcmp(parser_tokval(parser), "else")) {
2511 /* parse into the 'else' branch */
2512 if (!parser_next(parser)) {
2513 parseerror(parser, "expected on-false branch after 'else'");
2518 if (!parse_statement_or_block(parser, &onfalse)) {
2525 cond = process_condition(parser, cond, &ifnot);
2527 if (ontrue) ast_delete(ontrue);
2528 if (onfalse) ast_delete(onfalse);
2533 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2535 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2536 *out = (ast_expression*)ifthen;
2540 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2541 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2546 /* skip the 'while' and get the body */
2547 if (!parser_next(parser)) {
2548 if (OPTS_FLAG(LOOP_LABELS))
2549 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2551 parseerror(parser, "expected 'while' condition in parenthesis");
2555 if (parser->tok == ':') {
2556 if (!OPTS_FLAG(LOOP_LABELS))
2557 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2558 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2559 parseerror(parser, "expected loop label");
2562 label = util_strdup(parser_tokval(parser));
2563 if (!parser_next(parser)) {
2565 parseerror(parser, "expected 'while' condition in parenthesis");
2570 if (parser->tok != '(') {
2571 parseerror(parser, "expected 'while' condition in parenthesis");
2575 vec_push(parser->breaks, label);
2576 vec_push(parser->continues, label);
2578 rv = parse_while_go(parser, block, out);
2581 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2582 parseerror(parser, "internal error: label stack corrupted");
2588 vec_pop(parser->breaks);
2589 vec_pop(parser->continues);
2594 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2597 ast_expression *cond, *ontrue;
2601 lex_ctx ctx = parser_ctx(parser);
2603 (void)block; /* not touching */
2605 /* parse into the expression */
2606 if (!parser_next(parser)) {
2607 parseerror(parser, "expected 'while' condition after opening paren");
2610 /* parse the condition */
2611 cond = parse_expression_leave(parser, false, true, false);
2615 if (parser->tok != ')') {
2616 parseerror(parser, "expected closing paren after 'while' condition");
2620 /* parse into the 'then' branch */
2621 if (!parser_next(parser)) {
2622 parseerror(parser, "expected while-loop body");
2626 if (!parse_statement_or_block(parser, &ontrue)) {
2631 cond = process_condition(parser, cond, &ifnot);
2636 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2637 *out = (ast_expression*)aloop;
2641 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2642 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2647 /* skip the 'do' and get the body */
2648 if (!parser_next(parser)) {
2649 if (OPTS_FLAG(LOOP_LABELS))
2650 parseerror(parser, "expected loop label or body");
2652 parseerror(parser, "expected loop body");
2656 if (parser->tok == ':') {
2657 if (!OPTS_FLAG(LOOP_LABELS))
2658 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2659 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2660 parseerror(parser, "expected loop label");
2663 label = util_strdup(parser_tokval(parser));
2664 if (!parser_next(parser)) {
2666 parseerror(parser, "expected loop body");
2671 vec_push(parser->breaks, label);
2672 vec_push(parser->continues, label);
2674 rv = parse_dowhile_go(parser, block, out);
2677 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2678 parseerror(parser, "internal error: label stack corrupted");
2684 vec_pop(parser->breaks);
2685 vec_pop(parser->continues);
2690 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2693 ast_expression *cond, *ontrue;
2697 lex_ctx ctx = parser_ctx(parser);
2699 (void)block; /* not touching */
2701 if (!parse_statement_or_block(parser, &ontrue))
2704 /* expect the "while" */
2705 if (parser->tok != TOKEN_KEYWORD ||
2706 strcmp(parser_tokval(parser), "while"))
2708 parseerror(parser, "expected 'while' and condition");
2713 /* skip the 'while' and check for opening paren */
2714 if (!parser_next(parser) || parser->tok != '(') {
2715 parseerror(parser, "expected 'while' condition in parenthesis");
2719 /* parse into the expression */
2720 if (!parser_next(parser)) {
2721 parseerror(parser, "expected 'while' condition after opening paren");
2725 /* parse the condition */
2726 cond = parse_expression_leave(parser, false, true, false);
2730 if (parser->tok != ')') {
2731 parseerror(parser, "expected closing paren after 'while' condition");
2737 if (!parser_next(parser) || parser->tok != ';') {
2738 parseerror(parser, "expected semicolon after condition");
2744 if (!parser_next(parser)) {
2745 parseerror(parser, "parse error");
2751 cond = process_condition(parser, cond, &ifnot);
2756 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2757 *out = (ast_expression*)aloop;
2761 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2762 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2767 /* skip the 'for' and check for opening paren */
2768 if (!parser_next(parser)) {
2769 if (OPTS_FLAG(LOOP_LABELS))
2770 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2772 parseerror(parser, "expected 'for' expressions in parenthesis");
2776 if (parser->tok == ':') {
2777 if (!OPTS_FLAG(LOOP_LABELS))
2778 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2779 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2780 parseerror(parser, "expected loop label");
2783 label = util_strdup(parser_tokval(parser));
2784 if (!parser_next(parser)) {
2786 parseerror(parser, "expected 'for' expressions in parenthesis");
2791 if (parser->tok != '(') {
2792 parseerror(parser, "expected 'for' expressions in parenthesis");
2796 vec_push(parser->breaks, label);
2797 vec_push(parser->continues, label);
2799 rv = parse_for_go(parser, block, out);
2802 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2803 parseerror(parser, "internal error: label stack corrupted");
2809 vec_pop(parser->breaks);
2810 vec_pop(parser->continues);
2814 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2817 ast_expression *initexpr, *cond, *increment, *ontrue;
2822 lex_ctx ctx = parser_ctx(parser);
2824 parser_enterblock(parser);
2831 /* parse into the expression */
2832 if (!parser_next(parser)) {
2833 parseerror(parser, "expected 'for' initializer after opening paren");
2838 if (parser->tok == TOKEN_IDENT)
2839 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2841 if (typevar || parser->tok == TOKEN_TYPENAME) {
2843 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
2844 if (parsewarning(parser, WARN_EXTENSIONS,
2845 "current standard does not allow variable declarations in for-loop initializers"))
2849 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, 0, NULL))
2852 else if (parser->tok != ';')
2854 initexpr = parse_expression_leave(parser, false, false, false);
2859 /* move on to condition */
2860 if (parser->tok != ';') {
2861 parseerror(parser, "expected semicolon after for-loop initializer");
2864 if (!parser_next(parser)) {
2865 parseerror(parser, "expected for-loop condition");
2869 /* parse the condition */
2870 if (parser->tok != ';') {
2871 cond = parse_expression_leave(parser, false, true, false);
2876 /* move on to incrementor */
2877 if (parser->tok != ';') {
2878 parseerror(parser, "expected semicolon after for-loop initializer");
2881 if (!parser_next(parser)) {
2882 parseerror(parser, "expected for-loop condition");
2886 /* parse the incrementor */
2887 if (parser->tok != ')') {
2888 lex_ctx condctx = parser_ctx(parser);
2889 increment = parse_expression_leave(parser, false, false, false);
2892 if (!ast_side_effects(increment)) {
2893 if (compile_warning(condctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2899 if (parser->tok != ')') {
2900 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2903 /* parse into the 'then' branch */
2904 if (!parser_next(parser)) {
2905 parseerror(parser, "expected for-loop body");
2908 if (!parse_statement_or_block(parser, &ontrue))
2912 cond = process_condition(parser, cond, &ifnot);
2916 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2917 *out = (ast_expression*)aloop;
2919 if (!parser_leaveblock(parser)) {
2925 if (initexpr) ast_unref(initexpr);
2926 if (cond) ast_unref(cond);
2927 if (increment) ast_unref(increment);
2928 (void)!parser_leaveblock(parser);
2932 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2934 ast_expression *exp = NULL;
2935 ast_expression *var = NULL;
2936 ast_return *ret = NULL;
2937 ast_value *retval = parser->function->return_value;
2938 ast_value *expected = parser->function->vtype;
2940 lex_ctx ctx = parser_ctx(parser);
2942 (void)block; /* not touching */
2944 if (!parser_next(parser)) {
2945 parseerror(parser, "expected return expression");
2949 /* return assignments */
2950 if (parser->tok == '=') {
2951 if (!OPTS_FLAG(RETURN_ASSIGNMENTS)) {
2952 parseerror(parser, "return assignments not activated, try using -freturn-assigments");
2956 if (type_store_instr[expected->expression.next->vtype] == VINSTR_END) {
2958 ast_type_to_string(expected->expression.next, ty1, sizeof(ty1));
2959 parseerror(parser, "invalid return type: `%s'", ty1);
2963 if (!parser_next(parser)) {
2964 parseerror(parser, "expected return assignment expression");
2968 if (!(exp = parse_expression_leave(parser, false, false, false)))
2971 /* prepare the return value */
2973 retval = ast_value_new(ctx, "#LOCAL_RETURN", TYPE_VOID);
2974 ast_type_adopt(retval, expected->expression.next);
2975 parser->function->return_value = retval;
2978 if (!ast_compare_type(exp, (ast_expression*)retval)) {
2979 char ty1[1024], ty2[1024];
2980 ast_type_to_string(exp, ty1, sizeof(ty1));
2981 ast_type_to_string(&retval->expression, ty2, sizeof(ty2));
2982 parseerror(parser, "invalid type for return value: `%s', expected `%s'", ty1, ty2);
2985 /* store to 'return' local variable */
2986 var = (ast_expression*)ast_store_new(
2988 type_store_instr[expected->expression.next->vtype],
2989 (ast_expression*)retval, exp);
2996 if (parser->tok != ';')
2997 parseerror(parser, "missing semicolon after return assignment");
2998 else if (!parser_next(parser))
2999 parseerror(parser, "parse error after return assignment");
3005 if (parser->tok != ';') {
3006 exp = parse_expression(parser, false, false);
3010 if (exp->vtype != TYPE_NIL &&
3011 exp->vtype != ((ast_expression*)expected)->next->vtype)
3013 parseerror(parser, "return with invalid expression");
3016 ret = ast_return_new(ctx, exp);
3022 if (!parser_next(parser))
3023 parseerror(parser, "parse error");
3025 if (!retval && expected->expression.next->vtype != TYPE_VOID)
3027 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
3029 ret = ast_return_new(ctx, (ast_expression*)retval);
3031 *out = (ast_expression*)ret;
3035 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
3038 unsigned int levels = 0;
3039 lex_ctx ctx = parser_ctx(parser);
3040 const char **loops = (is_continue ? parser->continues : parser->breaks);
3042 (void)block; /* not touching */
3043 if (!parser_next(parser)) {
3044 parseerror(parser, "expected semicolon or loop label");
3048 if (!vec_size(loops)) {
3050 parseerror(parser, "`continue` can only be used inside loops");
3052 parseerror(parser, "`break` can only be used inside loops or switches");
3055 if (parser->tok == TOKEN_IDENT) {
3056 if (!OPTS_FLAG(LOOP_LABELS))
3057 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3058 i = vec_size(loops);
3060 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
3063 parseerror(parser, "no such loop to %s: `%s`",
3064 (is_continue ? "continue" : "break out of"),
3065 parser_tokval(parser));
3070 if (!parser_next(parser)) {
3071 parseerror(parser, "expected semicolon");
3076 if (parser->tok != ';') {
3077 parseerror(parser, "expected semicolon");
3081 if (!parser_next(parser))
3082 parseerror(parser, "parse error");
3084 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
3088 /* returns true when it was a variable qualifier, false otherwise!
3089 * on error, cvq is set to CV_WRONG
3091 static bool parse_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *is_static, uint32_t *_flags, char **message)
3093 bool had_const = false;
3094 bool had_var = false;
3095 bool had_noref = false;
3096 bool had_attrib = false;
3097 bool had_static = false;
3102 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
3104 /* parse an attribute */
3105 if (!parser_next(parser)) {
3106 parseerror(parser, "expected attribute after `[[`");
3110 if (!strcmp(parser_tokval(parser), "noreturn")) {
3111 flags |= AST_FLAG_NORETURN;
3112 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3113 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
3118 else if (!strcmp(parser_tokval(parser), "noref")) {
3120 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3121 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3126 else if (!strcmp(parser_tokval(parser), "inline")) {
3127 flags |= AST_FLAG_INLINE;
3128 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3129 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
3134 else if (!strcmp(parser_tokval(parser), "alias") && !(flags & AST_FLAG_ALIAS)) {
3135 flags |= AST_FLAG_ALIAS;
3138 if (!parser_next(parser)) {
3139 parseerror(parser, "parse error in attribute");
3143 if (parser->tok == '(') {
3144 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3145 parseerror(parser, "`alias` attribute missing parameter");
3149 *message = util_strdup(parser_tokval(parser));
3151 if (!parser_next(parser)) {
3152 parseerror(parser, "parse error in attribute");
3156 if (parser->tok != ')') {
3157 parseerror(parser, "`alias` attribute expected `)` after parameter");
3161 if (!parser_next(parser)) {
3162 parseerror(parser, "parse error in attribute");
3167 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3168 parseerror(parser, "`alias` attribute expected `]]`");
3172 else if (!strcmp(parser_tokval(parser), "deprecated") && !(flags & AST_FLAG_DEPRECATED)) {
3173 flags |= AST_FLAG_DEPRECATED;
3176 if (!parser_next(parser)) {
3177 parseerror(parser, "parse error in attribute");
3181 if (parser->tok == '(') {
3182 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
3183 parseerror(parser, "`deprecated` attribute missing parameter");
3187 *message = util_strdup(parser_tokval(parser));
3189 if (!parser_next(parser)) {
3190 parseerror(parser, "parse error in attribute");
3194 if(parser->tok != ')') {
3195 parseerror(parser, "`deprecated` attribute expected `)` after parameter");
3199 if (!parser_next(parser)) {
3200 parseerror(parser, "parse error in attribute");
3205 if (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3206 parseerror(parser, "`deprecated` attribute expected `]]`");
3209 if (*message) mem_d(*message);
3217 /* Skip tokens until we hit a ]] */
3218 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
3219 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
3220 if (!parser_next(parser)) {
3221 parseerror(parser, "error inside attribute");
3228 else if (with_local && !strcmp(parser_tokval(parser), "static"))
3230 else if (!strcmp(parser_tokval(parser), "const"))
3232 else if (!strcmp(parser_tokval(parser), "var"))
3234 else if (with_local && !strcmp(parser_tokval(parser), "local"))
3236 else if (!strcmp(parser_tokval(parser), "noref"))
3238 else if (!had_const && !had_var && !had_noref && !had_attrib && !had_static && !flags) {
3243 if (!parser_next(parser))
3253 *is_static = had_static;
3257 parseerror(parser, "parse error after variable qualifier");
3262 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
3263 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
3268 /* skip the 'while' and get the body */
3269 if (!parser_next(parser)) {
3270 if (OPTS_FLAG(LOOP_LABELS))
3271 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
3273 parseerror(parser, "expected 'switch' operand in parenthesis");
3277 if (parser->tok == ':') {
3278 if (!OPTS_FLAG(LOOP_LABELS))
3279 parseerror(parser, "labeled loops not activated, try using -floop-labels");
3280 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3281 parseerror(parser, "expected loop label");
3284 label = util_strdup(parser_tokval(parser));
3285 if (!parser_next(parser)) {
3287 parseerror(parser, "expected 'switch' operand in parenthesis");
3292 if (parser->tok != '(') {
3293 parseerror(parser, "expected 'switch' operand in parenthesis");
3297 vec_push(parser->breaks, label);
3299 rv = parse_switch_go(parser, block, out);
3302 if (vec_last(parser->breaks) != label) {
3303 parseerror(parser, "internal error: label stack corrupted");
3309 vec_pop(parser->breaks);
3314 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
3316 ast_expression *operand;
3319 ast_switch *switchnode;
3320 ast_switch_case swcase;
3323 bool noref, is_static;
3324 uint32_t qflags = 0;
3326 lex_ctx ctx = parser_ctx(parser);
3328 (void)block; /* not touching */
3331 /* parse into the expression */
3332 if (!parser_next(parser)) {
3333 parseerror(parser, "expected switch operand");
3336 /* parse the operand */
3337 operand = parse_expression_leave(parser, false, false, false);
3341 switchnode = ast_switch_new(ctx, operand);
3344 if (parser->tok != ')') {
3345 ast_delete(switchnode);
3346 parseerror(parser, "expected closing paren after 'switch' operand");
3350 /* parse over the opening paren */
3351 if (!parser_next(parser) || parser->tok != '{') {
3352 ast_delete(switchnode);
3353 parseerror(parser, "expected list of cases");
3357 if (!parser_next(parser)) {
3358 ast_delete(switchnode);
3359 parseerror(parser, "expected 'case' or 'default'");
3363 /* new block; allow some variables to be declared here */
3364 parser_enterblock(parser);
3367 if (parser->tok == TOKEN_IDENT)
3368 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3369 if (typevar || parser->tok == TOKEN_TYPENAME) {
3370 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL)) {
3371 ast_delete(switchnode);
3376 if (parse_qualifiers(parser, true, &cvq, &noref, &is_static, &qflags, NULL))
3378 if (cvq == CV_WRONG) {
3379 ast_delete(switchnode);
3382 if (!parse_variable(parser, block, false, cvq, NULL, noref, is_static, qflags, NULL)) {
3383 ast_delete(switchnode);
3392 while (parser->tok != '}') {
3393 ast_block *caseblock;
3395 if (!strcmp(parser_tokval(parser), "case")) {
3396 if (!parser_next(parser)) {
3397 ast_delete(switchnode);
3398 parseerror(parser, "expected expression for case");
3401 swcase.value = parse_expression_leave(parser, false, false, false);
3402 if (!swcase.value) {
3403 ast_delete(switchnode);
3404 parseerror(parser, "expected expression for case");
3407 if (!OPTS_FLAG(RELAXED_SWITCH)) {
3408 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
3409 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
3415 else if (!strcmp(parser_tokval(parser), "default")) {
3416 swcase.value = NULL;
3417 if (!parser_next(parser)) {
3418 ast_delete(switchnode);
3419 parseerror(parser, "expected colon");
3424 ast_delete(switchnode);
3425 parseerror(parser, "expected 'case' or 'default'");
3429 /* Now the colon and body */
3430 if (parser->tok != ':') {
3431 if (swcase.value) ast_unref(swcase.value);
3432 ast_delete(switchnode);
3433 parseerror(parser, "expected colon");
3437 if (!parser_next(parser)) {
3438 if (swcase.value) ast_unref(swcase.value);
3439 ast_delete(switchnode);
3440 parseerror(parser, "expected statements or case");
3443 caseblock = ast_block_new(parser_ctx(parser));
3445 if (swcase.value) ast_unref(swcase.value);
3446 ast_delete(switchnode);
3449 swcase.code = (ast_expression*)caseblock;
3450 vec_push(switchnode->cases, swcase);
3452 ast_expression *expr;
3453 if (parser->tok == '}')
3455 if (parser->tok == TOKEN_KEYWORD) {
3456 if (!strcmp(parser_tokval(parser), "case") ||
3457 !strcmp(parser_tokval(parser), "default"))
3462 if (!parse_statement(parser, caseblock, &expr, true)) {
3463 ast_delete(switchnode);
3468 if (!ast_block_add_expr(caseblock, expr)) {
3469 ast_delete(switchnode);
3475 parser_leaveblock(parser);
3478 if (parser->tok != '}') {
3479 ast_delete(switchnode);
3480 parseerror(parser, "expected closing paren of case list");
3483 if (!parser_next(parser)) {
3484 ast_delete(switchnode);
3485 parseerror(parser, "parse error after switch");
3488 *out = (ast_expression*)switchnode;
3492 /* parse computed goto sides */
3493 static ast_expression *parse_goto_computed(parser_t *parser, ast_expression **side) {
3494 ast_expression *on_true;
3495 ast_expression *on_false;
3496 ast_expression *cond;
3501 if (ast_istype(*side, ast_ternary)) {
3502 ast_ternary *tern = (ast_ternary*)*side;
3503 on_true = parse_goto_computed(parser, &tern->on_true);
3504 on_false = parse_goto_computed(parser, &tern->on_false);
3506 if (!on_true || !on_false) {
3507 parseerror(parser, "expected label or expression in ternary");
3508 if (on_true) ast_unref(on_true);
3509 if (on_false) ast_unref(on_false);
3517 return (ast_expression*)ast_ifthen_new(parser_ctx(parser), cond, on_true, on_false);
3518 } else if (ast_istype(*side, ast_label)) {
3519 ast_goto *gt = ast_goto_new(parser_ctx(parser), ((ast_label*)*side)->name);
3520 ast_goto_set_label(gt, ((ast_label*)*side));
3522 return (ast_expression*)gt;
3527 static bool parse_goto(parser_t *parser, ast_expression **out)
3529 ast_goto *gt = NULL;
3530 ast_expression *lbl;
3532 if (!parser_next(parser))
3535 if (parser->tok != TOKEN_IDENT) {
3536 ast_expression *expression;
3538 /* could be an expression i.e computed goto :-) */
3539 if (parser->tok != '(') {
3540 parseerror(parser, "expected label name after `goto`");
3544 /* failed to parse expression for goto */
3545 if (!(expression = parse_expression(parser, false, true)) ||
3546 !(*out = parse_goto_computed(parser, &expression))) {
3547 parseerror(parser, "invalid goto expression");
3548 ast_unref(expression);
3555 /* not computed goto */
3556 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
3557 lbl = parser_find_label(parser, gt->name);
3559 if (!ast_istype(lbl, ast_label)) {
3560 parseerror(parser, "internal error: label is not an ast_label");
3564 ast_goto_set_label(gt, (ast_label*)lbl);
3567 vec_push(parser->gotos, gt);
3569 if (!parser_next(parser) || parser->tok != ';') {
3570 parseerror(parser, "semicolon expected after goto label");
3573 if (!parser_next(parser)) {
3574 parseerror(parser, "parse error after goto");
3578 *out = (ast_expression*)gt;
3582 static bool parse_skipwhite(parser_t *parser)
3585 if (!parser_next(parser))
3587 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
3588 return parser->tok < TOKEN_ERROR;
3591 static bool parse_eol(parser_t *parser)
3593 if (!parse_skipwhite(parser))
3595 return parser->tok == TOKEN_EOL;
3598 static bool parse_pragma_do(parser_t *parser)
3600 if (!parser_next(parser) ||
3601 parser->tok != TOKEN_IDENT ||
3602 strcmp(parser_tokval(parser), "pragma"))
3604 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
3607 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
3608 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
3612 if (!strcmp(parser_tokval(parser), "noref")) {
3613 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
3614 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
3617 parser->noref = !!parser_token(parser)->constval.i;
3618 if (!parse_eol(parser)) {
3619 parseerror(parser, "parse error after `noref` pragma");
3625 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
3632 static bool parse_pragma(parser_t *parser)
3635 parser->lex->flags.preprocessing = true;
3636 parser->lex->flags.mergelines = true;
3637 rv = parse_pragma_do(parser);
3638 if (parser->tok != TOKEN_EOL) {
3639 parseerror(parser, "junk after pragma");
3642 parser->lex->flags.preprocessing = false;
3643 parser->lex->flags.mergelines = false;
3644 if (!parser_next(parser)) {
3645 parseerror(parser, "parse error after pragma");
3651 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
3653 bool noref, is_static;
3655 uint32_t qflags = 0;
3656 ast_value *typevar = NULL;
3657 char *vstring = NULL;
3661 if (parser->tok == TOKEN_IDENT)
3662 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
3664 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
3666 /* local variable */
3668 parseerror(parser, "cannot declare a variable from here");
3671 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3672 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
3675 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, 0, NULL))
3679 else if (parse_qualifiers(parser, !!block, &cvq, &noref, &is_static, &qflags, &vstring))
3681 if (cvq == CV_WRONG)
3683 return parse_variable(parser, block, true, cvq, NULL, noref, is_static, qflags, vstring);
3685 else if (parser->tok == TOKEN_KEYWORD)
3687 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
3692 if (!parser_next(parser)) {
3693 parseerror(parser, "parse error after __builtin_debug_printtype");
3697 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
3699 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
3700 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
3701 if (!parser_next(parser)) {
3702 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
3708 if (!parse_statement(parser, block, out, allow_cases))
3711 con_out("__builtin_debug_printtype: got no output node\n");
3714 ast_type_to_string(*out, ty, sizeof(ty));
3715 con_out("__builtin_debug_printtype: `%s`\n", ty);
3720 else if (!strcmp(parser_tokval(parser), "return"))
3722 return parse_return(parser, block, out);
3724 else if (!strcmp(parser_tokval(parser), "if"))
3726 return parse_if(parser, block, out);
3728 else if (!strcmp(parser_tokval(parser), "while"))
3730 return parse_while(parser, block, out);
3732 else if (!strcmp(parser_tokval(parser), "do"))
3734 return parse_dowhile(parser, block, out);
3736 else if (!strcmp(parser_tokval(parser), "for"))
3738 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
3739 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3742 return parse_for(parser, block, out);
3744 else if (!strcmp(parser_tokval(parser), "break"))
3746 return parse_break_continue(parser, block, out, false);
3748 else if (!strcmp(parser_tokval(parser), "continue"))
3750 return parse_break_continue(parser, block, out, true);
3752 else if (!strcmp(parser_tokval(parser), "switch"))
3754 return parse_switch(parser, block, out);
3756 else if (!strcmp(parser_tokval(parser), "case") ||
3757 !strcmp(parser_tokval(parser), "default"))
3760 parseerror(parser, "unexpected 'case' label");
3765 else if (!strcmp(parser_tokval(parser), "goto"))
3767 return parse_goto(parser, out);
3769 else if (!strcmp(parser_tokval(parser), "typedef"))
3771 if (!parser_next(parser)) {
3772 parseerror(parser, "expected type definition after 'typedef'");
3775 return parse_typedef(parser);
3777 parseerror(parser, "Unexpected keyword: `%s'", parser_tokval(parser));
3780 else if (parser->tok == '{')
3783 inner = parse_block(parser);
3786 *out = (ast_expression*)inner;
3789 else if (parser->tok == ':')
3793 if (!parser_next(parser)) {
3794 parseerror(parser, "expected label name");
3797 if (parser->tok != TOKEN_IDENT) {
3798 parseerror(parser, "label must be an identifier");
3801 label = (ast_label*)parser_find_label(parser, parser_tokval(parser));
3803 if (!label->undefined) {
3804 parseerror(parser, "label `%s` already defined", label->name);
3807 label->undefined = false;
3810 label = ast_label_new(parser_ctx(parser), parser_tokval(parser), false);
3811 vec_push(parser->labels, label);
3813 *out = (ast_expression*)label;
3814 if (!parser_next(parser)) {
3815 parseerror(parser, "parse error after label");
3818 for (i = 0; i < vec_size(parser->gotos); ++i) {
3819 if (!strcmp(parser->gotos[i]->name, label->name)) {
3820 ast_goto_set_label(parser->gotos[i], label);
3821 vec_remove(parser->gotos, i, 1);
3827 else if (parser->tok == ';')
3829 if (!parser_next(parser)) {
3830 parseerror(parser, "parse error after empty statement");
3837 lex_ctx ctx = parser_ctx(parser);
3838 ast_expression *exp = parse_expression(parser, false, false);
3842 if (!ast_side_effects(exp)) {
3843 if (compile_warning(ctx, WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3850 static bool parse_enum(parser_t *parser)
3853 bool reverse = false;
3855 ast_value **values = NULL;
3856 ast_value *var = NULL;
3859 ast_expression *old;
3861 if (!parser_next(parser) || (parser->tok != '{' && parser->tok != ':')) {
3862 parseerror(parser, "expected `{` or `:` after `enum` keyword");
3866 /* enumeration attributes (can add more later) */
3867 if (parser->tok == ':') {
3868 if (!parser_next(parser) || parser->tok != TOKEN_IDENT){
3869 parseerror(parser, "expected `flag` or `reverse` for enumeration attribute");
3874 if (!strcmp(parser_tokval(parser), "flag")) {
3878 else if (!strcmp(parser_tokval(parser), "reverse")) {
3882 parseerror(parser, "invalid attribute `%s` for enumeration", parser_tokval(parser));
3886 if (!parser_next(parser) || parser->tok != '{') {
3887 parseerror(parser, "expected `{` after enum attribute ");
3893 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
3894 if (parser->tok == '}') {
3895 /* allow an empty enum */
3898 parseerror(parser, "expected identifier or `}`");
3902 old = parser_find_field(parser, parser_tokval(parser));
3904 old = parser_find_global(parser, parser_tokval(parser));
3906 parseerror(parser, "value `%s` has already been declared here: %s:%i",
3907 parser_tokval(parser), ast_ctx(old).file, ast_ctx(old).line);
3911 var = ast_value_new(parser_ctx(parser), parser_tokval(parser), TYPE_FLOAT);
3912 vec_push(values, var);
3913 var->cvq = CV_CONST;
3914 var->hasvalue = true;
3916 /* for flagged enumerations increment in POTs of TWO */
3917 var->constval.vfloat = (flag) ? (num *= 2) : (num ++);
3918 parser_addglobal(parser, var->name, (ast_expression*)var);
3920 if (!parser_next(parser)) {
3921 parseerror(parser, "expected `=`, `}` or comma after identifier");
3925 if (parser->tok == ',')
3927 if (parser->tok == '}')
3929 if (parser->tok != '=') {
3930 parseerror(parser, "expected `=`, `}` or comma after identifier");
3934 if (!parser_next(parser)) {
3935 parseerror(parser, "expected expression after `=`");
3939 /* We got a value! */
3940 old = parse_expression_leave(parser, true, false, false);
3941 asvalue = (ast_value*)old;
3942 if (!ast_istype(old, ast_value) || asvalue->cvq != CV_CONST || !asvalue->hasvalue) {
3943 compile_error(ast_ctx(var), "constant value or expression expected");
3946 num = (var->constval.vfloat = asvalue->constval.vfloat) + 1;
3948 if (parser->tok == '}')
3950 if (parser->tok != ',') {
3951 parseerror(parser, "expected `}` or comma after expression");
3956 /* patch them all (for reversed attribute) */
3959 for (i = 0; i < vec_size(values); i++)
3960 values[i]->constval.vfloat = vec_size(values) - i - 1;
3963 if (parser->tok != '}') {
3964 parseerror(parser, "internal error: breaking without `}`");
3968 if (!parser_next(parser) || parser->tok != ';') {
3969 parseerror(parser, "expected semicolon after enumeration");
3973 if (!parser_next(parser)) {
3974 parseerror(parser, "parse error after enumeration");
3986 static bool parse_block_into(parser_t *parser, ast_block *block)
3990 parser_enterblock(parser);
3992 if (!parser_next(parser)) { /* skip the '{' */
3993 parseerror(parser, "expected function body");
3997 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3999 ast_expression *expr = NULL;
4000 if (parser->tok == '}')
4003 if (!parse_statement(parser, block, &expr, false)) {
4004 /* parseerror(parser, "parse error"); */
4010 if (!ast_block_add_expr(block, expr)) {
4017 if (parser->tok != '}') {
4020 (void)parser_next(parser);
4024 if (!parser_leaveblock(parser))
4026 return retval && !!block;
4029 static ast_block* parse_block(parser_t *parser)
4032 block = ast_block_new(parser_ctx(parser));
4035 if (!parse_block_into(parser, block)) {
4036 ast_block_delete(block);
4042 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
4044 if (parser->tok == '{') {
4045 *out = (ast_expression*)parse_block(parser);
4048 return parse_statement(parser, NULL, out, false);
4051 static bool create_vector_members(ast_value *var, ast_member **me)
4054 size_t len = strlen(var->name);
4056 for (i = 0; i < 3; ++i) {
4057 char *name = (char*)mem_a(len+3);
4058 memcpy(name, var->name, len);
4060 name[len+1] = 'x'+i;
4062 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
4071 do { ast_member_delete(me[--i]); } while(i);
4075 static bool parse_function_body(parser_t *parser, ast_value *var)
4077 ast_block *block = NULL;
4082 ast_expression *framenum = NULL;
4083 ast_expression *nextthink = NULL;
4084 /* None of the following have to be deleted */
4085 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
4086 ast_expression *gbl_time = NULL, *gbl_self = NULL;
4087 bool has_frame_think;
4091 has_frame_think = false;
4092 old = parser->function;
4094 if (var->expression.flags & AST_FLAG_ALIAS) {
4095 parseerror(parser, "function aliases cannot have bodies");
4099 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
4100 parseerror(parser, "gotos/labels leaking");
4104 if (!OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4105 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
4106 "variadic function with implementation will not be able to access additional parameters (try -fvariadic-args)"))
4112 if (parser->tok == '[') {
4113 /* got a frame definition: [ framenum, nextthink ]
4114 * this translates to:
4115 * self.frame = framenum;
4116 * self.nextthink = time + 0.1;
4117 * self.think = nextthink;
4121 fld_think = parser_find_field(parser, "think");
4122 fld_nextthink = parser_find_field(parser, "nextthink");
4123 fld_frame = parser_find_field(parser, "frame");
4124 if (!fld_think || !fld_nextthink || !fld_frame) {
4125 parseerror(parser, "cannot use [frame,think] notation without the required fields");
4126 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
4129 gbl_time = parser_find_global(parser, "time");
4130 gbl_self = parser_find_global(parser, "self");
4131 if (!gbl_time || !gbl_self) {
4132 parseerror(parser, "cannot use [frame,think] notation without the required globals");
4133 parseerror(parser, "please declare the following globals: `time`, `self`");
4137 if (!parser_next(parser))
4140 framenum = parse_expression_leave(parser, true, false, false);
4142 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
4145 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
4146 ast_unref(framenum);
4147 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
4151 if (parser->tok != ',') {
4152 ast_unref(framenum);
4153 parseerror(parser, "expected comma after frame number in [frame,think] notation");
4154 parseerror(parser, "Got a %i\n", parser->tok);
4158 if (!parser_next(parser)) {
4159 ast_unref(framenum);
4163 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
4165 /* qc allows the use of not-yet-declared functions here
4166 * - this automatically creates a prototype */
4167 ast_value *thinkfunc;
4168 ast_expression *functype = fld_think->next;
4170 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->vtype);
4171 if (!thinkfunc) { /* || !ast_type_adopt(thinkfunc, functype)*/
4172 ast_unref(framenum);
4173 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
4176 ast_type_adopt(thinkfunc, functype);
4178 if (!parser_next(parser)) {
4179 ast_unref(framenum);
4180 ast_delete(thinkfunc);
4184 parser_addglobal(parser, thinkfunc->name, (ast_expression*)thinkfunc);
4186 nextthink = (ast_expression*)thinkfunc;
4189 nextthink = parse_expression_leave(parser, true, false, false);
4191 ast_unref(framenum);
4192 parseerror(parser, "expected a think-function in [frame,think] notation");
4197 if (!ast_istype(nextthink, ast_value)) {
4198 parseerror(parser, "think-function in [frame,think] notation must be a constant");
4202 if (retval && parser->tok != ']') {
4203 parseerror(parser, "expected closing `]` for [frame,think] notation");
4207 if (retval && !parser_next(parser)) {
4211 if (retval && parser->tok != '{') {
4212 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
4217 ast_unref(nextthink);
4218 ast_unref(framenum);
4222 has_frame_think = true;
4225 block = ast_block_new(parser_ctx(parser));
4227 parseerror(parser, "failed to allocate block");
4228 if (has_frame_think) {
4229 ast_unref(nextthink);
4230 ast_unref(framenum);
4235 if (has_frame_think) {
4237 ast_expression *self_frame;
4238 ast_expression *self_nextthink;
4239 ast_expression *self_think;
4240 ast_expression *time_plus_1;
4241 ast_store *store_frame;
4242 ast_store *store_nextthink;
4243 ast_store *store_think;
4245 ctx = parser_ctx(parser);
4246 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
4247 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
4248 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
4250 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
4251 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
4253 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
4254 if (self_frame) ast_delete(self_frame);
4255 if (self_nextthink) ast_delete(self_nextthink);
4256 if (self_think) ast_delete(self_think);
4257 if (time_plus_1) ast_delete(time_plus_1);
4263 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
4264 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
4265 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
4268 ast_delete(self_frame);
4271 if (!store_nextthink) {
4272 ast_delete(self_nextthink);
4276 ast_delete(self_think);
4280 if (store_frame) ast_delete(store_frame);
4281 if (store_nextthink) ast_delete(store_nextthink);
4282 if (store_think) ast_delete(store_think);
4285 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
4286 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
4287 !ast_block_add_expr(block, (ast_expression*)store_think))
4294 parseerror(parser, "failed to generate code for [frame,think]");
4295 ast_unref(nextthink);
4296 ast_unref(framenum);
4302 if (var->hasvalue) {
4303 parseerror(parser, "function `%s` declared with multiple bodies", var->name);
4304 ast_block_delete(block);
4308 func = ast_function_new(ast_ctx(var), var->name, var);
4310 parseerror(parser, "failed to allocate function for `%s`", var->name);
4311 ast_block_delete(block);
4314 vec_push(parser->functions, func);
4316 parser_enterblock(parser);
4318 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
4320 ast_value *param = var->expression.params[parami];
4323 if (param->expression.vtype != TYPE_VECTOR &&
4324 (param->expression.vtype != TYPE_FIELD ||
4325 param->expression.next->vtype != TYPE_VECTOR))
4330 if (!create_vector_members(param, me)) {
4331 ast_block_delete(block);
4335 for (e = 0; e < 3; ++e) {
4336 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
4337 ast_block_collect(block, (ast_expression*)me[e]);
4341 if (var->argcounter) {
4342 ast_value *argc = ast_value_new(ast_ctx(var), var->argcounter, TYPE_FLOAT);
4343 parser_addlocal(parser, argc->name, (ast_expression*)argc);
4347 if (OPTS_FLAG(VARIADIC_ARGS) && var->expression.flags & AST_FLAG_VARIADIC) {
4349 ast_value *varargs = ast_value_new(ast_ctx(var), "reserved:va_args", TYPE_ARRAY);
4350 varargs->expression.flags |= AST_FLAG_IS_VARARG;
4351 varargs->expression.next = (ast_expression*)ast_value_new(ast_ctx(var), NULL, TYPE_VECTOR);
4352 varargs->expression.count = 0;
4353 util_snprintf(name, sizeof(name), "%s##va##SET", var->name);
4354 if (!parser_create_array_setter_proto(parser, varargs, name)) {
4355 ast_delete(varargs);
4356 ast_block_delete(block);
4359 util_snprintf(name, sizeof(name), "%s##va##GET", var->name);
4360 if (!parser_create_array_getter_proto(parser, varargs, varargs->expression.next, name)) {
4361 ast_delete(varargs);
4362 ast_block_delete(block);
4365 func->varargs = varargs;
4367 func->fixedparams = parser_const_float(parser, vec_size(var->expression.params));
4370 parser->function = func;
4371 if (!parse_block_into(parser, block)) {
4372 ast_block_delete(block);
4376 vec_push(func->blocks, block);
4379 parser->function = old;
4380 if (!parser_leaveblock(parser))
4382 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
4383 parseerror(parser, "internal error: local scopes left");
4387 if (parser->tok == ';')
4388 return parser_next(parser);
4389 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4390 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
4394 (void)!parser_leaveblock(parser);
4395 vec_pop(parser->functions);
4396 ast_function_delete(func);
4397 var->constval.vfunc = NULL;
4400 parser->function = old;
4404 static ast_expression *array_accessor_split(
4409 ast_expression *left,
4410 ast_expression *right
4416 lex_ctx ctx = ast_ctx(array);
4418 if (!left || !right) {
4419 if (left) ast_delete(left);
4420 if (right) ast_delete(right);
4424 cmp = ast_binary_new(ctx, INSTR_LT,
4425 (ast_expression*)index,
4426 (ast_expression*)parser_const_float(parser, middle));
4430 parseerror(parser, "internal error: failed to create comparison for array setter");
4434 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
4436 ast_delete(cmp); /* will delete left and right */
4437 parseerror(parser, "internal error: failed to create conditional jump for array setter");
4441 return (ast_expression*)ifthen;
4444 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
4446 lex_ctx ctx = ast_ctx(array);
4448 if (from+1 == afterend) {
4449 /* set this value */
4452 ast_array_index *subscript;
4454 int assignop = type_store_instr[value->expression.vtype];
4456 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4457 assignop = INSTR_STORE_V;
4459 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4463 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
4465 ast_delete(subscript);
4469 block = ast_block_new(ctx);
4475 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4480 ret = ast_return_new(ctx, NULL);
4486 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4491 return (ast_expression*)block;
4493 ast_expression *left, *right;
4494 size_t diff = afterend - from;
4495 size_t middle = from + diff/2;
4496 left = array_setter_node(parser, array, index, value, from, middle);
4497 right = array_setter_node(parser, array, index, value, middle, afterend);
4498 return array_accessor_split(parser, array, index, middle, left, right);
4502 static ast_expression *array_field_setter_node(
4511 lex_ctx ctx = ast_ctx(array);
4513 if (from+1 == afterend) {
4514 /* set this value */
4517 ast_entfield *entfield;
4518 ast_array_index *subscript;
4520 int assignop = type_storep_instr[value->expression.vtype];
4522 if (value->expression.vtype == TYPE_FIELD && value->expression.next->vtype == TYPE_VECTOR)
4523 assignop = INSTR_STOREP_V;
4525 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4529 subscript->expression.next = ast_type_copy(ast_ctx(subscript), (ast_expression*)subscript);
4530 subscript->expression.vtype = TYPE_FIELD;
4532 entfield = ast_entfield_new_force(ctx,
4533 (ast_expression*)entity,
4534 (ast_expression*)subscript,
4535 (ast_expression*)subscript);
4537 ast_delete(subscript);
4541 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
4543 ast_delete(entfield);
4547 block = ast_block_new(ctx);
4553 if (!ast_block_add_expr(block, (ast_expression*)st)) {
4558 ret = ast_return_new(ctx, NULL);
4564 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
4569 return (ast_expression*)block;
4571 ast_expression *left, *right;
4572 size_t diff = afterend - from;
4573 size_t middle = from + diff/2;
4574 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
4575 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
4576 return array_accessor_split(parser, array, index, middle, left, right);
4580 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
4582 lex_ctx ctx = ast_ctx(array);
4584 if (from+1 == afterend) {
4586 ast_array_index *subscript;
4588 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
4592 ret = ast_return_new(ctx, (ast_expression*)subscript);
4594 ast_delete(subscript);
4598 return (ast_expression*)ret;
4600 ast_expression *left, *right;
4601 size_t diff = afterend - from;
4602 size_t middle = from + diff/2;
4603 left = array_getter_node(parser, array, index, from, middle);
4604 right = array_getter_node(parser, array, index, middle, afterend);
4605 return array_accessor_split(parser, array, index, middle, left, right);
4609 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
4611 ast_function *func = NULL;
4612 ast_value *fval = NULL;
4613 ast_block *body = NULL;
4615 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
4617 parseerror(parser, "failed to create accessor function value");
4621 func = ast_function_new(ast_ctx(array), funcname, fval);
4624 parseerror(parser, "failed to create accessor function node");
4628 body = ast_block_new(ast_ctx(array));
4630 parseerror(parser, "failed to create block for array accessor");
4636 vec_push(func->blocks, body);
4639 vec_push(parser->accessors, fval);
4644 static ast_value* parser_create_array_setter_proto(parser_t *parser, ast_value *array, const char *funcname)
4646 ast_value *index = NULL;
4647 ast_value *value = NULL;
4651 if (!ast_istype(array->expression.next, ast_value)) {
4652 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4656 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4658 func = fval->constval.vfunc;
4659 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4661 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4662 value = ast_value_copy((ast_value*)array->expression.next);
4664 if (!index || !value) {
4665 parseerror(parser, "failed to create locals for array accessor");
4668 (void)!ast_value_set_name(value, "value"); /* not important */
4669 vec_push(fval->expression.params, index);
4670 vec_push(fval->expression.params, value);
4672 array->setter = fval;
4675 if (index) ast_delete(index);
4676 if (value) ast_delete(value);
4682 static bool parser_create_array_setter_impl(parser_t *parser, ast_value *array)
4684 ast_expression *root = NULL;
4685 root = array_setter_node(parser, array,
4686 array->setter->expression.params[0],
4687 array->setter->expression.params[1],
4688 0, array->expression.count);
4690 parseerror(parser, "failed to build accessor search tree");
4693 if (!ast_block_add_expr(array->setter->constval.vfunc->blocks[0], root)) {
4700 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
4702 if (!parser_create_array_setter_proto(parser, array, funcname))
4704 return parser_create_array_setter_impl(parser, array);
4707 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
4709 ast_expression *root = NULL;
4710 ast_value *entity = NULL;
4711 ast_value *index = NULL;
4712 ast_value *value = NULL;
4716 if (!ast_istype(array->expression.next, ast_value)) {
4717 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4721 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4723 func = fval->constval.vfunc;
4724 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
4726 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
4727 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4728 value = ast_value_copy((ast_value*)array->expression.next);
4729 if (!entity || !index || !value) {
4730 parseerror(parser, "failed to create locals for array accessor");
4733 (void)!ast_value_set_name(value, "value"); /* not important */
4734 vec_push(fval->expression.params, entity);
4735 vec_push(fval->expression.params, index);
4736 vec_push(fval->expression.params, value);
4738 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
4740 parseerror(parser, "failed to build accessor search tree");
4744 array->setter = fval;
4745 return ast_block_add_expr(func->blocks[0], root);
4747 if (entity) ast_delete(entity);
4748 if (index) ast_delete(index);
4749 if (value) ast_delete(value);
4750 if (root) ast_delete(root);
4756 static ast_value* parser_create_array_getter_proto(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4758 ast_value *index = NULL;
4762 /* NOTE: checking array->expression.next rather than elemtype since
4763 * for fields elemtype is a temporary fieldtype.
4765 if (!ast_istype(array->expression.next, ast_value)) {
4766 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
4770 if (!parser_create_array_accessor(parser, array, funcname, &fval))
4772 func = fval->constval.vfunc;
4773 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
4775 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
4778 parseerror(parser, "failed to create locals for array accessor");
4781 vec_push(fval->expression.params, index);
4783 array->getter = fval;
4786 if (index) ast_delete(index);
4792 static bool parser_create_array_getter_impl(parser_t *parser, ast_value *array)
4794 ast_expression *root = NULL;
4796 root = array_getter_node(parser, array, array->getter->expression.params[0], 0, array->expression.count);
4798 parseerror(parser, "failed to build accessor search tree");
4801 if (!ast_block_add_expr(array->getter->constval.vfunc->blocks[0], root)) {
4808 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
4810 if (!parser_create_array_getter_proto(parser, array, elemtype, funcname))
4812 return parser_create_array_getter_impl(parser, array);
4815 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
4816 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
4824 bool variadic = false;
4825 ast_value *varparam = NULL;
4826 char *argcounter = NULL;
4828 ctx = parser_ctx(parser);
4830 /* for the sake of less code we parse-in in this function */
4831 if (!parser_next(parser)) {
4833 parseerror(parser, "expected parameter list");
4839 /* parse variables until we hit a closing paren */
4840 while (parser->tok != ')') {
4842 /* there must be commas between them */
4843 if (parser->tok != ',') {
4844 parseerror(parser, "expected comma or end of parameter list");
4847 if (!parser_next(parser)) {
4848 parseerror(parser, "expected parameter");
4854 if (parser->tok == TOKEN_DOTS) {
4855 /* '...' indicates a varargs function */
4857 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4858 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4861 if (parser->tok == TOKEN_IDENT) {
4862 argcounter = util_strdup(parser_tokval(parser));
4863 if (!parser_next(parser) || parser->tok != ')') {
4864 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4871 /* for anything else just parse a typename */
4872 param = parse_typename(parser, NULL, NULL);
4875 vec_push(params, param);
4876 if (param->expression.vtype >= TYPE_VARIANT) {
4877 char tname[1024]; /* typename is reserved in C++ */
4878 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
4879 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
4882 /* type-restricted varargs */
4883 if (parser->tok == TOKEN_DOTS) {
4885 varparam = vec_last(params);
4887 if (!parser_next(parser) || (parser->tok != ')' && parser->tok != TOKEN_IDENT)) {
4888 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4891 if (parser->tok == TOKEN_IDENT) {
4892 argcounter = util_strdup(parser_tokval(parser));
4893 if (!parser_next(parser) || parser->tok != ')') {
4894 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
4902 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
4906 if (vec_size(params) > 8 && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
4907 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
4910 if (!parser_next(parser)) {
4911 parseerror(parser, "parse error after typename");
4915 /* now turn 'var' into a function type */
4916 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
4917 fval->expression.next = (ast_expression*)var;
4919 fval->expression.flags |= AST_FLAG_VARIADIC;
4922 var->expression.params = params;
4923 var->expression.varparam = (ast_expression*)varparam;
4924 var->argcounter = argcounter;
4933 ast_delete(varparam);
4935 for (i = 0; i < vec_size(params); ++i)
4936 ast_delete(params[i]);
4941 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
4943 ast_expression *cexp;
4944 ast_value *cval, *tmp;
4947 ctx = parser_ctx(parser);
4949 if (!parser_next(parser)) {
4951 parseerror(parser, "expected array-size");
4955 if (parser->tok != ']') {
4956 cexp = parse_expression_leave(parser, true, false, false);
4958 if (!cexp || !ast_istype(cexp, ast_value)) {
4962 parseerror(parser, "expected array-size as constant positive integer");
4965 cval = (ast_value*)cexp;
4972 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
4973 tmp->expression.next = (ast_expression*)var;
4977 if (cval->expression.vtype == TYPE_INTEGER)
4978 tmp->expression.count = cval->constval.vint;
4979 else if (cval->expression.vtype == TYPE_FLOAT)
4980 tmp->expression.count = cval->constval.vfloat;
4984 parseerror(parser, "array-size must be a positive integer constant");
4990 var->expression.count = -1;
4991 var->expression.flags |= AST_FLAG_ARRAY_INIT;
4994 if (parser->tok != ']') {
4996 parseerror(parser, "expected ']' after array-size");
4999 if (!parser_next(parser)) {
5001 parseerror(parser, "error after parsing array size");
5007 /* Parse a complete typename.
5008 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
5009 * but when parsing variables separated by comma
5010 * 'storebase' should point to where the base-type should be kept.
5011 * The base type makes up every bit of type information which comes *before* the
5014 * The following will be parsed in its entirety:
5016 * The 'basetype' in this case is 'void()'
5017 * and if there's a comma after it, say:
5019 * then the type-information 'void()' can be stored in 'storebase'
5021 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
5023 ast_value *var, *tmp;
5026 const char *name = NULL;
5027 bool isfield = false;
5028 bool wasarray = false;
5029 size_t morefields = 0;
5031 ctx = parser_ctx(parser);
5033 /* types may start with a dot */
5034 if (parser->tok == '.') {
5036 /* if we parsed a dot we need a typename now */
5037 if (!parser_next(parser)) {
5038 parseerror(parser, "expected typename for field definition");
5042 /* Further dots are handled seperately because they won't be part of the
5045 while (parser->tok == '.') {
5047 if (!parser_next(parser)) {
5048 parseerror(parser, "expected typename for field definition");
5053 if (parser->tok == TOKEN_IDENT)
5054 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
5055 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
5056 parseerror(parser, "expected typename");
5060 /* generate the basic type value */
5061 if (cached_typedef) {
5062 var = ast_value_copy(cached_typedef);
5063 ast_value_set_name(var, "<type(from_def)>");
5065 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
5067 for (; morefields; --morefields) {
5068 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
5069 tmp->expression.next = (ast_expression*)var;
5073 /* do not yet turn into a field - remember:
5074 * .void() foo; is a field too
5075 * .void()() foo; is a function
5079 if (!parser_next(parser)) {
5081 parseerror(parser, "parse error after typename");
5085 /* an opening paren now starts the parameter-list of a function
5086 * this is where original-QC has parameter lists.
5087 * We allow a single parameter list here.
5088 * Much like fteqcc we don't allow `float()() x`
5090 if (parser->tok == '(') {
5091 var = parse_parameter_list(parser, var);
5096 /* store the base if requested */
5098 *storebase = ast_value_copy(var);
5100 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5101 tmp->expression.next = (ast_expression*)*storebase;
5106 /* there may be a name now */
5107 if (parser->tok == TOKEN_IDENT) {
5108 name = util_strdup(parser_tokval(parser));
5110 if (!parser_next(parser)) {
5113 parseerror(parser, "error after variable or field declaration");
5118 /* now this may be an array */
5119 if (parser->tok == '[') {
5121 var = parse_arraysize(parser, var);
5123 if (name) mem_d(name);
5128 /* This is the point where we can turn it into a field */
5130 /* turn it into a field if desired */
5131 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
5132 tmp->expression.next = (ast_expression*)var;
5136 /* now there may be function parens again */
5137 if (parser->tok == '(' && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5138 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5139 if (parser->tok == '(' && wasarray)
5140 parseerror(parser, "arrays as part of a return type is not supported");
5141 while (parser->tok == '(') {
5142 var = parse_parameter_list(parser, var);
5144 if (name) mem_d(name);
5149 /* finally name it */
5151 if (!ast_value_set_name(var, name)) {
5154 parseerror(parser, "internal error: failed to set name");
5157 /* free the name, ast_value_set_name duplicates */
5164 static bool parse_typedef(parser_t *parser)
5166 ast_value *typevar, *oldtype;
5167 ast_expression *old;
5169 typevar = parse_typename(parser, NULL, NULL);
5174 if ( (old = parser_find_var(parser, typevar->name)) ) {
5175 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
5176 " -> `%s` has been declared here: %s:%i",
5177 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
5178 ast_delete(typevar);
5182 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
5183 parseerror(parser, "type `%s` has already been declared here: %s:%i",
5184 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
5185 ast_delete(typevar);
5189 vec_push(parser->_typedefs, typevar);
5190 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
5192 if (parser->tok != ';') {
5193 parseerror(parser, "expected semicolon after typedef");
5196 if (!parser_next(parser)) {
5197 parseerror(parser, "parse error after typedef");
5204 static const char *cvq_to_str(int cvq) {
5206 case CV_NONE: return "none";
5207 case CV_VAR: return "`var`";
5208 case CV_CONST: return "`const`";
5209 default: return "<INVALID>";
5213 static bool parser_check_qualifiers(parser_t *parser, const ast_value *var, const ast_value *proto)
5216 if (proto->cvq != var->cvq) {
5217 if (!(proto->cvq == CV_CONST && var->cvq == CV_NONE &&
5218 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5219 parser->tok == '='))
5221 return !parsewarning(parser, WARN_DIFFERENT_QUALIFIERS,
5222 "`%s` declared with different qualifiers: %s\n"
5223 " -> previous declaration here: %s:%i uses %s",
5224 var->name, cvq_to_str(var->cvq),
5225 ast_ctx(proto).file, ast_ctx(proto).line,
5226 cvq_to_str(proto->cvq));
5229 av = (var ->expression.flags & AST_FLAG_NORETURN);
5230 ao = (proto->expression.flags & AST_FLAG_NORETURN);
5232 return !parsewarning(parser, WARN_DIFFERENT_ATTRIBUTES,
5233 "`%s` declared with different attributes%s\n"
5234 " -> previous declaration here: %s:%i",
5235 var->name, (av ? ": noreturn" : ""),
5236 ast_ctx(proto).file, ast_ctx(proto).line,
5237 (ao ? ": noreturn" : ""));
5242 static bool create_array_accessors(parser_t *parser, ast_value *var)
5245 util_snprintf(name, sizeof(name), "%s##SET", var->name);
5246 if (!parser_create_array_setter(parser, var, name))
5248 util_snprintf(name, sizeof(name), "%s##GET", var->name);
5249 if (!parser_create_array_getter(parser, var, var->expression.next, name))
5254 static bool parse_array(parser_t *parser, ast_value *array)
5257 if (array->initlist) {
5258 parseerror(parser, "array already initialized elsewhere");
5261 if (!parser_next(parser)) {
5262 parseerror(parser, "parse error in array initializer");
5266 while (parser->tok != '}') {
5267 ast_value *v = (ast_value*)parse_expression_leave(parser, true, false, false);
5270 if (!ast_istype(v, ast_value) || !v->hasvalue || v->cvq != CV_CONST) {
5272 parseerror(parser, "initializing element must be a compile time constant");
5275 vec_push(array->initlist, v->constval);
5276 if (v->expression.vtype == TYPE_STRING) {
5277 array->initlist[i].vstring = util_strdupe(array->initlist[i].vstring);
5281 if (parser->tok == '}')
5283 if (parser->tok != ',' || !parser_next(parser)) {
5284 parseerror(parser, "expected comma or '}' in element list");
5288 if (!parser_next(parser) || parser->tok != ';') {
5289 parseerror(parser, "expected semicolon after initializer, got %s");
5293 if (!parser_next(parser)) {
5294 parseerror(parser, "parse error after initializer");
5299 if (array->expression.flags & AST_FLAG_ARRAY_INIT) {
5300 if (array->expression.count != (size_t)-1) {
5301 parseerror(parser, "array `%s' has already been initialized with %u elements",
5302 array->name, (unsigned)array->expression.count);
5304 array->expression.count = vec_size(array->initlist);
5305 if (!create_array_accessors(parser, array))
5311 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)
5315 ast_expression *old;
5319 ast_value *basetype = NULL;
5321 bool isparam = false;
5322 bool isvector = false;
5323 bool cleanvar = true;
5324 bool wasarray = false;
5326 ast_member *me[3] = { NULL, NULL, NULL };
5328 if (!localblock && is_static)
5329 parseerror(parser, "`static` qualifier is not supported in global scope");
5331 /* get the first complete variable */
5332 var = parse_typename(parser, &basetype, cached_typedef);
5335 ast_delete(basetype);
5343 /* Part 0: finish the type */
5344 if (parser->tok == '(') {
5345 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5346 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5347 var = parse_parameter_list(parser, var);
5353 /* we only allow 1-dimensional arrays */
5354 if (parser->tok == '[') {
5356 var = parse_arraysize(parser, var);
5362 if (parser->tok == '(' && wasarray) {
5363 parseerror(parser, "arrays as part of a return type is not supported");
5364 /* we'll still parse the type completely for now */
5366 /* for functions returning functions */
5367 while (parser->tok == '(') {
5368 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC)
5369 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
5370 var = parse_parameter_list(parser, var);
5377 var->cvq = qualifier;
5378 var->expression.flags |= qflags;
5381 * store the vstring back to var for alias and
5382 * deprecation messages.
5384 if (var->expression.flags & AST_FLAG_DEPRECATED ||
5385 var->expression.flags & AST_FLAG_ALIAS)
5386 var->desc = vstring;
5389 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
5390 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
5391 * is then filled with the previous definition and the parameter-names replaced.
5393 if (!strcmp(var->name, "nil")) {
5394 if (OPTS_FLAG(UNTYPED_NIL)) {
5395 if (!localblock || !OPTS_FLAG(PERMISSIVE))
5396 parseerror(parser, "name `nil` not allowed (try -fpermissive)");
5398 (void)!parsewarning(parser, WARN_RESERVED_NAMES, "variable name `nil` is reserved");
5401 /* Deal with end_sys_ vars */
5403 if (!strcmp(var->name, "end_sys_globals")) {
5405 parser->crc_globals = vec_size(parser->globals);
5408 else if (!strcmp(var->name, "end_sys_fields")) {
5410 parser->crc_fields = vec_size(parser->fields);
5413 if (was_end && var->expression.vtype == TYPE_FIELD) {
5414 if (parsewarning(parser, WARN_END_SYS_FIELDS,
5415 "global '%s' hint should not be a field",
5416 parser_tokval(parser)))
5423 if (!nofields && var->expression.vtype == TYPE_FIELD)
5425 /* deal with field declarations */
5426 old = parser_find_field(parser, var->name);
5428 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
5429 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
5438 parseerror(parser, "field `%s` already declared here: %s:%i",
5439 var->name, ast_ctx(old).file, ast_ctx(old).line);
5444 if ((OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC || OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_FTEQCC) &&
5445 (old = parser_find_global(parser, var->name)))
5447 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5448 parseerror(parser, "field `%s` already declared here: %s:%i",
5449 var->name, ast_ctx(old).file, ast_ctx(old).line);
5456 /* deal with other globals */
5457 old = parser_find_global(parser, var->name);
5458 if (old && var->expression.vtype == TYPE_FUNCTION && old->vtype == TYPE_FUNCTION)
5460 /* This is a function which had a prototype */
5461 if (!ast_istype(old, ast_value)) {
5462 parseerror(parser, "internal error: prototype is not an ast_value");
5466 proto = (ast_value*)old;
5467 proto->desc = var->desc;
5468 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
5469 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
5471 ast_ctx(proto).file, ast_ctx(proto).line);
5475 /* we need the new parameter-names */
5476 for (i = 0; i < vec_size(proto->expression.params); ++i)
5477 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
5478 if (!parser_check_qualifiers(parser, var, proto)) {
5485 proto->expression.flags |= var->expression.flags;
5493 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
5494 "global `%s` already declared here: %s:%i",
5495 var->name, ast_ctx(old).file, ast_ctx(old).line))
5500 proto = (ast_value*)old;
5501 if (!ast_istype(old, ast_value)) {
5502 parseerror(parser, "internal error: not an ast_value");
5507 if (!parser_check_qualifiers(parser, var, proto)) {
5512 proto->expression.flags |= var->expression.flags;
5516 if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC &&
5517 (old = parser_find_field(parser, var->name)))
5519 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
5520 parseerror(parser, "global `%s` already declared here: %s:%i",
5521 var->name, ast_ctx(old).file, ast_ctx(old).line);
5528 else /* it's not a global */
5530 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
5531 if (old && !isparam) {
5532 parseerror(parser, "local `%s` already declared here: %s:%i",
5533 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5537 old = parser_find_local(parser, var->name, 0, &isparam);
5538 if (old && isparam) {
5539 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
5540 "local `%s` is shadowing a parameter", var->name))
5542 parseerror(parser, "local `%s` already declared here: %s:%i",
5543 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
5547 if (OPTS_OPTION_U32(OPTION_STANDARD) != COMPILER_GMQCC) {
5555 /* in a noref section we simply bump the usecount */
5556 if (noref || parser->noref)
5560 * Create the global/local, and deal with vector types.
5563 if (var->expression.vtype == TYPE_VECTOR)
5565 else if (var->expression.vtype == TYPE_FIELD &&
5566 var->expression.next->vtype == TYPE_VECTOR)
5570 if (!create_vector_members(var, me)) {
5577 /* deal with global variables, fields, functions */
5578 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
5579 var->isfield = true;
5580 vec_push(parser->fields, (ast_expression*)var);
5581 util_htset(parser->htfields, var->name, var);
5583 for (i = 0; i < 3; ++i) {
5584 vec_push(parser->fields, (ast_expression*)me[i]);
5585 util_htset(parser->htfields, me[i]->name, me[i]);
5590 if (!(var->expression.flags & AST_FLAG_ALIAS)) {
5591 parser_addglobal(parser, var->name, (ast_expression*)var);
5593 for (i = 0; i < 3; ++i) {
5594 parser_addglobal(parser, me[i]->name, (ast_expression*)me[i]);
5598 ast_expression *find = parser_find_global(parser, var->desc);
5601 compile_error(parser_ctx(parser), "undeclared variable `%s` for alias `%s`", var->desc, var->name);
5605 if (var->expression.vtype != find->vtype) {
5609 ast_type_to_string(find, ty1, sizeof(ty1));
5610 ast_type_to_string((ast_expression*)var, ty2, sizeof(ty2));
5612 compile_error(parser_ctx(parser), "incompatible types `%s` and `%s` for alias `%s`",
5619 * add alias to aliases table and to corrector
5620 * so corrections can apply for aliases as well.
5622 util_htset(parser->aliases, var->name, find);
5625 * add to corrector so corrections can work
5626 * even for aliases too.
5629 vec_last(parser->correct_variables),
5630 &vec_last(parser->correct_variables_score),
5634 /* generate aliases for vector components */
5638 util_asprintf(&buffer[0], "%s_x", var->desc);
5639 util_asprintf(&buffer[1], "%s_y", var->desc);
5640 util_asprintf(&buffer[2], "%s_z", var->desc);
5642 util_htset(parser->aliases, me[0]->name, parser_find_global(parser, buffer[0]));
5643 util_htset(parser->aliases, me[1]->name, parser_find_global(parser, buffer[1]));
5644 util_htset(parser->aliases, me[2]->name, parser_find_global(parser, buffer[2]));
5651 * add to corrector so corrections can work
5652 * even for aliases too.
5655 vec_last(parser->correct_variables),
5656 &vec_last(parser->correct_variables_score),
5660 vec_last(parser->correct_variables),
5661 &vec_last(parser->correct_variables_score),
5665 vec_last(parser->correct_variables),
5666 &vec_last(parser->correct_variables_score),
5674 /* a static adds itself to be generated like any other global
5675 * but is added to the local namespace instead
5677 char *defname = NULL;
5678 size_t prefix_len, ln;
5680 ln = strlen(parser->function->name);
5681 vec_append(defname, ln, parser->function->name);
5683 vec_append(defname, 2, "::");
5684 /* remember the length up to here */
5685 prefix_len = vec_size(defname);
5687 /* Add it to the local scope */
5688 util_htset(vec_last(parser->variables), var->name, (void*)var);
5692 vec_last(parser->correct_variables),
5693 &vec_last(parser->correct_variables_score),
5697 /* now rename the global */
5698 ln = strlen(var->name);
5699 vec_append(defname, ln, var->name);
5700 ast_value_set_name(var, defname);
5702 /* push it to the to-be-generated globals */
5703 vec_push(parser->globals, (ast_expression*)var);
5705 /* same game for the vector members */
5707 for (i = 0; i < 3; ++i) {
5708 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
5712 vec_last(parser->correct_variables),
5713 &vec_last(parser->correct_variables_score),
5717 vec_shrinkto(defname, prefix_len);
5718 ln = strlen(me[i]->name);
5719 vec_append(defname, ln, me[i]->name);
5720 ast_member_set_name(me[i], defname);
5722 vec_push(parser->globals, (ast_expression*)me[i]);
5727 vec_push(localblock->locals, var);
5728 parser_addlocal(parser, var->name, (ast_expression*)var);
5730 for (i = 0; i < 3; ++i) {
5731 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
5732 ast_block_collect(localblock, (ast_expression*)me[i]);
5738 me[0] = me[1] = me[2] = NULL;
5743 if (var->expression.vtype == TYPE_ARRAY) {
5744 if (var->expression.count != (size_t)-1) {
5745 if (!create_array_accessors(parser, var))
5749 else if (!localblock && !nofields &&
5750 var->expression.vtype == TYPE_FIELD &&
5751 var->expression.next->vtype == TYPE_ARRAY)
5754 ast_expression *telem;
5756 ast_value *array = (ast_value*)var->expression.next;
5758 if (!ast_istype(var->expression.next, ast_value)) {
5759 parseerror(parser, "internal error: field element type must be an ast_value");
5763 util_snprintf(name, sizeof(name), "%s##SETF", var->name);
5764 if (!parser_create_array_field_setter(parser, array, name))
5767 telem = ast_type_copy(ast_ctx(var), array->expression.next);
5768 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
5769 tfield->expression.next = telem;
5770 util_snprintf(name, sizeof(name), "%s##GETFP", var->name);
5771 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
5779 if (parser->tok == ';') {
5780 ast_delete(basetype);
5781 if (!parser_next(parser)) {
5782 parseerror(parser, "error after variable declaration");
5788 if (parser->tok == ',')
5792 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
5795 parseerror(parser, "missing comma or semicolon while parsing variables");
5799 if (localblock && OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5800 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
5801 "initializing expression turns variable `%s` into a constant in this standard",
5808 if (parser->tok != '{' || var->expression.vtype != TYPE_FUNCTION) {
5809 if (parser->tok != '=') {
5810 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
5814 if (!parser_next(parser)) {
5815 parseerror(parser, "error parsing initializer");
5819 else if (OPTS_OPTION_U32(OPTION_STANDARD) == COMPILER_QCC) {
5820 parseerror(parser, "expected '=' before function body in this standard");
5823 if (parser->tok == '#') {
5824 ast_function *func = NULL;
5825 ast_value *number = NULL;
5831 parseerror(parser, "cannot declare builtins within functions");
5834 if (var->expression.vtype != TYPE_FUNCTION) {
5835 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
5838 if (!parser_next(parser)) {
5839 parseerror(parser, "expected builtin number");
5843 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)) {
5844 number = (ast_value*)parse_expression_leave(parser, true, false, false);
5846 parseerror(parser, "builtin number expected");
5849 if (!ast_istype(number, ast_value) || !number->hasvalue || number->cvq != CV_CONST)
5852 parseerror(parser, "builtin number must be a compile time constant");
5855 if (number->expression.vtype == TYPE_INTEGER)
5856 builtin_num = number->constval.vint;
5857 else if (number->expression.vtype == TYPE_FLOAT)
5858 builtin_num = number->constval.vfloat;
5861 parseerror(parser, "builtin number must be an integer constant");
5866 fractional = modff(builtin_num, &integral);
5867 if (builtin_num < 0 || fractional != 0) {
5868 parseerror(parser, "builtin number must be an integer greater than zero");
5872 /* we only want the integral part anyways */
5873 builtin_num = integral;
5874 } else if (parser->tok == TOKEN_INTCONST) {
5875 builtin_num = parser_token(parser)->constval.i;
5877 parseerror(parser, "builtin number must be a compile time constant");
5881 if (var->hasvalue) {
5882 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
5883 "builtin `%s` has already been defined\n"
5884 " -> previous declaration here: %s:%i",
5885 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
5889 func = ast_function_new(ast_ctx(var), var->name, var);
5891 parseerror(parser, "failed to allocate function for `%s`", var->name);
5894 vec_push(parser->functions, func);
5896 func->builtin = -builtin_num-1;
5899 if (OPTS_FLAG(EXPRESSIONS_FOR_BUILTINS)
5900 ? (parser->tok != ',' && parser->tok != ';')
5901 : (!parser_next(parser)))
5903 parseerror(parser, "expected comma or semicolon");
5905 ast_function_delete(func);
5906 var->constval.vfunc = NULL;
5910 else if (var->expression.vtype == TYPE_ARRAY && parser->tok == '{')
5913 /* Note that fteqcc and most others don't even *have*
5914 * local arrays, so this is not a high priority.
5916 parseerror(parser, "TODO: initializers for local arrays");
5920 var->hasvalue = true;
5921 if (!parse_array(parser, var))
5924 else if (var->expression.vtype == TYPE_FUNCTION && (parser->tok == '{' || parser->tok == '['))
5927 parseerror(parser, "cannot declare functions within functions");
5932 ast_ctx(proto) = parser_ctx(parser);
5934 if (!parse_function_body(parser, var))
5936 ast_delete(basetype);
5937 for (i = 0; i < vec_size(parser->gotos); ++i)
5938 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
5939 vec_free(parser->gotos);
5940 vec_free(parser->labels);
5943 ast_expression *cexp;
5946 cexp = parse_expression_leave(parser, true, false, false);
5951 cval = (ast_value*)cexp;
5952 if (cval != parser->nil &&
5953 (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
5956 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
5960 if (!OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
5961 qualifier != CV_VAR)
5963 var->cvq = CV_CONST;
5965 if (cval == parser->nil)
5966 var->expression.flags |= AST_FLAG_INITIALIZED;
5969 var->hasvalue = true;
5970 if (cval->expression.vtype == TYPE_STRING)
5971 var->constval.vstring = parser_strdup(cval->constval.vstring);
5972 else if (cval->expression.vtype == TYPE_FIELD)
5973 var->constval.vfield = cval;
5975 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
5981 shunt sy = { NULL, NULL, NULL, NULL };
5984 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
5985 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
5986 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
5987 if (!parser_sy_apply_operator(parser, &sy))
5990 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
5991 parseerror(parser, "internal error: leaked operands");
5992 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
6003 if (parser->tok == ',') {
6004 if (!parser_next(parser)) {
6005 parseerror(parser, "expected another variable");
6009 if (parser->tok != TOKEN_IDENT) {
6010 parseerror(parser, "expected another variable");
6013 var = ast_value_copy(basetype);
6015 ast_value_set_name(var, parser_tokval(parser));
6016 if (!parser_next(parser)) {
6017 parseerror(parser, "error parsing variable declaration");
6023 if (parser->tok != ';') {
6024 parseerror(parser, "missing semicolon after variables");
6028 if (!parser_next(parser)) {
6029 parseerror(parser, "parse error after variable declaration");
6033 ast_delete(basetype);
6037 if (cleanvar && var)
6039 ast_delete(basetype);
6043 ast_delete(basetype);
6044 if (cleanvar && var)
6046 if (me[0]) ast_member_delete(me[0]);
6047 if (me[1]) ast_member_delete(me[1]);
6048 if (me[2]) ast_member_delete(me[2]);
6052 static bool parser_global_statement(parser_t *parser)
6056 bool is_static = false;
6057 uint32_t qflags = 0;
6058 ast_value *istype = NULL;
6059 char *vstring = NULL;
6061 if (parser->tok == TOKEN_IDENT)
6062 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
6064 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
6066 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, 0, NULL);
6068 else if (parse_qualifiers(parser, false, &cvq, &noref, &is_static, &qflags, &vstring))
6070 if (cvq == CV_WRONG)
6072 return parse_variable(parser, NULL, true, cvq, NULL, noref, is_static, qflags, vstring);
6074 else if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "enum"))
6076 return parse_enum(parser);
6078 else if (parser->tok == TOKEN_KEYWORD)
6080 if (!strcmp(parser_tokval(parser), "typedef")) {
6081 if (!parser_next(parser)) {
6082 parseerror(parser, "expected type definition after 'typedef'");
6085 return parse_typedef(parser);
6087 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
6090 else if (parser->tok == '#')
6092 return parse_pragma(parser);
6094 else if (parser->tok == '$')
6096 if (!parser_next(parser)) {
6097 parseerror(parser, "parse error");
6103 parseerror(parser, "unexpected token: `%s`", parser->lex->tok.value);
6109 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
6111 return util_crc16(old, str, strlen(str));
6114 static void progdefs_crc_file(const char *str)
6116 /* write to progdefs.h here */
6120 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
6122 old = progdefs_crc_sum(old, str);
6123 progdefs_crc_file(str);
6127 static void generate_checksum(parser_t *parser)
6129 uint16_t crc = 0xFFFF;
6133 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
6134 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
6136 progdefs_crc_file("\tint\tpad;\n");
6137 progdefs_crc_file("\tint\tofs_return[3];\n");
6138 progdefs_crc_file("\tint\tofs_parm0[3];\n");
6139 progdefs_crc_file("\tint\tofs_parm1[3];\n");
6140 progdefs_crc_file("\tint\tofs_parm2[3];\n");
6141 progdefs_crc_file("\tint\tofs_parm3[3];\n");
6142 progdefs_crc_file("\tint\tofs_parm4[3];\n");
6143 progdefs_crc_file("\tint\tofs_parm5[3];\n");
6144 progdefs_crc_file("\tint\tofs_parm6[3];\n");
6145 progdefs_crc_file("\tint\tofs_parm7[3];\n");
6147 for (i = 0; i < parser->crc_globals; ++i) {
6148 if (!ast_istype(parser->globals[i], ast_value))
6150 value = (ast_value*)(parser->globals[i]);
6151 switch (value->expression.vtype) {
6152 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6153 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6154 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6155 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6157 crc = progdefs_crc_both(crc, "\tint\t");
6160 crc = progdefs_crc_both(crc, value->name);
6161 crc = progdefs_crc_both(crc, ";\n");
6163 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
6164 for (i = 0; i < parser->crc_fields; ++i) {
6165 if (!ast_istype(parser->fields[i], ast_value))
6167 value = (ast_value*)(parser->fields[i]);
6168 switch (value->expression.next->vtype) {
6169 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
6170 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
6171 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
6172 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
6174 crc = progdefs_crc_both(crc, "\tint\t");
6177 crc = progdefs_crc_both(crc, value->name);
6178 crc = progdefs_crc_both(crc, ";\n");
6180 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
6182 parser->code->crc = crc;
6185 parser_t *parser_create()
6191 parser = (parser_t*)mem_a(sizeof(parser_t));
6195 memset(parser, 0, sizeof(*parser));
6197 if (!(parser->code = code_init())) {
6202 for (i = 0; i < operator_count; ++i) {
6203 if (operators[i].id == opid1('=')) {
6204 parser->assign_op = operators+i;
6208 if (!parser->assign_op) {
6209 printf("internal error: initializing parser: failed to find assign operator\n");
6214 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
6215 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
6216 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
6217 vec_push(parser->_blocktypedefs, 0);
6219 parser->aliases = util_htnew(PARSER_HT_SIZE);
6221 parser->ht_imm_string = util_htnew(512);
6224 vec_push(parser->correct_variables, correct_trie_new());
6225 vec_push(parser->correct_variables_score, NULL);
6227 empty_ctx.file = "<internal>";
6229 parser->nil = ast_value_new(empty_ctx, "nil", TYPE_NIL);
6230 parser->nil->cvq = CV_CONST;
6231 if (OPTS_FLAG(UNTYPED_NIL))
6232 util_htset(parser->htglobals, "nil", (void*)parser->nil);
6234 parser->max_param_count = 1;
6236 parser->const_vec[0] = ast_value_new(empty_ctx, "<vector.x>", TYPE_NOEXPR);
6237 parser->const_vec[1] = ast_value_new(empty_ctx, "<vector.y>", TYPE_NOEXPR);
6238 parser->const_vec[2] = ast_value_new(empty_ctx, "<vector.z>", TYPE_NOEXPR);
6240 if (OPTS_OPTION_BOOL(OPTION_ADD_INFO)) {
6241 parser->reserved_version = ast_value_new(empty_ctx, "reserved:version", TYPE_STRING);
6242 parser->reserved_version->cvq = CV_CONST;
6243 parser->reserved_version->hasvalue = true;
6244 parser->reserved_version->expression.flags |= AST_FLAG_INCLUDE_DEF;
6245 parser->reserved_version->constval.vstring = util_strdup(GMQCC_FULL_VERSION_STRING);
6247 parser->reserved_version = NULL;
6253 static bool parser_compile(parser_t *parser)
6255 /* initial lexer/parser state */
6256 parser->lex->flags.noops = true;
6258 if (parser_next(parser))
6260 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
6262 if (!parser_global_statement(parser)) {
6263 if (parser->tok == TOKEN_EOF)
6264 parseerror(parser, "unexpected end of file");
6265 else if (compile_errors)
6266 parseerror(parser, "there have been errors, bailing out");
6267 lex_close(parser->lex);
6273 parseerror(parser, "parse error");
6274 lex_close(parser->lex);
6279 lex_close(parser->lex);
6282 return !compile_errors;
6285 bool parser_compile_file(parser_t *parser, const char *filename)
6287 parser->lex = lex_open(filename);
6289 con_err("failed to open file \"%s\"\n", filename);
6292 return parser_compile(parser);
6295 bool parser_compile_string(parser_t *parser, const char *name, const char *str, size_t len)
6297 parser->lex = lex_open_string(str, len, name);
6299 con_err("failed to create lexer for string \"%s\"\n", name);
6302 return parser_compile(parser);
6305 static void parser_remove_ast(parser_t *parser)
6308 if (parser->ast_cleaned)
6310 parser->ast_cleaned = true;
6311 for (i = 0; i < vec_size(parser->accessors); ++i) {
6312 ast_delete(parser->accessors[i]->constval.vfunc);
6313 parser->accessors[i]->constval.vfunc = NULL;
6314 ast_delete(parser->accessors[i]);
6316 for (i = 0; i < vec_size(parser->functions); ++i) {
6317 ast_delete(parser->functions[i]);
6319 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6320 ast_delete(parser->imm_vector[i]);
6322 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6323 ast_delete(parser->imm_string[i]);
6325 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6326 ast_delete(parser->imm_float[i]);
6328 for (i = 0; i < vec_size(parser->fields); ++i) {
6329 ast_delete(parser->fields[i]);
6331 for (i = 0; i < vec_size(parser->globals); ++i) {
6332 ast_delete(parser->globals[i]);
6334 vec_free(parser->accessors);
6335 vec_free(parser->functions);
6336 vec_free(parser->imm_vector);
6337 vec_free(parser->imm_string);
6338 util_htdel(parser->ht_imm_string);
6339 vec_free(parser->imm_float);
6340 vec_free(parser->globals);
6341 vec_free(parser->fields);
6343 for (i = 0; i < vec_size(parser->variables); ++i)
6344 util_htdel(parser->variables[i]);
6345 vec_free(parser->variables);
6346 vec_free(parser->_blocklocals);
6347 vec_free(parser->_locals);
6350 for (i = 0; i < vec_size(parser->correct_variables); ++i) {
6351 correct_del(parser->correct_variables[i], parser->correct_variables_score[i]);
6353 vec_free(parser->correct_variables);
6354 vec_free(parser->correct_variables_score);
6357 for (i = 0; i < vec_size(parser->_typedefs); ++i)
6358 ast_delete(parser->_typedefs[i]);
6359 vec_free(parser->_typedefs);
6360 for (i = 0; i < vec_size(parser->typedefs); ++i)
6361 util_htdel(parser->typedefs[i]);
6362 vec_free(parser->typedefs);
6363 vec_free(parser->_blocktypedefs);
6365 vec_free(parser->_block_ctx);
6367 vec_free(parser->labels);
6368 vec_free(parser->gotos);
6369 vec_free(parser->breaks);
6370 vec_free(parser->continues);
6372 ast_value_delete(parser->nil);
6374 ast_value_delete(parser->const_vec[0]);
6375 ast_value_delete(parser->const_vec[1]);
6376 ast_value_delete(parser->const_vec[2]);
6378 util_htdel(parser->aliases);
6379 intrin_intrinsics_destroy(parser);
6382 void parser_cleanup(parser_t *parser)
6384 parser_remove_ast(parser);
6385 code_cleanup(parser->code);
6390 bool parser_finish(parser_t *parser, const char *output)
6396 if (compile_errors) {
6397 con_out("*** there were compile errors\n");
6401 ir = ir_builder_new("gmqcc_out");
6403 con_out("failed to allocate builder\n");
6407 for (i = 0; i < vec_size(parser->fields); ++i) {
6410 if (!ast_istype(parser->fields[i], ast_value))
6412 field = (ast_value*)parser->fields[i];
6413 hasvalue = field->hasvalue;
6414 field->hasvalue = false;
6415 if (!ast_global_codegen((ast_value*)field, ir, true)) {
6416 con_out("failed to generate field %s\n", field->name);
6417 ir_builder_delete(ir);
6422 ast_expression *subtype;
6423 field->hasvalue = true;
6424 subtype = field->expression.next;
6425 ifld = ir_builder_create_field(ir, field->name, subtype->vtype);
6426 if (subtype->vtype == TYPE_FIELD)
6427 ifld->fieldtype = subtype->next->vtype;
6428 else if (subtype->vtype == TYPE_FUNCTION)
6429 ifld->outtype = subtype->next->vtype;
6430 (void)!ir_value_set_field(field->ir_v, ifld);
6433 for (i = 0; i < vec_size(parser->globals); ++i) {
6435 if (!ast_istype(parser->globals[i], ast_value))
6437 asvalue = (ast_value*)(parser->globals[i]);
6438 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
6439 retval = retval && !compile_warning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
6440 "unused global: `%s`", asvalue->name);
6442 if (!ast_global_codegen(asvalue, ir, false)) {
6443 con_out("failed to generate global %s\n", asvalue->name);
6444 ir_builder_delete(ir);
6448 /* Build function vararg accessor ast tree now before generating
6449 * immediates, because the accessors may add new immediates
6451 for (i = 0; i < vec_size(parser->functions); ++i) {
6452 ast_function *f = parser->functions[i];
6454 if (parser->max_param_count > vec_size(f->vtype->expression.params)) {
6455 f->varargs->expression.count = parser->max_param_count - vec_size(f->vtype->expression.params);
6456 if (!parser_create_array_setter_impl(parser, f->varargs)) {
6457 con_out("failed to generate vararg setter for %s\n", f->name);
6458 ir_builder_delete(ir);
6461 if (!parser_create_array_getter_impl(parser, f->varargs)) {
6462 con_out("failed to generate vararg getter for %s\n", f->name);
6463 ir_builder_delete(ir);
6467 ast_delete(f->varargs);
6472 /* Now we can generate immediates */
6473 for (i = 0; i < vec_size(parser->imm_float); ++i) {
6474 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
6475 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
6476 ir_builder_delete(ir);
6480 for (i = 0; i < vec_size(parser->imm_string); ++i) {
6481 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
6482 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
6483 ir_builder_delete(ir);
6487 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
6488 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
6489 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
6490 ir_builder_delete(ir);
6494 for (i = 0; i < vec_size(parser->globals); ++i) {
6496 if (!ast_istype(parser->globals[i], ast_value))
6498 asvalue = (ast_value*)(parser->globals[i]);
6499 if (!(asvalue->expression.flags & AST_FLAG_INITIALIZED))
6501 if (asvalue->cvq == CV_CONST && !asvalue->hasvalue)
6502 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_CONSTANT,
6503 "uninitialized constant: `%s`",
6505 else if ((asvalue->cvq == CV_NONE || asvalue->cvq == CV_CONST) && !asvalue->hasvalue)
6506 (void)!compile_warning(ast_ctx(asvalue), WARN_UNINITIALIZED_GLOBAL,
6507 "uninitialized global: `%s`",
6510 if (!ast_generate_accessors(asvalue, ir)) {
6511 ir_builder_delete(ir);
6515 for (i = 0; i < vec_size(parser->fields); ++i) {
6517 asvalue = (ast_value*)(parser->fields[i]->next);
6519 if (!ast_istype((ast_expression*)asvalue, ast_value))
6521 if (asvalue->expression.vtype != TYPE_ARRAY)
6523 if (!ast_generate_accessors(asvalue, ir)) {
6524 ir_builder_delete(ir);
6528 if (parser->reserved_version &&
6529 !ast_global_codegen(parser->reserved_version, ir, false))
6531 con_out("failed to generate reserved::version");
6532 ir_builder_delete(ir);
6535 for (i = 0; i < vec_size(parser->functions); ++i) {
6536 ast_function *f = parser->functions[i];
6537 if (!ast_function_codegen(f, ir)) {
6538 con_out("failed to generate function %s\n", f->name);
6539 ir_builder_delete(ir);
6544 generate_checksum(parser);
6545 if (OPTS_OPTION_BOOL(OPTION_DUMP))
6546 ir_builder_dump(ir, con_out);
6547 for (i = 0; i < vec_size(parser->functions); ++i) {
6548 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
6549 con_out("failed to finalize function %s\n", parser->functions[i]->name);
6550 ir_builder_delete(ir);
6554 parser_remove_ast(parser);
6556 if (compile_Werrors) {
6557 con_out("*** there were warnings treated as errors\n");
6558 compile_show_werrors();
6563 if (OPTS_OPTION_BOOL(OPTION_DUMPFIN))
6564 ir_builder_dump(ir, con_out);
6566 if (!ir_builder_generate(parser->code, ir, output)) {
6567 con_out("*** failed to generate output file\n");
6568 ir_builder_delete(ir);
6572 ir_builder_delete(ir);