5 * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 * this software and associated documentation files (the "Software"), to deal in
7 * the Software without restriction, including without limitation the rights to
8 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9 * of the Software, and to permit persons to whom the Software is furnished to do
10 * so, subject to the following conditions:
12 * The above copyright notice and this permission notice shall be included in all
13 * copies or substantial portions of the Software.
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 /* beginning of locals */
30 #define PARSER_HT_LOCALS 2
32 #define PARSER_HT_SIZE 1024
33 #define TYPEDEF_HT_SIZE 16
35 enum parser_pot { POT_PAREN, POT_TERNARY1, POT_TERNARY2 };
40 ast_expression **globals;
41 ast_expression **fields;
42 ast_function **functions;
43 ast_value **imm_float;
44 ast_value **imm_string;
45 ast_value **imm_vector;
48 /* must be deleted first, they reference immediates and values */
49 ast_value **accessors;
51 ast_value *imm_float_zero;
52 ast_value *imm_float_one;
53 ast_value *imm_vector_zero;
58 ast_function *function;
60 /* All the labels the function defined...
61 * Should they be in ast_function instead?
66 const char **continues;
68 /* A list of hashtables for each scope */
74 /* not to be used directly, we use the hash table */
75 ast_expression **_locals;
77 ast_value **_typedefs;
78 size_t *_blocktypedefs;
81 /* we store the '=' operator info */
82 const oper_info *assign_op;
84 /* TYPE_FIELD -> parser_find_fields is used instead of find_var
85 * TODO: TYPE_VECTOR -> x, y and z are accepted in the gmqcc standard
86 * anything else: type error
90 /* Keep track of our ternary vs parenthesis nesting state.
91 * If we reach a 'comma' operator in a ternary without a paren,
92 * we shall trigger -Wternary-precedence.
100 static const ast_expression *intrinsic_debug_typestring = (ast_expression*)0x10;
102 static void parser_enterblock(parser_t *parser);
103 static bool parser_leaveblock(parser_t *parser);
104 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e);
105 static bool parse_typedef(parser_t *parser);
106 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static);
107 static ast_block* parse_block(parser_t *parser);
108 static bool parse_block_into(parser_t *parser, ast_block *block);
109 static bool parse_statement_or_block(parser_t *parser, ast_expression **out);
110 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases);
111 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma);
112 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma);
114 static void parseerror(parser_t *parser, const char *fmt, ...)
118 vcompile_error(parser->lex->tok.ctx, fmt, ap);
122 /* returns true if it counts as an error */
123 static bool GMQCC_WARN parsewarning(parser_t *parser, int warntype, const char *fmt, ...)
128 r = vcompile_warning(parser->lex->tok.ctx, warntype, fmt, ap);
133 static bool GMQCC_WARN genwarning(lex_ctx ctx, int warntype, const char *fmt, ...)
138 r = vcompile_warning(ctx, warntype, fmt, ap);
143 /**********************************************************************
144 * some maths used for constant folding
147 vector vec3_add(vector a, vector b)
156 vector vec3_sub(vector a, vector b)
165 qcfloat vec3_mulvv(vector a, vector b)
167 return (a.x * b.x + a.y * b.y + a.z * b.z);
170 vector vec3_mulvf(vector a, float b)
179 /**********************************************************************
183 bool parser_next(parser_t *parser)
185 /* lex_do kills the previous token */
186 parser->tok = lex_do(parser->lex);
187 if (parser->tok == TOKEN_EOF)
189 if (parser->tok >= TOKEN_ERROR) {
190 parseerror(parser, "lex error");
196 #define parser_tokval(p) ((p)->lex->tok.value)
197 #define parser_token(p) (&((p)->lex->tok))
198 #define parser_ctx(p) ((p)->lex->tok.ctx)
200 static ast_value* parser_const_float(parser_t *parser, double d)
204 for (i = 0; i < vec_size(parser->imm_float); ++i) {
205 const double compare = parser->imm_float[i]->constval.vfloat;
206 if (memcmp((const void*)&compare, (const void *)&d, sizeof(double)) == 0)
207 return parser->imm_float[i];
209 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_FLOAT);
211 out->hasvalue = true;
212 out->constval.vfloat = d;
213 vec_push(parser->imm_float, out);
217 static ast_value* parser_const_float_0(parser_t *parser)
219 if (!parser->imm_float_zero)
220 parser->imm_float_zero = parser_const_float(parser, 0);
221 return parser->imm_float_zero;
224 static ast_value* parser_const_float_1(parser_t *parser)
226 if (!parser->imm_float_one)
227 parser->imm_float_one = parser_const_float(parser, 1);
228 return parser->imm_float_one;
231 static char *parser_strdup(const char *str)
234 /* actually dup empty strings */
235 char *out = (char*)mem_a(1);
239 return util_strdup(str);
242 static ast_value* parser_const_string(parser_t *parser, const char *str, bool dotranslate)
246 for (i = 0; i < vec_size(parser->imm_string); ++i) {
247 if (!strcmp(parser->imm_string[i]->constval.vstring, str))
248 return parser->imm_string[i];
252 snprintf(name, sizeof(name), "dotranslate_%lu", (unsigned long)(parser->translated++));
253 out = ast_value_new(parser_ctx(parser), name, TYPE_STRING);
255 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_STRING);
257 out->hasvalue = true;
258 out->constval.vstring = parser_strdup(str);
259 vec_push(parser->imm_string, out);
263 static ast_value* parser_const_vector(parser_t *parser, vector v)
267 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
268 if (!memcmp(&parser->imm_vector[i]->constval.vvec, &v, sizeof(v)))
269 return parser->imm_vector[i];
271 out = ast_value_new(parser_ctx(parser), "#IMMEDIATE", TYPE_VECTOR);
273 out->hasvalue = true;
274 out->constval.vvec = v;
275 vec_push(parser->imm_vector, out);
279 static ast_value* parser_const_vector_f(parser_t *parser, float x, float y, float z)
285 return parser_const_vector(parser, v);
288 static ast_value* parser_const_vector_0(parser_t *parser)
290 if (!parser->imm_vector_zero)
291 parser->imm_vector_zero = parser_const_vector_f(parser, 0, 0, 0);
292 return parser->imm_vector_zero;
295 static ast_expression* parser_find_field(parser_t *parser, const char *name)
297 return ( ast_expression*)util_htget(parser->htfields, name);
300 static ast_expression* parser_find_global(parser_t *parser, const char *name)
302 return (ast_expression*)util_htget(parser->htglobals, name);
305 static ast_expression* parser_find_param(parser_t *parser, const char *name)
309 if (!parser->function)
311 fun = parser->function->vtype;
312 for (i = 0; i < vec_size(fun->expression.params); ++i) {
313 if (!strcmp(fun->expression.params[i]->name, name))
314 return (ast_expression*)(fun->expression.params[i]);
319 static ast_expression* parser_find_local(parser_t *parser, const char *name, size_t upto, bool *isparam)
324 hash = util_hthash(parser->htglobals, name);
327 for (i = vec_size(parser->variables); i > upto;) {
329 if ( (e = (ast_expression*)util_htgeth(parser->variables[i], name, hash)) )
333 return parser_find_param(parser, name);
336 static ast_expression* parser_find_var(parser_t *parser, const char *name)
340 v = parser_find_local(parser, name, 0, &dummy);
341 if (!v) v = parser_find_global(parser, name);
345 static ast_value* parser_find_typedef(parser_t *parser, const char *name, size_t upto)
349 hash = util_hthash(parser->typedefs[0], name);
351 for (i = vec_size(parser->typedefs); i > upto;) {
353 if ( (e = (ast_value*)util_htgeth(parser->typedefs[i], name, hash)) )
361 size_t etype; /* 0 = expression, others are operators */
365 ast_block *block; /* for commas and function calls */
374 #define SY_PAREN_EXPR '('
375 #define SY_PAREN_FUNC 'f'
376 #define SY_PAREN_INDEX '['
377 #define SY_PAREN_TERNARY '?'
379 static sy_elem syexp(lex_ctx ctx, ast_expression *v) {
390 static sy_elem syblock(lex_ctx ctx, ast_block *v) {
394 e.out = (ast_expression*)v;
401 static sy_elem syop(lex_ctx ctx, const oper_info *op) {
403 e.etype = 1 + (op - operators);
412 static sy_elem syparen(lex_ctx ctx, int p, size_t off) {
424 # define DEBUGSHUNTDO(x) x
426 # define DEBUGSHUNTDO(x)
429 /* With regular precedence rules, ent.foo[n] is the same as (ent.foo)[n],
430 * so we need to rotate it to become ent.(foo[n]).
432 static bool rotate_entfield_array_index_nodes(ast_expression **out)
434 ast_array_index *index;
435 ast_entfield *entfield;
439 ast_expression *entity;
441 lex_ctx ctx = ast_ctx(*out);
443 if (!ast_istype(*out, ast_array_index))
445 index = (ast_array_index*)*out;
447 if (!ast_istype(index->array, ast_entfield))
449 entfield = (ast_entfield*)index->array;
451 if (!ast_istype(entfield->field, ast_value))
453 field = (ast_value*)entfield->field;
456 entity = entfield->entity;
460 index = ast_array_index_new(ctx, (ast_expression*)field, sub);
461 entfield = ast_entfield_new(ctx, entity, (ast_expression*)index);
462 *out = (ast_expression*)entfield;
467 static bool immediate_is_true(lex_ctx ctx, ast_value *v)
469 switch (v->expression.vtype) {
471 return !!v->constval.vfloat;
473 return !!v->constval.vint;
475 if (OPTS_FLAG(CORRECT_LOGIC))
476 return v->constval.vvec.x &&
477 v->constval.vvec.y &&
480 return !!(v->constval.vvec.x);
482 if (!v->constval.vstring)
484 if (v->constval.vstring && OPTS_FLAG(TRUE_EMPTY_STRINGS))
486 return !!v->constval.vstring[0];
488 compile_error(ctx, "internal error: immediate_is_true on invalid type");
489 return !!v->constval.vfunc;
493 static bool parser_sy_apply_operator(parser_t *parser, shunt *sy)
497 ast_expression *out = NULL;
498 ast_expression *exprs[3];
499 ast_block *blocks[3];
500 ast_value *asvalue[3];
501 ast_binstore *asbinstore;
502 size_t i, assignop, addop, subop;
503 qcint generated_op = 0;
508 if (!vec_size(sy->ops)) {
509 parseerror(parser, "internal error: missing operator");
513 if (vec_last(sy->ops).paren) {
514 parseerror(parser, "unmatched parenthesis");
518 op = &operators[vec_last(sy->ops).etype - 1];
519 ctx = vec_last(sy->ops).ctx;
521 DEBUGSHUNTDO(con_out("apply %s\n", op->op));
523 if (vec_size(sy->out) < op->operands) {
524 parseerror(parser, "internal error: not enough operands: %i (operator %s (%i))", vec_size(sy->out),
525 op->op, (int)op->id);
529 vec_shrinkby(sy->ops, 1);
531 /* op(:?) has no input and no output */
535 vec_shrinkby(sy->out, op->operands);
536 for (i = 0; i < op->operands; ++i) {
537 exprs[i] = sy->out[vec_size(sy->out)+i].out;
538 blocks[i] = sy->out[vec_size(sy->out)+i].block;
539 asvalue[i] = (ast_value*)exprs[i];
542 if (blocks[0] && !vec_size(blocks[0]->exprs) && op->id != opid1(',')) {
543 parseerror(parser, "internal error: operator cannot be applied on empty blocks");
547 #define NotSameType(T) \
548 (exprs[0]->expression.vtype != exprs[1]->expression.vtype || \
549 exprs[0]->expression.vtype != T)
550 #define CanConstFold1(A) \
551 (ast_istype((A), ast_value) && ((ast_value*)(A))->hasvalue && (((ast_value*)(A))->cvq == CV_CONST) &&\
552 (A)->expression.vtype != TYPE_FUNCTION)
553 #define CanConstFold(A, B) \
554 (CanConstFold1(A) && CanConstFold1(B))
555 #define ConstV(i) (asvalue[(i)]->constval.vvec)
556 #define ConstF(i) (asvalue[(i)]->constval.vfloat)
557 #define ConstS(i) (asvalue[(i)]->constval.vstring)
561 parseerror(parser, "internal error: unhandled operator: %s (%i)", op->op, (int)op->id);
565 if (exprs[0]->expression.vtype == TYPE_ENTITY) {
566 if (exprs[1]->expression.vtype != TYPE_FIELD) {
567 parseerror(parser, "type error: right hand of member-operand should be an entity-field");
570 out = (ast_expression*)ast_entfield_new(ctx, exprs[0], exprs[1]);
572 else if (exprs[0]->expression.vtype == TYPE_VECTOR) {
573 parseerror(parser, "internal error: vector access is not supposed to be handled at this point");
577 parseerror(parser, "type error: member-of operator on something that is not an entity or vector");
583 if (exprs[0]->expression.vtype != TYPE_ARRAY &&
584 !(exprs[0]->expression.vtype == TYPE_FIELD &&
585 exprs[0]->expression.next->expression.vtype == TYPE_ARRAY))
587 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
588 parseerror(parser, "cannot index value of type %s", ty1);
591 if (exprs[1]->expression.vtype != TYPE_FLOAT) {
592 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
593 parseerror(parser, "index must be of type float, not %s", ty1);
596 out = (ast_expression*)ast_array_index_new(ctx, exprs[0], exprs[1]);
597 if (rotate_entfield_array_index_nodes(&out))
600 /* This is not broken in fteqcc anymore */
601 if (opts.standard != COMPILER_GMQCC) {
602 /* this error doesn't need to make us bail out */
603 (void)!parsewarning(parser, WARN_EXTENSIONS,
604 "accessing array-field members of an entity without parenthesis\n"
605 " -> this is an extension from -std=gmqcc");
613 if (!ast_block_add_expr(blocks[0], exprs[1]))
616 blocks[0] = ast_block_new(ctx);
617 if (!ast_block_add_expr(blocks[0], exprs[0]) ||
618 !ast_block_add_expr(blocks[0], exprs[1]))
623 if (!ast_block_set_type(blocks[0], exprs[1]))
626 vec_push(sy->out, syblock(ctx, blocks[0]));
633 switch (exprs[0]->expression.vtype) {
635 if (CanConstFold1(exprs[0]))
636 out = (ast_expression*)parser_const_float(parser, -ConstF(0));
638 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F,
639 (ast_expression*)parser_const_float_0(parser),
643 if (CanConstFold1(exprs[0]))
644 out = (ast_expression*)parser_const_vector_f(parser,
645 -ConstV(0).x, -ConstV(0).y, -ConstV(0).z);
647 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V,
648 (ast_expression*)parser_const_vector_0(parser),
652 parseerror(parser, "invalid types used in expression: cannot negate type %s",
653 type_name[exprs[0]->expression.vtype]);
659 switch (exprs[0]->expression.vtype) {
661 if (CanConstFold1(exprs[0]))
662 out = (ast_expression*)parser_const_float(parser, !ConstF(0));
664 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
667 if (CanConstFold1(exprs[0]))
668 out = (ast_expression*)parser_const_float(parser,
669 (!ConstV(0).x && !ConstV(0).y && !ConstV(0).z));
671 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[0]);
674 if (CanConstFold1(exprs[0])) {
675 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
676 out = (ast_expression*)parser_const_float(parser, !ConstS(0));
678 out = (ast_expression*)parser_const_float(parser, !ConstS(0) || !*ConstS(0));
680 if (OPTS_FLAG(TRUE_EMPTY_STRINGS))
681 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, exprs[0]);
683 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[0]);
686 /* we don't constant-fold NOT for these types */
688 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_ENT, exprs[0]);
691 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_FNC, exprs[0]);
694 parseerror(parser, "invalid types used in expression: cannot logically negate type %s",
695 type_name[exprs[0]->expression.vtype]);
701 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
702 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
704 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
705 type_name[exprs[0]->expression.vtype],
706 type_name[exprs[1]->expression.vtype]);
709 switch (exprs[0]->expression.vtype) {
711 if (CanConstFold(exprs[0], exprs[1]))
713 out = (ast_expression*)parser_const_float(parser, ConstF(0) + ConstF(1));
716 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F, exprs[0], exprs[1]);
719 if (CanConstFold(exprs[0], exprs[1]))
720 out = (ast_expression*)parser_const_vector(parser, vec3_add(ConstV(0), ConstV(1)));
722 out = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_V, exprs[0], exprs[1]);
725 parseerror(parser, "invalid types used in expression: cannot add type %s and %s",
726 type_name[exprs[0]->expression.vtype],
727 type_name[exprs[1]->expression.vtype]);
732 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
733 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
735 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
736 type_name[exprs[1]->expression.vtype],
737 type_name[exprs[0]->expression.vtype]);
740 switch (exprs[0]->expression.vtype) {
742 if (CanConstFold(exprs[0], exprs[1]))
743 out = (ast_expression*)parser_const_float(parser, ConstF(0) - ConstF(1));
745 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_F, exprs[0], exprs[1]);
748 if (CanConstFold(exprs[0], exprs[1]))
749 out = (ast_expression*)parser_const_vector(parser, vec3_sub(ConstV(0), ConstV(1)));
751 out = (ast_expression*)ast_binary_new(ctx, INSTR_SUB_V, exprs[0], exprs[1]);
754 parseerror(parser, "invalid types used in expression: cannot subtract type %s from %s",
755 type_name[exprs[1]->expression.vtype],
756 type_name[exprs[0]->expression.vtype]);
761 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype &&
762 exprs[0]->expression.vtype != TYPE_VECTOR &&
763 exprs[0]->expression.vtype != TYPE_FLOAT &&
764 exprs[1]->expression.vtype != TYPE_VECTOR &&
765 exprs[1]->expression.vtype != TYPE_FLOAT)
767 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
768 type_name[exprs[1]->expression.vtype],
769 type_name[exprs[0]->expression.vtype]);
772 switch (exprs[0]->expression.vtype) {
774 if (exprs[1]->expression.vtype == TYPE_VECTOR)
776 if (CanConstFold(exprs[0], exprs[1]))
777 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(1), ConstF(0)));
779 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_FV, exprs[0], exprs[1]);
783 if (CanConstFold(exprs[0], exprs[1]))
784 out = (ast_expression*)parser_const_float(parser, ConstF(0) * ConstF(1));
786 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_F, exprs[0], exprs[1]);
790 if (exprs[1]->expression.vtype == TYPE_FLOAT)
792 if (CanConstFold(exprs[0], exprs[1]))
793 out = (ast_expression*)parser_const_vector(parser, vec3_mulvf(ConstV(0), ConstF(1)));
795 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_VF, exprs[0], exprs[1]);
799 if (CanConstFold(exprs[0], exprs[1]))
800 out = (ast_expression*)parser_const_float(parser, vec3_mulvv(ConstV(0), ConstV(1)));
802 out = (ast_expression*)ast_binary_new(ctx, INSTR_MUL_V, exprs[0], exprs[1]);
806 parseerror(parser, "invalid types used in expression: cannot multiply types %s and %s",
807 type_name[exprs[1]->expression.vtype],
808 type_name[exprs[0]->expression.vtype]);
813 if (NotSameType(TYPE_FLOAT)) {
814 parseerror(parser, "invalid types used in expression: cannot divide types %s and %s",
815 type_name[exprs[0]->expression.vtype],
816 type_name[exprs[1]->expression.vtype]);
819 if (CanConstFold(exprs[0], exprs[1]))
820 out = (ast_expression*)parser_const_float(parser, ConstF(0) / ConstF(1));
822 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F, exprs[0], exprs[1]);
826 parseerror(parser, "qc does not have a modulo operator");
830 if (NotSameType(TYPE_FLOAT)) {
831 parseerror(parser, "invalid types used in expression: cannot perform bit operations between types %s and %s",
832 type_name[exprs[0]->expression.vtype],
833 type_name[exprs[1]->expression.vtype]);
836 if (CanConstFold(exprs[0], exprs[1]))
837 out = (ast_expression*)parser_const_float(parser,
838 (op->id == opid1('|') ? (float)( ((qcint)ConstF(0)) | ((qcint)ConstF(1)) ) :
839 (float)( ((qcint)ConstF(0)) & ((qcint)ConstF(1)) ) ));
841 out = (ast_expression*)ast_binary_new(ctx,
842 (op->id == opid1('|') ? INSTR_BITOR : INSTR_BITAND),
846 parseerror(parser, "TODO: bitxor");
851 case opid3('<','<','='):
852 case opid3('>','>','='):
853 parseerror(parser, "TODO: shifts");
857 generated_op += 1; /* INSTR_OR */
859 generated_op += INSTR_AND;
861 if (NotSameType(TYPE_FLOAT)) {
862 parseerror(parser, "invalid types used in expression: cannot perform logical operations between types %s and %s",
863 type_name[exprs[0]->expression.vtype],
864 type_name[exprs[1]->expression.vtype]);
865 parseerror(parser, "TODO: logical ops for arbitrary types using INSTR_NOT");
866 parseerror(parser, "TODO: optional early out");
870 if (CanConstFold(exprs[0], exprs[1]))
872 if (OPTS_FLAG(PERL_LOGIC)) {
873 if (immediate_is_true(ctx, asvalue[0]))
877 out = (ast_expression*)parser_const_float(parser,
878 ( (generated_op == INSTR_OR)
879 ? (immediate_is_true(ctx, asvalue[0]) || immediate_is_true(ctx, asvalue[1]))
880 : (immediate_is_true(ctx, asvalue[0]) && immediate_is_true(ctx, asvalue[1])) )
885 if (OPTS_FLAG(PERL_LOGIC) && !ast_compare_type(exprs[0], exprs[1])) {
886 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
887 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
888 parseerror(parser, "invalid types for logical operation with -fperl-logic: %s and %s", ty1, ty2);
891 for (i = 0; i < 2; ++i) {
892 if (OPTS_FLAG(CORRECT_LOGIC) && exprs[i]->expression.vtype == TYPE_VECTOR) {
893 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_V, exprs[i]);
895 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
897 exprs[i] = out; out = NULL;
898 if (OPTS_FLAG(PERL_LOGIC)) {
899 /* here we want to keep the right expressions' type */
903 else if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && exprs[i]->expression.vtype == TYPE_STRING) {
904 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_S, exprs[i]);
906 out = (ast_expression*)ast_unary_new(ctx, INSTR_NOT_F, out);
908 exprs[i] = out; out = NULL;
909 if (OPTS_FLAG(PERL_LOGIC)) {
910 /* here we want to keep the right expressions' type */
915 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
920 if (vec_last(parser->pot) != POT_TERNARY2) {
921 parseerror(parser, "mismatched parenthesis/ternary");
924 vec_pop(parser->pot);
925 if (exprs[1]->expression.vtype != exprs[2]->expression.vtype) {
926 ast_type_to_string(exprs[1], ty1, sizeof(ty1));
927 ast_type_to_string(exprs[2], ty2, sizeof(ty2));
928 parseerror(parser, "operands of ternary expression must have the same type, got %s and %s", ty1, ty2);
931 if (CanConstFold1(exprs[0]))
932 out = (ConstF(0) ? exprs[1] : exprs[2]);
934 out = (ast_expression*)ast_ternary_new(ctx, exprs[0], exprs[1], exprs[2]);
938 generated_op += 1; /* INSTR_GT */
940 generated_op += 1; /* INSTR_LT */
941 case opid2('>', '='):
942 generated_op += 1; /* INSTR_GE */
943 case opid2('<', '='):
944 generated_op += INSTR_LE;
945 if (NotSameType(TYPE_FLOAT)) {
946 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
947 type_name[exprs[0]->expression.vtype],
948 type_name[exprs[1]->expression.vtype]);
951 out = (ast_expression*)ast_binary_new(ctx, generated_op, exprs[0], exprs[1]);
953 case opid2('!', '='):
954 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
955 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
956 type_name[exprs[0]->expression.vtype],
957 type_name[exprs[1]->expression.vtype]);
960 out = (ast_expression*)ast_binary_new(ctx, type_ne_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
962 case opid2('=', '='):
963 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype) {
964 parseerror(parser, "invalid types used in expression: cannot perform comparison between types %s and %s",
965 type_name[exprs[0]->expression.vtype],
966 type_name[exprs[1]->expression.vtype]);
969 out = (ast_expression*)ast_binary_new(ctx, type_eq_instr[exprs[0]->expression.vtype], exprs[0], exprs[1]);
973 if (ast_istype(exprs[0], ast_entfield)) {
974 ast_expression *field = ((ast_entfield*)exprs[0])->field;
975 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
976 exprs[0]->expression.vtype == TYPE_FIELD &&
977 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
979 assignop = type_storep_instr[TYPE_VECTOR];
982 assignop = type_storep_instr[exprs[0]->expression.vtype];
983 if (assignop == AINSTR_END ||
984 !ast_compare_type(field->expression.next, exprs[1]))
986 ast_type_to_string(field->expression.next, ty1, sizeof(ty1));
987 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
988 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
989 field->expression.next->expression.vtype == TYPE_FUNCTION &&
990 exprs[1]->expression.vtype == TYPE_FUNCTION)
992 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
993 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
996 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1001 if (OPTS_FLAG(ADJUST_VECTOR_FIELDS) &&
1002 exprs[0]->expression.vtype == TYPE_FIELD &&
1003 exprs[0]->expression.next->expression.vtype == TYPE_VECTOR)
1005 assignop = type_store_instr[TYPE_VECTOR];
1008 assignop = type_store_instr[exprs[0]->expression.vtype];
1011 if (assignop == AINSTR_END) {
1012 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1013 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1014 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1016 else if (!ast_compare_type(exprs[0], exprs[1])) {
1017 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1018 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1019 if (OPTS_FLAG(ASSIGN_FUNCTION_TYPES) &&
1020 exprs[0]->expression.vtype == TYPE_FUNCTION &&
1021 exprs[1]->expression.vtype == TYPE_FUNCTION)
1023 (void)!parsewarning(parser, WARN_ASSIGN_FUNCTION_TYPES,
1024 "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1027 parseerror(parser, "invalid types in assignment: cannot assign %s to %s", ty2, ty1);
1030 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1031 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1033 out = (ast_expression*)ast_store_new(ctx, assignop, exprs[0], exprs[1]);
1035 case opid3('+','+','P'):
1036 case opid3('-','-','P'):
1038 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1039 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1040 parseerror(parser, "invalid type for prefix increment: %s", ty1);
1043 if (op->id == opid3('+','+','P'))
1044 addop = INSTR_ADD_F;
1046 addop = INSTR_SUB_F;
1047 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1048 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1050 if (ast_istype(exprs[0], ast_entfield)) {
1051 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1053 (ast_expression*)parser_const_float_1(parser));
1055 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1057 (ast_expression*)parser_const_float_1(parser));
1060 case opid3('S','+','+'):
1061 case opid3('S','-','-'):
1063 if (exprs[0]->expression.vtype != TYPE_FLOAT) {
1064 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1065 parseerror(parser, "invalid type for suffix increment: %s", ty1);
1068 if (op->id == opid3('S','+','+')) {
1069 addop = INSTR_ADD_F;
1070 subop = INSTR_SUB_F;
1072 addop = INSTR_SUB_F;
1073 subop = INSTR_ADD_F;
1075 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1076 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1078 if (ast_istype(exprs[0], ast_entfield)) {
1079 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STOREP_F, addop,
1081 (ast_expression*)parser_const_float_1(parser));
1083 out = (ast_expression*)ast_binstore_new(ctx, INSTR_STORE_F, addop,
1085 (ast_expression*)parser_const_float_1(parser));
1089 out = (ast_expression*)ast_binary_new(ctx, subop,
1091 (ast_expression*)parser_const_float_1(parser));
1093 case opid2('+','='):
1094 case opid2('-','='):
1095 if (exprs[0]->expression.vtype != exprs[1]->expression.vtype ||
1096 (exprs[0]->expression.vtype != TYPE_VECTOR && exprs[0]->expression.vtype != TYPE_FLOAT) )
1098 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1099 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1100 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1104 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1105 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1107 if (ast_istype(exprs[0], ast_entfield))
1108 assignop = type_storep_instr[exprs[0]->expression.vtype];
1110 assignop = type_store_instr[exprs[0]->expression.vtype];
1111 switch (exprs[0]->expression.vtype) {
1113 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1114 (op->id == opid2('+','=') ? INSTR_ADD_F : INSTR_SUB_F),
1115 exprs[0], exprs[1]);
1118 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1119 (op->id == opid2('+','=') ? INSTR_ADD_V : INSTR_SUB_V),
1120 exprs[0], exprs[1]);
1123 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1124 type_name[exprs[0]->expression.vtype],
1125 type_name[exprs[1]->expression.vtype]);
1129 case opid2('*','='):
1130 case opid2('/','='):
1131 if (exprs[1]->expression.vtype != TYPE_FLOAT ||
1132 !(exprs[0]->expression.vtype == TYPE_FLOAT ||
1133 exprs[0]->expression.vtype == TYPE_VECTOR))
1135 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1136 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1137 parseerror(parser, "invalid types used in expression: %s and %s",
1141 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1142 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1144 if (ast_istype(exprs[0], ast_entfield))
1145 assignop = type_storep_instr[exprs[0]->expression.vtype];
1147 assignop = type_store_instr[exprs[0]->expression.vtype];
1148 switch (exprs[0]->expression.vtype) {
1150 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1151 (op->id == opid2('*','=') ? INSTR_MUL_F : INSTR_DIV_F),
1152 exprs[0], exprs[1]);
1155 if (op->id == opid2('*','=')) {
1156 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1157 exprs[0], exprs[1]);
1159 /* there's no DIV_VF */
1160 out = (ast_expression*)ast_binary_new(ctx, INSTR_DIV_F,
1161 (ast_expression*)parser_const_float_1(parser),
1165 out = (ast_expression*)ast_binstore_new(ctx, assignop, INSTR_MUL_VF,
1170 parseerror(parser, "invalid types used in expression: cannot add or subtract type %s and %s",
1171 type_name[exprs[0]->expression.vtype],
1172 type_name[exprs[1]->expression.vtype]);
1176 case opid2('&','='):
1177 case opid2('|','='):
1178 if (NotSameType(TYPE_FLOAT)) {
1179 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1180 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1181 parseerror(parser, "invalid types used in expression: %s and %s",
1185 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1186 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1188 if (ast_istype(exprs[0], ast_entfield))
1189 assignop = type_storep_instr[exprs[0]->expression.vtype];
1191 assignop = type_store_instr[exprs[0]->expression.vtype];
1192 out = (ast_expression*)ast_binstore_new(ctx, assignop,
1193 (op->id == opid2('&','=') ? INSTR_BITAND : INSTR_BITOR),
1194 exprs[0], exprs[1]);
1196 case opid3('&','~','='):
1197 /* This is like: a &= ~(b);
1198 * But QC has no bitwise-not, so we implement it as
1201 if (NotSameType(TYPE_FLOAT)) {
1202 ast_type_to_string(exprs[0], ty1, sizeof(ty1));
1203 ast_type_to_string(exprs[1], ty2, sizeof(ty2));
1204 parseerror(parser, "invalid types used in expression: %s and %s",
1208 if (ast_istype(exprs[0], ast_entfield))
1209 assignop = type_storep_instr[exprs[0]->expression.vtype];
1211 assignop = type_store_instr[exprs[0]->expression.vtype];
1212 out = (ast_expression*)ast_binary_new(ctx, INSTR_BITAND, exprs[0], exprs[1]);
1215 if (ast_istype(exprs[0], ast_value) && asvalue[0]->cvq == CV_CONST) {
1216 parseerror(parser, "assignment to constant `%s`", asvalue[0]->name);
1218 asbinstore = ast_binstore_new(ctx, assignop, INSTR_SUB_F, exprs[0], out);
1219 asbinstore->keep_dest = true;
1220 out = (ast_expression*)asbinstore;
1226 parseerror(parser, "failed to apply operand %s", op->op);
1230 DEBUGSHUNTDO(con_out("applied %s\n", op->op));
1231 vec_push(sy->out, syexp(ctx, out));
1235 static bool parser_close_call(parser_t *parser, shunt *sy)
1237 /* was a function call */
1238 ast_expression *fun;
1244 vec_shrinkby(sy->ops, 1);
1245 fid = sy->ops[vec_size(sy->ops)].off;
1247 /* out[fid] is the function
1248 * everything above is parameters...
1249 * 0 params = nothing
1250 * 1 params = ast_expression
1254 if (vec_size(sy->out) < 1 || vec_size(sy->out) <= fid) {
1255 parseerror(parser, "internal error: function call needs function and parameter list...");
1259 fun = sy->out[fid].out;
1261 if (fun == intrinsic_debug_typestring) {
1263 if (fid+2 != vec_size(sy->out) ||
1264 vec_last(sy->out).block)
1266 parseerror(parser, "intrinsic __builtin_debug_typestring requires exactly 1 parameter");
1269 ast_type_to_string(vec_last(sy->out).out, ty, sizeof(ty));
1270 ast_unref(vec_last(sy->out).out);
1271 sy->out[fid] = syexp(ast_ctx(vec_last(sy->out).out),
1272 (ast_expression*)parser_const_string(parser, ty, false));
1273 vec_shrinkby(sy->out, 1);
1277 call = ast_call_new(sy->ops[vec_size(sy->ops)].ctx, fun);
1279 parseerror(parser, "internal error: failed to create ast_call node");
1283 if (fid+1 == vec_size(sy->out)) {
1286 } else if (fid+2 == vec_size(sy->out)) {
1288 vec_shrinkby(sy->out, 1);
1289 params = sy->out[vec_size(sy->out)].block;
1293 vec_push(call->params, sy->out[vec_size(sy->out)].out);
1295 paramcount = vec_size(params->exprs);
1296 call->params = params->exprs;
1297 params->exprs = NULL;
1300 (void)!ast_call_check_types(call);
1302 parseerror(parser, "invalid function call");
1306 /* overwrite fid, the function, with a call */
1307 sy->out[fid] = syexp(call->expression.node.context, (ast_expression*)call);
1309 if (fun->expression.vtype != TYPE_FUNCTION) {
1310 parseerror(parser, "not a function (%s)", type_name[fun->expression.vtype]);
1314 if (!fun->expression.next) {
1315 parseerror(parser, "could not determine function return type");
1318 if (vec_size(fun->expression.params) != paramcount &&
1319 !((fun->expression.flags & AST_FLAG_VARIADIC) &&
1320 vec_size(fun->expression.params) < paramcount))
1323 const char *fewmany = (vec_size(fun->expression.params) > paramcount) ? "few" : "many";
1325 fval = (ast_istype(fun, ast_value) ? ((ast_value*)fun) : NULL);
1326 if (opts.standard == COMPILER_GMQCC)
1329 parseerror(parser, "too %s parameters for call to %s: expected %i, got %i\n"
1330 " -> `%s` has been declared here: %s:%i",
1331 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1332 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1334 parseerror(parser, "too %s parameters for function call: expected %i, got %i\n"
1335 " -> it has been declared here: %s:%i",
1336 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1337 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1343 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1344 "too %s parameters for call to %s: expected %i, got %i\n"
1345 " -> `%s` has been declared here: %s:%i",
1346 fewmany, fval->name, (int)vec_size(fun->expression.params), (int)paramcount,
1347 fval->name, ast_ctx(fun).file, (int)ast_ctx(fun).line);
1349 return !parsewarning(parser, WARN_TOO_FEW_PARAMETERS,
1350 "too %s parameters for function call: expected %i, got %i\n"
1351 " -> it has been declared here: %s:%i",
1352 fewmany, (int)vec_size(fun->expression.params), (int)paramcount,
1353 ast_ctx(fun).file, (int)ast_ctx(fun).line);
1361 static bool parser_close_paren(parser_t *parser, shunt *sy, bool functions_only)
1363 if (!vec_size(sy->ops)) {
1364 parseerror(parser, "unmatched closing paren");
1367 /* this would for bit a + (x) because there are no operators inside (x)
1368 if (sy->ops[vec_size(sy->ops)-1].paren == 1) {
1369 parseerror(parser, "empty parenthesis expression");
1373 while (vec_size(sy->ops)) {
1374 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_FUNC) {
1375 if (!parser_close_call(parser, sy))
1379 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_EXPR) {
1380 vec_shrinkby(sy->ops, 1);
1381 return !functions_only;
1383 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_INDEX) {
1386 /* pop off the parenthesis */
1387 vec_shrinkby(sy->ops, 1);
1388 /* then apply the index operator */
1389 if (!parser_sy_apply_operator(parser, sy))
1393 if (sy->ops[vec_size(sy->ops)-1].paren == SY_PAREN_TERNARY) {
1396 if (vec_last(parser->pot) != POT_TERNARY1) {
1397 parseerror(parser, "mismatched colon in ternary expression (missing closing paren?)");
1400 vec_last(parser->pot) = POT_TERNARY2;
1401 /* pop off the parenthesis */
1402 vec_shrinkby(sy->ops, 1);
1405 if (!parser_sy_apply_operator(parser, sy))
1411 static void parser_reclassify_token(parser_t *parser)
1414 for (i = 0; i < operator_count; ++i) {
1415 if (!strcmp(parser_tokval(parser), operators[i].op)) {
1416 parser->tok = TOKEN_OPERATOR;
1422 static ast_expression* parse_expression_leave(parser_t *parser, bool stopatcomma)
1424 ast_expression *expr = NULL;
1426 bool wantop = false;
1427 bool gotmemberof = false;
1429 /* count the parens because an if starts with one, so the
1430 * end of a condition is an unmatched closing paren
1438 parser->lex->flags.noops = false;
1440 parser_reclassify_token(parser);
1445 gotmemberof = false;
1447 parser->memberof = 0;
1449 if (OPTS_FLAG(TRANSLATABLE_STRINGS) &&
1450 parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "_"))
1452 /* a translatable string */
1456 parseerror(parser, "expected operator or end of statement, got constant");
1460 parser->lex->flags.noops = true;
1461 if (!parser_next(parser) || parser->tok != '(') {
1462 parseerror(parser, "use _(\"string\") to create a translatable string constant");
1465 parser->lex->flags.noops = false;
1466 if (!parser_next(parser) || parser->tok != TOKEN_STRINGCONST) {
1467 parseerror(parser, "expected a constant string in translatable-string extension");
1470 val = parser_const_string(parser, parser_tokval(parser), true);
1474 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1475 DEBUGSHUNTDO(con_out("push string\n"));
1477 if (!parser_next(parser) || parser->tok != ')') {
1478 parseerror(parser, "expected closing paren after translatable string");
1482 else if (parser->tok == TOKEN_IDENT)
1484 ast_expression *var;
1486 parseerror(parser, "expected operator or end of statement");
1491 if (opts.standard == COMPILER_GMQCC)
1493 if (parser->memberof == TYPE_ENTITY) {
1494 /* still get vars first since there could be a fieldpointer */
1495 var = parser_find_var(parser, parser_tokval(parser));
1497 var = parser_find_field(parser, parser_tokval(parser));
1499 else if (parser->memberof == TYPE_VECTOR)
1501 parseerror(parser, "TODO: implement effective vector member access");
1504 else if (parser->memberof) {
1505 parseerror(parser, "namespace for member not found");
1509 var = parser_find_var(parser, parser_tokval(parser));
1511 var = parser_find_var(parser, parser_tokval(parser));
1513 var = parser_find_field(parser, parser_tokval(parser));
1517 if (!strcmp(parser_tokval(parser), "__builtin_debug_typestring")) {
1518 var = (ast_expression*)intrinsic_debug_typestring;
1523 parseerror(parser, "unexpected ident: %s", parser_tokval(parser));
1529 if (ast_istype(var, ast_value)) {
1530 ((ast_value*)var)->uses++;
1532 else if (ast_istype(var, ast_member)) {
1533 ast_member *mem = (ast_member*)var;
1534 if (ast_istype(mem->owner, ast_value))
1535 ((ast_value*)(mem->owner))->uses++;
1538 vec_push(sy.out, syexp(parser_ctx(parser), var));
1539 DEBUGSHUNTDO(con_out("push %s\n", parser_tokval(parser)));
1541 else if (parser->tok == TOKEN_FLOATCONST) {
1544 parseerror(parser, "expected operator or end of statement, got constant");
1548 val = parser_const_float(parser, (parser_token(parser)->constval.f));
1551 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1552 DEBUGSHUNTDO(con_out("push %g\n", parser_token(parser)->constval.f));
1554 else if (parser->tok == TOKEN_INTCONST || parser->tok == TOKEN_CHARCONST) {
1557 parseerror(parser, "expected operator or end of statement, got constant");
1561 val = parser_const_float(parser, (double)(parser_token(parser)->constval.i));
1564 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1565 DEBUGSHUNTDO(con_out("push %i\n", parser_token(parser)->constval.i));
1567 else if (parser->tok == TOKEN_STRINGCONST) {
1570 parseerror(parser, "expected operator or end of statement, got constant");
1574 val = parser_const_string(parser, parser_tokval(parser), false);
1577 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1578 DEBUGSHUNTDO(con_out("push string\n"));
1580 else if (parser->tok == TOKEN_VECTORCONST) {
1583 parseerror(parser, "expected operator or end of statement, got constant");
1587 val = parser_const_vector(parser, parser_token(parser)->constval.v);
1590 vec_push(sy.out, syexp(parser_ctx(parser), (ast_expression*)val));
1591 DEBUGSHUNTDO(con_out("push '%g %g %g'\n",
1592 parser_token(parser)->constval.v.x,
1593 parser_token(parser)->constval.v.y,
1594 parser_token(parser)->constval.v.z));
1596 else if (parser->tok == '(') {
1597 parseerror(parser, "internal error: '(' should be classified as operator");
1600 else if (parser->tok == '[') {
1601 parseerror(parser, "internal error: '[' should be classified as operator");
1604 else if (parser->tok == ')') {
1606 DEBUGSHUNTDO(con_out("do[op] )\n"));
1610 /* we do expect an operator next */
1611 /* closing an opening paren */
1612 if (!parser_close_paren(parser, &sy, false))
1614 if (vec_last(parser->pot) != POT_PAREN) {
1615 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1618 vec_pop(parser->pot);
1620 DEBUGSHUNTDO(con_out("do[nop] )\n"));
1624 /* allowed for function calls */
1625 if (!parser_close_paren(parser, &sy, true))
1627 if (vec_last(parser->pot) != POT_PAREN) {
1628 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1631 vec_pop(parser->pot);
1635 else if (parser->tok == ']') {
1637 parseerror(parser, "operand expected");
1641 if (!parser_close_paren(parser, &sy, false))
1643 if (vec_last(parser->pot) != POT_PAREN) {
1644 parseerror(parser, "mismatched parentheses (closing paren during ternary expression?)");
1647 vec_pop(parser->pot);
1650 else if (parser->tok == TOKEN_TYPENAME) {
1651 parseerror(parser, "unexpected typename");
1654 else if (parser->tok != TOKEN_OPERATOR) {
1656 parseerror(parser, "expected operator or end of statement");
1663 /* classify the operator */
1664 const oper_info *op;
1665 const oper_info *olast = NULL;
1667 for (o = 0; o < operator_count; ++o) {
1668 if ((!(operators[o].flags & OP_PREFIX) == wantop) &&
1669 /* !(operators[o].flags & OP_SUFFIX) && / * remove this */
1670 !strcmp(parser_tokval(parser), operators[o].op))
1675 if (o == operator_count) {
1676 /* no operator found... must be the end of the statement */
1679 /* found an operator */
1682 /* when declaring variables, a comma starts a new variable */
1683 if (op->id == opid1(',') && !parens && stopatcomma) {
1684 /* fixup the token */
1689 /* a colon without a pervious question mark cannot be a ternary */
1690 if (!ternaries && op->id == opid2(':','?')) {
1695 if (op->id == opid1(',')) {
1696 if (vec_size(parser->pot) && vec_last(parser->pot) == POT_TERNARY2) {
1697 (void)!parsewarning(parser, WARN_TERNARY_PRECEDENCE, "suggesting parenthesis around ternary expression");
1701 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1702 olast = &operators[vec_last(sy.ops).etype-1];
1705 (op->prec < olast->prec) ||
1706 (op->assoc == ASSOC_LEFT && op->prec <= olast->prec) ) )
1708 if (!parser_sy_apply_operator(parser, &sy))
1710 if (vec_size(sy.ops) && !vec_last(sy.ops).paren)
1711 olast = &operators[vec_last(sy.ops).etype-1];
1716 if (op->id == opid1('.') && opts.standard == COMPILER_GMQCC) {
1717 /* for gmqcc standard: open up the namespace of the previous type */
1718 ast_expression *prevex = vec_last(sy.out).out;
1720 parseerror(parser, "unexpected member operator");
1723 if (prevex->expression.vtype == TYPE_ENTITY)
1724 parser->memberof = TYPE_ENTITY;
1725 else if (prevex->expression.vtype == TYPE_VECTOR)
1726 parser->memberof = TYPE_VECTOR;
1728 parseerror(parser, "type error: type has no members");
1734 if (op->id == opid1('(')) {
1736 size_t sycount = vec_size(sy.out);
1737 DEBUGSHUNTDO(con_out("push [op] (\n"));
1738 ++parens; vec_push(parser->pot, POT_PAREN);
1739 /* we expected an operator, this is the function-call operator */
1740 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_FUNC, sycount-1));
1742 ++parens; vec_push(parser->pot, POT_PAREN);
1743 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_EXPR, 0));
1744 DEBUGSHUNTDO(con_out("push [nop] (\n"));
1747 } else if (op->id == opid1('[')) {
1749 parseerror(parser, "unexpected array subscript");
1752 ++parens; vec_push(parser->pot, POT_PAREN);
1753 /* push both the operator and the paren, this makes life easier */
1754 vec_push(sy.ops, syop(parser_ctx(parser), op));
1755 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_INDEX, 0));
1757 } else if (op->id == opid2('?',':')) {
1758 vec_push(sy.ops, syop(parser_ctx(parser), op));
1759 vec_push(sy.ops, syparen(parser_ctx(parser), SY_PAREN_TERNARY, 0));
1762 vec_push(parser->pot, POT_TERNARY1);
1763 } else if (op->id == opid2(':','?')) {
1764 if (!vec_size(parser->pot)) {
1765 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1768 if (vec_last(parser->pot) != POT_TERNARY1) {
1769 parseerror(parser, "unexpected colon outside ternary expression (missing parenthesis?)");
1772 if (!parser_close_paren(parser, &sy, false))
1774 vec_push(sy.ops, syop(parser_ctx(parser), op));
1778 DEBUGSHUNTDO(con_out("push operator %s\n", op->op));
1779 vec_push(sy.ops, syop(parser_ctx(parser), op));
1780 wantop = !!(op->flags & OP_SUFFIX);
1783 if (!parser_next(parser)) {
1786 if (parser->tok == ';' ||
1787 (!parens && parser->tok == ']'))
1793 while (vec_size(sy.ops)) {
1794 if (!parser_sy_apply_operator(parser, &sy))
1798 parser->lex->flags.noops = true;
1799 if (!vec_size(sy.out)) {
1800 parseerror(parser, "empty expression");
1803 expr = sy.out[0].out;
1806 DEBUGSHUNTDO(con_out("shunt done\n"));
1807 if (vec_size(parser->pot)) {
1808 parseerror(parser, "internal error: vec_size(parser->pot) = %lu", (unsigned long)vec_size(parser->pot));
1811 vec_free(parser->pot);
1815 parser->lex->flags.noops = true;
1821 static ast_expression* parse_expression(parser_t *parser, bool stopatcomma)
1823 ast_expression *e = parse_expression_leave(parser, stopatcomma);
1826 if (!parser_next(parser)) {
1833 static void parser_enterblock(parser_t *parser)
1835 vec_push(parser->variables, util_htnew(PARSER_HT_SIZE));
1836 vec_push(parser->_blocklocals, vec_size(parser->_locals));
1837 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
1838 vec_push(parser->_blocktypedefs, vec_size(parser->_typedefs));
1839 vec_push(parser->_block_ctx, parser_ctx(parser));
1842 static bool parser_leaveblock(parser_t *parser)
1845 size_t locals, typedefs;
1847 if (vec_size(parser->variables) <= PARSER_HT_LOCALS) {
1848 parseerror(parser, "internal error: parser_leaveblock with no block");
1852 util_htdel(vec_last(parser->variables));
1853 vec_pop(parser->variables);
1854 if (!vec_size(parser->_blocklocals)) {
1855 parseerror(parser, "internal error: parser_leaveblock with no block (2)");
1859 locals = vec_last(parser->_blocklocals);
1860 vec_pop(parser->_blocklocals);
1861 while (vec_size(parser->_locals) != locals) {
1862 ast_expression *e = vec_last(parser->_locals);
1863 ast_value *v = (ast_value*)e;
1864 vec_pop(parser->_locals);
1865 if (ast_istype(e, ast_value) && !v->uses) {
1866 if (compile_warning(ast_ctx(v), WARN_UNUSED_VARIABLE, "unused variable: `%s`", v->name))
1871 typedefs = vec_last(parser->_blocktypedefs);
1872 while (vec_size(parser->_typedefs) != typedefs) {
1873 ast_delete(vec_last(parser->_typedefs));
1874 vec_pop(parser->_typedefs);
1876 util_htdel(vec_last(parser->typedefs));
1877 vec_pop(parser->typedefs);
1879 vec_pop(parser->_block_ctx);
1883 static void parser_addlocal(parser_t *parser, const char *name, ast_expression *e)
1885 vec_push(parser->_locals, e);
1886 util_htset(vec_last(parser->variables), name, (void*)e);
1889 static ast_expression* process_condition(parser_t *parser, ast_expression *cond, bool *_ifnot)
1893 ast_expression *prev;
1895 if (OPTS_FLAG(FALSE_EMPTY_STRINGS) && cond->expression.vtype == TYPE_STRING)
1898 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_S, cond);
1901 parseerror(parser, "internal error: failed to process condition");
1906 else if (OPTS_FLAG(CORRECT_LOGIC) && cond->expression.vtype == TYPE_VECTOR)
1908 /* vector types need to be cast to true booleans */
1909 ast_binary *bin = (ast_binary*)cond;
1910 if (!OPTS_FLAG(PERL_LOGIC) || !ast_istype(cond, ast_binary) || !(bin->op == INSTR_AND || bin->op == INSTR_OR))
1912 /* in perl-logic, AND and OR take care of the -fcorrect-logic */
1914 cond = (ast_expression*)ast_unary_new(ast_ctx(cond), INSTR_NOT_V, cond);
1917 parseerror(parser, "internal error: failed to process condition");
1924 unary = (ast_unary*)cond;
1925 while (ast_istype(cond, ast_unary) && unary->op == INSTR_NOT_F)
1927 cond = unary->operand;
1928 unary->operand = NULL;
1931 unary = (ast_unary*)cond;
1935 parseerror(parser, "internal error: failed to process condition");
1937 if (ifnot) *_ifnot = !*_ifnot;
1941 static bool parse_if(parser_t *parser, ast_block *block, ast_expression **out)
1944 ast_expression *cond, *ontrue = NULL, *onfalse = NULL;
1947 lex_ctx ctx = parser_ctx(parser);
1949 (void)block; /* not touching */
1951 /* skip the 'if', parse an optional 'not' and check for an opening paren */
1952 if (!parser_next(parser)) {
1953 parseerror(parser, "expected condition or 'not'");
1956 if (parser->tok == TOKEN_IDENT && !strcmp(parser_tokval(parser), "not")) {
1958 if (!parser_next(parser)) {
1959 parseerror(parser, "expected condition in parenthesis");
1963 if (parser->tok != '(') {
1964 parseerror(parser, "expected 'if' condition in parenthesis");
1967 /* parse into the expression */
1968 if (!parser_next(parser)) {
1969 parseerror(parser, "expected 'if' condition after opening paren");
1972 /* parse the condition */
1973 cond = parse_expression_leave(parser, false);
1977 if (parser->tok != ')') {
1978 parseerror(parser, "expected closing paren after 'if' condition");
1982 /* parse into the 'then' branch */
1983 if (!parser_next(parser)) {
1984 parseerror(parser, "expected statement for on-true branch of 'if'");
1988 if (!parse_statement_or_block(parser, &ontrue)) {
1992 /* check for an else */
1993 if (!strcmp(parser_tokval(parser), "else")) {
1994 /* parse into the 'else' branch */
1995 if (!parser_next(parser)) {
1996 parseerror(parser, "expected on-false branch after 'else'");
2001 if (!parse_statement_or_block(parser, &onfalse)) {
2008 cond = process_condition(parser, cond, &ifnot);
2010 if (ontrue) ast_delete(ontrue);
2011 if (onfalse) ast_delete(onfalse);
2016 ifthen = ast_ifthen_new(ctx, cond, onfalse, ontrue);
2018 ifthen = ast_ifthen_new(ctx, cond, ontrue, onfalse);
2019 *out = (ast_expression*)ifthen;
2023 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out);
2024 static bool parse_while(parser_t *parser, ast_block *block, ast_expression **out)
2029 /* skip the 'while' and get the body */
2030 if (!parser_next(parser)) {
2031 if (OPTS_FLAG(LOOP_LABELS))
2032 parseerror(parser, "expected loop label or 'while' condition in parenthesis");
2034 parseerror(parser, "expected 'while' condition in parenthesis");
2038 if (parser->tok == ':') {
2039 if (!OPTS_FLAG(LOOP_LABELS))
2040 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2041 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2042 parseerror(parser, "expected loop label");
2045 label = util_strdup(parser_tokval(parser));
2046 if (!parser_next(parser)) {
2048 parseerror(parser, "expected 'while' condition in parenthesis");
2053 if (parser->tok != '(') {
2054 parseerror(parser, "expected 'while' condition in parenthesis");
2058 vec_push(parser->breaks, label);
2059 vec_push(parser->continues, label);
2061 rv = parse_while_go(parser, block, out);
2064 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2065 parseerror(parser, "internal error: label stack corrupted");
2071 vec_pop(parser->breaks);
2072 vec_pop(parser->continues);
2077 static bool parse_while_go(parser_t *parser, ast_block *block, ast_expression **out)
2080 ast_expression *cond, *ontrue;
2084 lex_ctx ctx = parser_ctx(parser);
2086 (void)block; /* not touching */
2088 /* parse into the expression */
2089 if (!parser_next(parser)) {
2090 parseerror(parser, "expected 'while' condition after opening paren");
2093 /* parse the condition */
2094 cond = parse_expression_leave(parser, false);
2098 if (parser->tok != ')') {
2099 parseerror(parser, "expected closing paren after 'while' condition");
2103 /* parse into the 'then' branch */
2104 if (!parser_next(parser)) {
2105 parseerror(parser, "expected while-loop body");
2109 if (!parse_statement_or_block(parser, &ontrue)) {
2114 cond = process_condition(parser, cond, &ifnot);
2119 aloop = ast_loop_new(ctx, NULL, cond, ifnot, NULL, false, NULL, ontrue);
2120 *out = (ast_expression*)aloop;
2124 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out);
2125 static bool parse_dowhile(parser_t *parser, ast_block *block, ast_expression **out)
2130 /* skip the 'do' and get the body */
2131 if (!parser_next(parser)) {
2132 if (OPTS_FLAG(LOOP_LABELS))
2133 parseerror(parser, "expected loop label or body");
2135 parseerror(parser, "expected loop body");
2139 if (parser->tok == ':') {
2140 if (!OPTS_FLAG(LOOP_LABELS))
2141 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2142 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2143 parseerror(parser, "expected loop label");
2146 label = util_strdup(parser_tokval(parser));
2147 if (!parser_next(parser)) {
2149 parseerror(parser, "expected loop body");
2154 vec_push(parser->breaks, label);
2155 vec_push(parser->continues, label);
2157 rv = parse_dowhile_go(parser, block, out);
2160 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2161 parseerror(parser, "internal error: label stack corrupted");
2167 vec_pop(parser->breaks);
2168 vec_pop(parser->continues);
2173 static bool parse_dowhile_go(parser_t *parser, ast_block *block, ast_expression **out)
2176 ast_expression *cond, *ontrue;
2180 lex_ctx ctx = parser_ctx(parser);
2182 (void)block; /* not touching */
2184 if (!parse_statement_or_block(parser, &ontrue))
2187 /* expect the "while" */
2188 if (parser->tok != TOKEN_KEYWORD ||
2189 strcmp(parser_tokval(parser), "while"))
2191 parseerror(parser, "expected 'while' and condition");
2196 /* skip the 'while' and check for opening paren */
2197 if (!parser_next(parser) || parser->tok != '(') {
2198 parseerror(parser, "expected 'while' condition in parenthesis");
2202 /* parse into the expression */
2203 if (!parser_next(parser)) {
2204 parseerror(parser, "expected 'while' condition after opening paren");
2208 /* parse the condition */
2209 cond = parse_expression_leave(parser, false);
2213 if (parser->tok != ')') {
2214 parseerror(parser, "expected closing paren after 'while' condition");
2220 if (!parser_next(parser) || parser->tok != ';') {
2221 parseerror(parser, "expected semicolon after condition");
2227 if (!parser_next(parser)) {
2228 parseerror(parser, "parse error");
2234 cond = process_condition(parser, cond, &ifnot);
2239 aloop = ast_loop_new(ctx, NULL, NULL, false, cond, ifnot, NULL, ontrue);
2240 *out = (ast_expression*)aloop;
2244 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out);
2245 static bool parse_for(parser_t *parser, ast_block *block, ast_expression **out)
2250 /* skip the 'for' and check for opening paren */
2251 if (!parser_next(parser)) {
2252 if (OPTS_FLAG(LOOP_LABELS))
2253 parseerror(parser, "expected loop label or 'for' expressions in parenthesis");
2255 parseerror(parser, "expected 'for' expressions in parenthesis");
2259 if (parser->tok == ':') {
2260 if (!OPTS_FLAG(LOOP_LABELS))
2261 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2262 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2263 parseerror(parser, "expected loop label");
2266 label = util_strdup(parser_tokval(parser));
2267 if (!parser_next(parser)) {
2269 parseerror(parser, "expected 'for' expressions in parenthesis");
2274 if (parser->tok != '(') {
2275 parseerror(parser, "expected 'for' expressions in parenthesis");
2279 vec_push(parser->breaks, label);
2280 vec_push(parser->continues, label);
2282 rv = parse_for_go(parser, block, out);
2285 if (vec_last(parser->breaks) != label || vec_last(parser->continues) != label) {
2286 parseerror(parser, "internal error: label stack corrupted");
2292 vec_pop(parser->breaks);
2293 vec_pop(parser->continues);
2297 static bool parse_for_go(parser_t *parser, ast_block *block, ast_expression **out)
2300 ast_expression *initexpr, *cond, *increment, *ontrue;
2306 lex_ctx ctx = parser_ctx(parser);
2308 parser_enterblock(parser);
2315 /* parse into the expression */
2316 if (!parser_next(parser)) {
2317 parseerror(parser, "expected 'for' initializer after opening paren");
2322 if (parser->tok == TOKEN_IDENT)
2323 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2325 if (typevar || parser->tok == TOKEN_TYPENAME) {
2326 if (opts.standard != COMPILER_GMQCC) {
2327 if (parsewarning(parser, WARN_EXTENSIONS,
2328 "current standard does not allow variable declarations in for-loop initializers"))
2331 if (!parse_variable(parser, block, true, CV_VAR, typevar, false, false, false))
2334 else if (parser->tok != ';')
2336 initexpr = parse_expression_leave(parser, false);
2341 /* move on to condition */
2342 if (parser->tok != ';') {
2343 parseerror(parser, "expected semicolon after for-loop initializer");
2346 if (!parser_next(parser)) {
2347 parseerror(parser, "expected for-loop condition");
2351 /* parse the condition */
2352 if (parser->tok != ';') {
2353 cond = parse_expression_leave(parser, false);
2358 /* move on to incrementor */
2359 if (parser->tok != ';') {
2360 parseerror(parser, "expected semicolon after for-loop initializer");
2363 if (!parser_next(parser)) {
2364 parseerror(parser, "expected for-loop condition");
2368 /* parse the incrementor */
2369 if (parser->tok != ')') {
2370 increment = parse_expression_leave(parser, false);
2373 if (!ast_side_effects(increment)) {
2374 if (genwarning(ast_ctx(increment), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
2380 if (parser->tok != ')') {
2381 parseerror(parser, "expected closing paren after 'for-loop' incrementor");
2384 /* parse into the 'then' branch */
2385 if (!parser_next(parser)) {
2386 parseerror(parser, "expected for-loop body");
2389 if (!parse_statement_or_block(parser, &ontrue))
2393 cond = process_condition(parser, cond, &ifnot);
2397 aloop = ast_loop_new(ctx, initexpr, cond, ifnot, NULL, false, increment, ontrue);
2398 *out = (ast_expression*)aloop;
2400 if (!parser_leaveblock(parser))
2404 if (initexpr) ast_delete(initexpr);
2405 if (cond) ast_delete(cond);
2406 if (increment) ast_delete(increment);
2407 (void)!parser_leaveblock(parser);
2411 static bool parse_return(parser_t *parser, ast_block *block, ast_expression **out)
2413 ast_expression *exp = NULL;
2414 ast_return *ret = NULL;
2415 ast_value *expected = parser->function->vtype;
2417 lex_ctx ctx = parser_ctx(parser);
2419 (void)block; /* not touching */
2421 if (!parser_next(parser)) {
2422 parseerror(parser, "expected return expression");
2426 if (parser->tok != ';') {
2427 exp = parse_expression(parser, false);
2431 if (exp->expression.vtype != expected->expression.next->expression.vtype) {
2432 parseerror(parser, "return with invalid expression");
2435 ret = ast_return_new(ctx, exp);
2441 if (!parser_next(parser))
2442 parseerror(parser, "parse error");
2443 if (expected->expression.next->expression.vtype != TYPE_VOID) {
2444 if (opts.standard != COMPILER_GMQCC)
2445 (void)!parsewarning(parser, WARN_MISSING_RETURN_VALUES, "return without value");
2447 parseerror(parser, "return without value");
2449 ret = ast_return_new(ctx, NULL);
2451 *out = (ast_expression*)ret;
2455 static bool parse_break_continue(parser_t *parser, ast_block *block, ast_expression **out, bool is_continue)
2458 unsigned int levels = 0;
2459 lex_ctx ctx = parser_ctx(parser);
2460 const char **loops = (is_continue ? parser->continues : parser->breaks);
2462 (void)block; /* not touching */
2463 if (!parser_next(parser)) {
2464 parseerror(parser, "expected semicolon or loop label");
2468 if (parser->tok == TOKEN_IDENT) {
2469 if (!OPTS_FLAG(LOOP_LABELS))
2470 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2471 i = vec_size(loops);
2473 if (loops[i] && !strcmp(loops[i], parser_tokval(parser)))
2476 parseerror(parser, "no such loop to %s: `%s`",
2477 (is_continue ? "continue" : "break out of"),
2478 parser_tokval(parser));
2483 if (!parser_next(parser)) {
2484 parseerror(parser, "expected semicolon");
2489 if (parser->tok != ';') {
2490 parseerror(parser, "expected semicolon");
2494 if (!parser_next(parser))
2495 parseerror(parser, "parse error");
2497 *out = (ast_expression*)ast_breakcont_new(ctx, is_continue, levels);
2501 /* returns true when it was a variable qualifier, false otherwise!
2502 * on error, cvq is set to CV_WRONG
2504 static bool parse_var_qualifiers(parser_t *parser, bool with_local, int *cvq, bool *noref, bool *noreturn, bool *is_static)
2506 bool had_const = false;
2507 bool had_var = false;
2508 bool had_noref = false;
2509 bool had_noreturn = false;
2510 bool had_attrib = false;
2511 bool had_static = false;
2515 if (parser->tok == TOKEN_ATTRIBUTE_OPEN) {
2517 /* parse an attribute */
2518 if (!parser_next(parser)) {
2519 parseerror(parser, "expected attribute after `[[`");
2523 if (!strcmp(parser_tokval(parser), "noreturn")) {
2524 had_noreturn = true;
2525 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2526 parseerror(parser, "`noreturn` attribute has no parameters, expected `]]`");
2531 else if (!strcmp(parser_tokval(parser), "noref")) {
2533 if (!parser_next(parser) || parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2534 parseerror(parser, "`noref` attribute has no parameters, expected `]]`");
2541 /* Skip tokens until we hit a ]] */
2542 (void)!parsewarning(parser, WARN_UNKNOWN_ATTRIBUTE, "unknown attribute starting with `%s`", parser_tokval(parser));
2543 while (parser->tok != TOKEN_ATTRIBUTE_CLOSE) {
2544 if (!parser_next(parser)) {
2545 parseerror(parser, "error inside attribute");
2552 else if (!strcmp(parser_tokval(parser), "static"))
2554 else if (!strcmp(parser_tokval(parser), "const"))
2556 else if (!strcmp(parser_tokval(parser), "var"))
2558 else if (with_local && !strcmp(parser_tokval(parser), "local"))
2560 else if (!strcmp(parser_tokval(parser), "noref"))
2562 else if (!had_const && !had_var && !had_noref && !had_noreturn && !had_attrib && !had_static) {
2567 if (!parser_next(parser))
2577 *noreturn = had_noreturn;
2578 *is_static = had_static;
2581 parseerror(parser, "parse error after variable qualifier");
2586 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out);
2587 static bool parse_switch(parser_t *parser, ast_block *block, ast_expression **out)
2592 /* skip the 'while' and get the body */
2593 if (!parser_next(parser)) {
2594 if (OPTS_FLAG(LOOP_LABELS))
2595 parseerror(parser, "expected loop label or 'switch' operand in parenthesis");
2597 parseerror(parser, "expected 'switch' operand in parenthesis");
2601 if (parser->tok == ':') {
2602 if (!OPTS_FLAG(LOOP_LABELS))
2603 parseerror(parser, "labeled loops not activated, try using -floop-labels");
2604 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2605 parseerror(parser, "expected loop label");
2608 label = util_strdup(parser_tokval(parser));
2609 if (!parser_next(parser)) {
2611 parseerror(parser, "expected 'switch' operand in parenthesis");
2616 if (parser->tok != '(') {
2617 parseerror(parser, "expected 'switch' operand in parenthesis");
2621 vec_push(parser->breaks, label);
2623 rv = parse_switch_go(parser, block, out);
2626 if (vec_last(parser->breaks) != label) {
2627 parseerror(parser, "internal error: label stack corrupted");
2633 vec_pop(parser->breaks);
2638 static bool parse_switch_go(parser_t *parser, ast_block *block, ast_expression **out)
2640 ast_expression *operand;
2643 ast_switch *switchnode;
2644 ast_switch_case swcase;
2647 bool noref, noreturn, is_static;
2649 lex_ctx ctx = parser_ctx(parser);
2651 (void)block; /* not touching */
2654 /* parse into the expression */
2655 if (!parser_next(parser)) {
2656 parseerror(parser, "expected switch operand");
2659 /* parse the operand */
2660 operand = parse_expression_leave(parser, false);
2664 switchnode = ast_switch_new(ctx, operand);
2667 if (parser->tok != ')') {
2668 ast_delete(switchnode);
2669 parseerror(parser, "expected closing paren after 'switch' operand");
2673 /* parse over the opening paren */
2674 if (!parser_next(parser) || parser->tok != '{') {
2675 ast_delete(switchnode);
2676 parseerror(parser, "expected list of cases");
2680 if (!parser_next(parser)) {
2681 ast_delete(switchnode);
2682 parseerror(parser, "expected 'case' or 'default'");
2686 /* new block; allow some variables to be declared here */
2687 parser_enterblock(parser);
2690 if (parser->tok == TOKEN_IDENT)
2691 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2692 if (typevar || parser->tok == TOKEN_TYPENAME) {
2693 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false)) {
2694 ast_delete(switchnode);
2699 if (parse_var_qualifiers(parser, true, &cvq, &noref, &noreturn, &is_static))
2701 if (cvq == CV_WRONG) {
2702 ast_delete(switchnode);
2705 if (!parse_variable(parser, block, false, cvq, NULL, noref, noreturn, is_static)) {
2706 ast_delete(switchnode);
2715 while (parser->tok != '}') {
2716 ast_block *caseblock;
2718 if (!strcmp(parser_tokval(parser), "case")) {
2719 if (!parser_next(parser)) {
2720 ast_delete(switchnode);
2721 parseerror(parser, "expected expression for case");
2724 swcase.value = parse_expression_leave(parser, false);
2725 if (!swcase.value) {
2726 ast_delete(switchnode);
2727 parseerror(parser, "expected expression for case");
2730 if (!OPTS_FLAG(RELAXED_SWITCH)) {
2731 if (!ast_istype(swcase.value, ast_value)) { /* || ((ast_value*)swcase.value)->cvq != CV_CONST) { */
2732 parseerror(parser, "case on non-constant values need to be explicitly enabled via -frelaxed-switch");
2738 else if (!strcmp(parser_tokval(parser), "default")) {
2739 swcase.value = NULL;
2740 if (!parser_next(parser)) {
2741 ast_delete(switchnode);
2742 parseerror(parser, "expected colon");
2747 ast_delete(switchnode);
2748 parseerror(parser, "expected 'case' or 'default'");
2752 /* Now the colon and body */
2753 if (parser->tok != ':') {
2754 if (swcase.value) ast_unref(swcase.value);
2755 ast_delete(switchnode);
2756 parseerror(parser, "expected colon");
2760 if (!parser_next(parser)) {
2761 if (swcase.value) ast_unref(swcase.value);
2762 ast_delete(switchnode);
2763 parseerror(parser, "expected statements or case");
2766 caseblock = ast_block_new(parser_ctx(parser));
2768 if (swcase.value) ast_unref(swcase.value);
2769 ast_delete(switchnode);
2772 swcase.code = (ast_expression*)caseblock;
2773 vec_push(switchnode->cases, swcase);
2775 ast_expression *expr;
2776 if (parser->tok == '}')
2778 if (parser->tok == TOKEN_KEYWORD) {
2779 if (!strcmp(parser_tokval(parser), "case") ||
2780 !strcmp(parser_tokval(parser), "default"))
2785 if (!parse_statement(parser, caseblock, &expr, true)) {
2786 ast_delete(switchnode);
2791 if (!ast_block_add_expr(caseblock, expr)) {
2792 ast_delete(switchnode);
2798 parser_leaveblock(parser);
2801 if (parser->tok != '}') {
2802 ast_delete(switchnode);
2803 parseerror(parser, "expected closing paren of case list");
2806 if (!parser_next(parser)) {
2807 ast_delete(switchnode);
2808 parseerror(parser, "parse error after switch");
2811 *out = (ast_expression*)switchnode;
2815 static bool parse_goto(parser_t *parser, ast_expression **out)
2820 if (!parser_next(parser) || parser->tok != TOKEN_IDENT) {
2821 parseerror(parser, "expected label name after `goto`");
2825 gt = ast_goto_new(parser_ctx(parser), parser_tokval(parser));
2827 for (i = 0; i < vec_size(parser->labels); ++i) {
2828 if (!strcmp(parser->labels[i]->name, parser_tokval(parser))) {
2829 ast_goto_set_label(gt, parser->labels[i]);
2833 if (i == vec_size(parser->labels))
2834 vec_push(parser->gotos, gt);
2836 if (!parser_next(parser) || parser->tok != ';') {
2837 parseerror(parser, "semicolon expected after goto label");
2840 if (!parser_next(parser)) {
2841 parseerror(parser, "parse error after goto");
2845 *out = (ast_expression*)gt;
2849 static bool parse_skipwhite(parser_t *parser)
2852 if (!parser_next(parser))
2854 } while (parser->tok == TOKEN_WHITE && parser->tok < TOKEN_ERROR);
2855 return parser->tok < TOKEN_ERROR;
2858 static bool parse_eol(parser_t *parser)
2860 if (!parse_skipwhite(parser))
2862 return parser->tok == TOKEN_EOL;
2865 static bool parse_pragma_do(parser_t *parser)
2867 if (!parser_next(parser) ||
2868 parser->tok != TOKEN_IDENT ||
2869 strcmp(parser_tokval(parser), "pragma"))
2871 parseerror(parser, "expected `pragma` keyword after `#`, got `%s`", parser_tokval(parser));
2874 if (!parse_skipwhite(parser) || parser->tok != TOKEN_IDENT) {
2875 parseerror(parser, "expected pragma, got `%s`", parser_tokval(parser));
2879 if (!strcmp(parser_tokval(parser), "noref")) {
2880 if (!parse_skipwhite(parser) || parser->tok != TOKEN_INTCONST) {
2881 parseerror(parser, "`noref` pragma requires an argument: 0 or 1");
2884 parser->noref = !!parser_token(parser)->constval.i;
2885 if (!parse_eol(parser)) {
2886 parseerror(parser, "parse error after `noref` pragma");
2892 (void)!parsewarning(parser, WARN_UNKNOWN_PRAGMAS, "ignoring #pragma %s", parser_tokval(parser));
2899 static bool parse_pragma(parser_t *parser)
2902 parser->lex->flags.preprocessing = true;
2903 parser->lex->flags.mergelines = true;
2904 rv = parse_pragma_do(parser);
2905 if (parser->tok != TOKEN_EOL) {
2906 parseerror(parser, "junk after pragma");
2909 parser->lex->flags.preprocessing = false;
2910 parser->lex->flags.mergelines = false;
2911 if (!parser_next(parser)) {
2912 parseerror(parser, "parse error after pragma");
2918 static bool parse_statement(parser_t *parser, ast_block *block, ast_expression **out, bool allow_cases)
2920 bool noref, noreturn, is_static;
2922 ast_value *typevar = NULL;
2926 if (parser->tok == TOKEN_IDENT)
2927 typevar = parser_find_typedef(parser, parser_tokval(parser), 0);
2929 if (typevar || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
2931 /* local variable */
2933 parseerror(parser, "cannot declare a variable from here");
2936 if (opts.standard == COMPILER_QCC) {
2937 if (parsewarning(parser, WARN_EXTENSIONS, "missing 'local' keyword when declaring a local variable"))
2940 if (!parse_variable(parser, block, false, CV_NONE, typevar, false, false, false))
2944 else if (parse_var_qualifiers(parser, !!block, &cvq, &noref, &noreturn, &is_static))
2946 if (cvq == CV_WRONG)
2948 return parse_variable(parser, block, true, cvq, NULL, noref, noreturn, is_static);
2950 else if (parser->tok == TOKEN_KEYWORD)
2952 if (!strcmp(parser_tokval(parser), "__builtin_debug_printtype"))
2957 if (!parser_next(parser)) {
2958 parseerror(parser, "parse error after __builtin_debug_printtype");
2962 if (parser->tok == TOKEN_IDENT && (tdef = parser_find_typedef(parser, parser_tokval(parser), 0)))
2964 ast_type_to_string((ast_expression*)tdef, ty, sizeof(ty));
2965 con_out("__builtin_debug_printtype: `%s`=`%s`\n", tdef->name, ty);
2966 if (!parser_next(parser)) {
2967 parseerror(parser, "parse error after __builtin_debug_printtype typename argument");
2973 if (!parse_statement(parser, block, out, allow_cases))
2976 con_out("__builtin_debug_printtype: got no output node\n");
2979 ast_type_to_string(*out, ty, sizeof(ty));
2980 con_out("__builtin_debug_printtype: `%s`\n", ty);
2985 else if (!strcmp(parser_tokval(parser), "return"))
2987 return parse_return(parser, block, out);
2989 else if (!strcmp(parser_tokval(parser), "if"))
2991 return parse_if(parser, block, out);
2993 else if (!strcmp(parser_tokval(parser), "while"))
2995 return parse_while(parser, block, out);
2997 else if (!strcmp(parser_tokval(parser), "do"))
2999 return parse_dowhile(parser, block, out);
3001 else if (!strcmp(parser_tokval(parser), "for"))
3003 if (opts.standard == COMPILER_QCC) {
3004 if (parsewarning(parser, WARN_EXTENSIONS, "for loops are not recognized in the original Quake C standard, to enable try an alternate standard --std=?"))
3007 return parse_for(parser, block, out);
3009 else if (!strcmp(parser_tokval(parser), "break"))
3011 return parse_break_continue(parser, block, out, false);
3013 else if (!strcmp(parser_tokval(parser), "continue"))
3015 return parse_break_continue(parser, block, out, true);
3017 else if (!strcmp(parser_tokval(parser), "switch"))
3019 return parse_switch(parser, block, out);
3021 else if (!strcmp(parser_tokval(parser), "case") ||
3022 !strcmp(parser_tokval(parser), "default"))
3025 parseerror(parser, "unexpected 'case' label");
3030 else if (!strcmp(parser_tokval(parser), "goto"))
3032 return parse_goto(parser, out);
3034 else if (!strcmp(parser_tokval(parser), "typedef"))
3036 if (!parser_next(parser)) {
3037 parseerror(parser, "expected type definition after 'typedef'");
3040 return parse_typedef(parser);
3042 parseerror(parser, "Unexpected keyword");
3045 else if (parser->tok == '{')
3048 inner = parse_block(parser);
3051 *out = (ast_expression*)inner;
3054 else if (parser->tok == ':')
3058 if (!parser_next(parser)) {
3059 parseerror(parser, "expected label name");
3062 if (parser->tok != TOKEN_IDENT) {
3063 parseerror(parser, "label must be an identifier");
3066 label = ast_label_new(parser_ctx(parser), parser_tokval(parser));
3069 vec_push(parser->labels, label);
3070 *out = (ast_expression*)label;
3071 if (!parser_next(parser)) {
3072 parseerror(parser, "parse error after label");
3075 for (i = 0; i < vec_size(parser->gotos); ++i) {
3076 if (!strcmp(parser->gotos[i]->name, label->name)) {
3077 ast_goto_set_label(parser->gotos[i], label);
3078 vec_remove(parser->gotos, i, 1);
3084 else if (parser->tok == ';')
3086 if (!parser_next(parser)) {
3087 parseerror(parser, "parse error after empty statement");
3094 ast_expression *exp = parse_expression(parser, false);
3098 if (!ast_side_effects(exp)) {
3099 if (genwarning(ast_ctx(exp), WARN_EFFECTLESS_STATEMENT, "statement has no effect"))
3106 static bool parse_block_into(parser_t *parser, ast_block *block)
3110 parser_enterblock(parser);
3112 if (!parser_next(parser)) { /* skip the '{' */
3113 parseerror(parser, "expected function body");
3117 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
3119 ast_expression *expr = NULL;
3120 if (parser->tok == '}')
3123 if (!parse_statement(parser, block, &expr, false)) {
3124 /* parseerror(parser, "parse error"); */
3130 if (!ast_block_add_expr(block, expr)) {
3137 if (parser->tok != '}') {
3140 (void)parser_next(parser);
3144 if (!parser_leaveblock(parser))
3146 return retval && !!block;
3149 static ast_block* parse_block(parser_t *parser)
3152 block = ast_block_new(parser_ctx(parser));
3155 if (!parse_block_into(parser, block)) {
3156 ast_block_delete(block);
3162 static bool parse_statement_or_block(parser_t *parser, ast_expression **out)
3164 if (parser->tok == '{') {
3165 *out = (ast_expression*)parse_block(parser);
3168 return parse_statement(parser, NULL, out, false);
3171 static bool create_vector_members(ast_value *var, ast_member **me)
3174 size_t len = strlen(var->name);
3176 for (i = 0; i < 3; ++i) {
3177 char *name = (char*)mem_a(len+3);
3178 memcpy(name, var->name, len);
3180 name[len+1] = 'x'+i;
3182 me[i] = ast_member_new(ast_ctx(var), (ast_expression*)var, i, name);
3191 do { ast_member_delete(me[--i]); } while(i);
3195 static bool parse_function_body(parser_t *parser, ast_value *var)
3197 ast_block *block = NULL;
3202 ast_expression *framenum = NULL;
3203 ast_expression *nextthink = NULL;
3204 /* None of the following have to be deleted */
3205 ast_expression *fld_think = NULL, *fld_nextthink = NULL, *fld_frame = NULL;
3206 ast_expression *gbl_time = NULL, *gbl_self = NULL;
3207 bool has_frame_think;
3211 has_frame_think = false;
3212 old = parser->function;
3214 if (vec_size(parser->gotos) || vec_size(parser->labels)) {
3215 parseerror(parser, "gotos/labels leaking");
3219 if (var->expression.flags & AST_FLAG_VARIADIC) {
3220 if (parsewarning(parser, WARN_VARIADIC_FUNCTION,
3221 "variadic function with implementation will not be able to access additional parameters"))
3227 if (parser->tok == '[') {
3228 /* got a frame definition: [ framenum, nextthink ]
3229 * this translates to:
3230 * self.frame = framenum;
3231 * self.nextthink = time + 0.1;
3232 * self.think = nextthink;
3236 fld_think = parser_find_field(parser, "think");
3237 fld_nextthink = parser_find_field(parser, "nextthink");
3238 fld_frame = parser_find_field(parser, "frame");
3239 if (!fld_think || !fld_nextthink || !fld_frame) {
3240 parseerror(parser, "cannot use [frame,think] notation without the required fields");
3241 parseerror(parser, "please declare the following entityfields: `frame`, `think`, `nextthink`");
3244 gbl_time = parser_find_global(parser, "time");
3245 gbl_self = parser_find_global(parser, "self");
3246 if (!gbl_time || !gbl_self) {
3247 parseerror(parser, "cannot use [frame,think] notation without the required globals");
3248 parseerror(parser, "please declare the following globals: `time`, `self`");
3252 if (!parser_next(parser))
3255 framenum = parse_expression_leave(parser, true);
3257 parseerror(parser, "expected a framenumber constant in[frame,think] notation");
3260 if (!ast_istype(framenum, ast_value) || !( (ast_value*)framenum )->hasvalue) {
3261 ast_unref(framenum);
3262 parseerror(parser, "framenumber in [frame,think] notation must be a constant");
3266 if (parser->tok != ',') {
3267 ast_unref(framenum);
3268 parseerror(parser, "expected comma after frame number in [frame,think] notation");
3269 parseerror(parser, "Got a %i\n", parser->tok);
3273 if (!parser_next(parser)) {
3274 ast_unref(framenum);
3278 if (parser->tok == TOKEN_IDENT && !parser_find_var(parser, parser_tokval(parser)))
3280 /* qc allows the use of not-yet-declared functions here
3281 * - this automatically creates a prototype */
3282 ast_value *thinkfunc;
3283 ast_expression *functype = fld_think->expression.next;
3285 thinkfunc = ast_value_new(parser_ctx(parser), parser_tokval(parser), functype->expression.vtype);
3286 if (!thinkfunc || !ast_type_adopt(thinkfunc, functype)) {
3287 ast_unref(framenum);
3288 parseerror(parser, "failed to create implicit prototype for `%s`", parser_tokval(parser));
3292 if (!parser_next(parser)) {
3293 ast_unref(framenum);
3294 ast_delete(thinkfunc);
3298 vec_push(parser->globals, (ast_expression*)thinkfunc);
3299 util_htset(parser->htglobals, thinkfunc->name, thinkfunc);
3300 nextthink = (ast_expression*)thinkfunc;
3303 nextthink = parse_expression_leave(parser, true);
3305 ast_unref(framenum);
3306 parseerror(parser, "expected a think-function in [frame,think] notation");
3311 if (!ast_istype(nextthink, ast_value)) {
3312 parseerror(parser, "think-function in [frame,think] notation must be a constant");
3316 if (retval && parser->tok != ']') {
3317 parseerror(parser, "expected closing `]` for [frame,think] notation");
3321 if (retval && !parser_next(parser)) {
3325 if (retval && parser->tok != '{') {
3326 parseerror(parser, "a function body has to be declared after a [frame,think] declaration");
3331 ast_unref(nextthink);
3332 ast_unref(framenum);
3336 has_frame_think = true;
3339 block = ast_block_new(parser_ctx(parser));
3341 parseerror(parser, "failed to allocate block");
3342 if (has_frame_think) {
3343 ast_unref(nextthink);
3344 ast_unref(framenum);
3349 if (has_frame_think) {
3351 ast_expression *self_frame;
3352 ast_expression *self_nextthink;
3353 ast_expression *self_think;
3354 ast_expression *time_plus_1;
3355 ast_store *store_frame;
3356 ast_store *store_nextthink;
3357 ast_store *store_think;
3359 ctx = parser_ctx(parser);
3360 self_frame = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_frame);
3361 self_nextthink = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_nextthink);
3362 self_think = (ast_expression*)ast_entfield_new(ctx, gbl_self, fld_think);
3364 time_plus_1 = (ast_expression*)ast_binary_new(ctx, INSTR_ADD_F,
3365 gbl_time, (ast_expression*)parser_const_float(parser, 0.1));
3367 if (!self_frame || !self_nextthink || !self_think || !time_plus_1) {
3368 if (self_frame) ast_delete(self_frame);
3369 if (self_nextthink) ast_delete(self_nextthink);
3370 if (self_think) ast_delete(self_think);
3371 if (time_plus_1) ast_delete(time_plus_1);
3377 store_frame = ast_store_new(ctx, INSTR_STOREP_F, self_frame, framenum);
3378 store_nextthink = ast_store_new(ctx, INSTR_STOREP_F, self_nextthink, time_plus_1);
3379 store_think = ast_store_new(ctx, INSTR_STOREP_FNC, self_think, nextthink);
3382 ast_delete(self_frame);
3385 if (!store_nextthink) {
3386 ast_delete(self_nextthink);
3390 ast_delete(self_think);
3394 if (store_frame) ast_delete(store_frame);
3395 if (store_nextthink) ast_delete(store_nextthink);
3396 if (store_think) ast_delete(store_think);
3399 if (!ast_block_add_expr(block, (ast_expression*)store_frame) ||
3400 !ast_block_add_expr(block, (ast_expression*)store_nextthink) ||
3401 !ast_block_add_expr(block, (ast_expression*)store_think))
3408 parseerror(parser, "failed to generate code for [frame,think]");
3409 ast_unref(nextthink);
3410 ast_unref(framenum);
3416 parser_enterblock(parser);
3418 for (parami = 0; parami < vec_size(var->expression.params); ++parami) {
3420 ast_value *param = var->expression.params[parami];
3423 if (param->expression.vtype != TYPE_VECTOR &&
3424 (param->expression.vtype != TYPE_FIELD ||
3425 param->expression.next->expression.vtype != TYPE_VECTOR))
3430 if (!create_vector_members(param, me)) {
3431 ast_block_delete(block);
3435 for (e = 0; e < 3; ++e) {
3436 parser_addlocal(parser, me[e]->name, (ast_expression*)me[e]);
3437 ast_block_collect(block, (ast_expression*)me[e]);
3441 func = ast_function_new(ast_ctx(var), var->name, var);
3443 parseerror(parser, "failed to allocate function for `%s`", var->name);
3444 ast_block_delete(block);
3447 vec_push(parser->functions, func);
3449 parser->function = func;
3450 if (!parse_block_into(parser, block)) {
3451 ast_block_delete(block);
3455 vec_push(func->blocks, block);
3457 parser->function = old;
3458 if (!parser_leaveblock(parser))
3460 if (vec_size(parser->variables) != PARSER_HT_LOCALS) {
3461 parseerror(parser, "internal error: local scopes left");
3465 if (parser->tok == ';')
3466 return parser_next(parser);
3467 else if (opts.standard == COMPILER_QCC)
3468 parseerror(parser, "missing semicolon after function body (mandatory with -std=qcc)");
3472 vec_pop(parser->functions);
3473 ast_function_delete(func);
3474 var->constval.vfunc = NULL;
3477 (void)!parser_leaveblock(parser);
3478 parser->function = old;
3482 static ast_expression *array_accessor_split(
3487 ast_expression *left,
3488 ast_expression *right
3494 lex_ctx ctx = ast_ctx(array);
3496 if (!left || !right) {
3497 if (left) ast_delete(left);
3498 if (right) ast_delete(right);
3502 cmp = ast_binary_new(ctx, INSTR_LT,
3503 (ast_expression*)index,
3504 (ast_expression*)parser_const_float(parser, middle));
3508 parseerror(parser, "internal error: failed to create comparison for array setter");
3512 ifthen = ast_ifthen_new(ctx, (ast_expression*)cmp, left, right);
3514 ast_delete(cmp); /* will delete left and right */
3515 parseerror(parser, "internal error: failed to create conditional jump for array setter");
3519 return (ast_expression*)ifthen;
3522 static ast_expression *array_setter_node(parser_t *parser, ast_value *array, ast_value *index, ast_value *value, size_t from, size_t afterend)
3524 lex_ctx ctx = ast_ctx(array);
3526 if (from+1 == afterend) {
3527 /* set this value */
3530 ast_array_index *subscript;
3532 int assignop = type_store_instr[value->expression.vtype];
3534 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3535 assignop = INSTR_STORE_V;
3537 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3541 st = ast_store_new(ctx, assignop, (ast_expression*)subscript, (ast_expression*)value);
3543 ast_delete(subscript);
3547 block = ast_block_new(ctx);
3553 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3558 ret = ast_return_new(ctx, NULL);
3564 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3569 return (ast_expression*)block;
3571 ast_expression *left, *right;
3572 size_t diff = afterend - from;
3573 size_t middle = from + diff/2;
3574 left = array_setter_node(parser, array, index, value, from, middle);
3575 right = array_setter_node(parser, array, index, value, middle, afterend);
3576 return array_accessor_split(parser, array, index, middle, left, right);
3580 static ast_expression *array_field_setter_node(
3589 lex_ctx ctx = ast_ctx(array);
3591 if (from+1 == afterend) {
3592 /* set this value */
3595 ast_entfield *entfield;
3596 ast_array_index *subscript;
3598 int assignop = type_storep_instr[value->expression.vtype];
3600 if (value->expression.vtype == TYPE_FIELD && value->expression.next->expression.vtype == TYPE_VECTOR)
3601 assignop = INSTR_STOREP_V;
3603 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3607 entfield = ast_entfield_new_force(ctx,
3608 (ast_expression*)entity,
3609 (ast_expression*)subscript,
3610 (ast_expression*)subscript);
3612 ast_delete(subscript);
3616 st = ast_store_new(ctx, assignop, (ast_expression*)entfield, (ast_expression*)value);
3618 ast_delete(entfield);
3622 block = ast_block_new(ctx);
3628 if (!ast_block_add_expr(block, (ast_expression*)st)) {
3633 ret = ast_return_new(ctx, NULL);
3639 if (!ast_block_add_expr(block, (ast_expression*)ret)) {
3644 return (ast_expression*)block;
3646 ast_expression *left, *right;
3647 size_t diff = afterend - from;
3648 size_t middle = from + diff/2;
3649 left = array_field_setter_node(parser, array, entity, index, value, from, middle);
3650 right = array_field_setter_node(parser, array, entity, index, value, middle, afterend);
3651 return array_accessor_split(parser, array, index, middle, left, right);
3655 static ast_expression *array_getter_node(parser_t *parser, ast_value *array, ast_value *index, size_t from, size_t afterend)
3657 lex_ctx ctx = ast_ctx(array);
3659 if (from+1 == afterend) {
3661 ast_array_index *subscript;
3663 subscript = ast_array_index_new(ctx, (ast_expression*)array, (ast_expression*)parser_const_float(parser, from));
3667 ret = ast_return_new(ctx, (ast_expression*)subscript);
3669 ast_delete(subscript);
3673 return (ast_expression*)ret;
3675 ast_expression *left, *right;
3676 size_t diff = afterend - from;
3677 size_t middle = from + diff/2;
3678 left = array_getter_node(parser, array, index, from, middle);
3679 right = array_getter_node(parser, array, index, middle, afterend);
3680 return array_accessor_split(parser, array, index, middle, left, right);
3684 static bool parser_create_array_accessor(parser_t *parser, ast_value *array, const char *funcname, ast_value **out)
3686 ast_function *func = NULL;
3687 ast_value *fval = NULL;
3688 ast_block *body = NULL;
3690 fval = ast_value_new(ast_ctx(array), funcname, TYPE_FUNCTION);
3692 parseerror(parser, "failed to create accessor function value");
3696 func = ast_function_new(ast_ctx(array), funcname, fval);
3699 parseerror(parser, "failed to create accessor function node");
3703 body = ast_block_new(ast_ctx(array));
3705 parseerror(parser, "failed to create block for array accessor");
3711 vec_push(func->blocks, body);
3714 vec_push(parser->accessors, fval);
3719 static bool parser_create_array_setter(parser_t *parser, ast_value *array, const char *funcname)
3721 ast_expression *root = NULL;
3722 ast_value *index = NULL;
3723 ast_value *value = NULL;
3727 if (!ast_istype(array->expression.next, ast_value)) {
3728 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3732 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3734 func = fval->constval.vfunc;
3735 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3737 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3738 value = ast_value_copy((ast_value*)array->expression.next);
3740 if (!index || !value) {
3741 parseerror(parser, "failed to create locals for array accessor");
3744 (void)!ast_value_set_name(value, "value"); /* not important */
3745 vec_push(fval->expression.params, index);
3746 vec_push(fval->expression.params, value);
3748 root = array_setter_node(parser, array, index, value, 0, array->expression.count);
3750 parseerror(parser, "failed to build accessor search tree");
3754 array->setter = fval;
3755 return ast_block_add_expr(func->blocks[0], root);
3757 if (index) ast_delete(index);
3758 if (value) ast_delete(value);
3759 if (root) ast_delete(root);
3765 static bool parser_create_array_field_setter(parser_t *parser, ast_value *array, const char *funcname)
3767 ast_expression *root = NULL;
3768 ast_value *entity = NULL;
3769 ast_value *index = NULL;
3770 ast_value *value = NULL;
3774 if (!ast_istype(array->expression.next, ast_value)) {
3775 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3779 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3781 func = fval->constval.vfunc;
3782 fval->expression.next = (ast_expression*)ast_value_new(ast_ctx(array), "<void>", TYPE_VOID);
3784 entity = ast_value_new(ast_ctx(array), "entity", TYPE_ENTITY);
3785 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3786 value = ast_value_copy((ast_value*)array->expression.next);
3787 if (!entity || !index || !value) {
3788 parseerror(parser, "failed to create locals for array accessor");
3791 (void)!ast_value_set_name(value, "value"); /* not important */
3792 vec_push(fval->expression.params, entity);
3793 vec_push(fval->expression.params, index);
3794 vec_push(fval->expression.params, value);
3796 root = array_field_setter_node(parser, array, entity, index, value, 0, array->expression.count);
3798 parseerror(parser, "failed to build accessor search tree");
3802 array->setter = fval;
3803 return ast_block_add_expr(func->blocks[0], root);
3805 if (entity) ast_delete(entity);
3806 if (index) ast_delete(index);
3807 if (value) ast_delete(value);
3808 if (root) ast_delete(root);
3814 static bool parser_create_array_getter(parser_t *parser, ast_value *array, const ast_expression *elemtype, const char *funcname)
3816 ast_expression *root = NULL;
3817 ast_value *index = NULL;
3821 /* NOTE: checking array->expression.next rather than elemtype since
3822 * for fields elemtype is a temporary fieldtype.
3824 if (!ast_istype(array->expression.next, ast_value)) {
3825 parseerror(parser, "internal error: array accessor needs to build an ast_value with a copy of the element type");
3829 if (!parser_create_array_accessor(parser, array, funcname, &fval))
3831 func = fval->constval.vfunc;
3832 fval->expression.next = ast_type_copy(ast_ctx(array), elemtype);
3834 index = ast_value_new(ast_ctx(array), "index", TYPE_FLOAT);
3837 parseerror(parser, "failed to create locals for array accessor");
3840 vec_push(fval->expression.params, index);
3842 root = array_getter_node(parser, array, index, 0, array->expression.count);
3844 parseerror(parser, "failed to build accessor search tree");
3848 array->getter = fval;
3849 return ast_block_add_expr(func->blocks[0], root);
3851 if (index) ast_delete(index);
3852 if (root) ast_delete(root);
3858 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef);
3859 static ast_value *parse_parameter_list(parser_t *parser, ast_value *var)
3867 bool variadic = false;
3869 ctx = parser_ctx(parser);
3871 /* for the sake of less code we parse-in in this function */
3872 if (!parser_next(parser)) {
3873 parseerror(parser, "expected parameter list");
3879 /* parse variables until we hit a closing paren */
3880 while (parser->tok != ')') {
3882 /* there must be commas between them */
3883 if (parser->tok != ',') {
3884 parseerror(parser, "expected comma or end of parameter list");
3887 if (!parser_next(parser)) {
3888 parseerror(parser, "expected parameter");
3894 if (parser->tok == TOKEN_DOTS) {
3895 /* '...' indicates a varargs function */
3897 if (!parser_next(parser)) {
3898 parseerror(parser, "expected parameter");
3901 if (parser->tok != ')') {
3902 parseerror(parser, "`...` must be the last parameter of a variadic function declaration");
3908 /* for anything else just parse a typename */
3909 param = parse_typename(parser, NULL, NULL);
3912 vec_push(params, param);
3913 if (param->expression.vtype >= TYPE_VARIANT) {
3914 char tname[1024]; /* typename is reserved in C++ */
3915 ast_type_to_string((ast_expression*)param, tname, sizeof(tname));
3916 parseerror(parser, "type not supported as part of a parameter list: %s", tname);
3922 if (vec_size(params) == 1 && params[0]->expression.vtype == TYPE_VOID)
3926 if (vec_size(params) > 8 && opts.standard == COMPILER_QCC)
3927 (void)!parsewarning(parser, WARN_EXTENSIONS, "more than 8 parameters are not supported by this standard");
3930 if (!parser_next(parser)) {
3931 parseerror(parser, "parse error after typename");
3935 /* now turn 'var' into a function type */
3936 fval = ast_value_new(ctx, "<type()>", TYPE_FUNCTION);
3937 fval->expression.next = (ast_expression*)var;
3939 fval->expression.flags |= AST_FLAG_VARIADIC;
3942 var->expression.params = params;
3949 for (i = 0; i < vec_size(params); ++i)
3950 ast_delete(params[i]);
3955 static ast_value *parse_arraysize(parser_t *parser, ast_value *var)
3957 ast_expression *cexp;
3958 ast_value *cval, *tmp;
3961 ctx = parser_ctx(parser);
3963 if (!parser_next(parser)) {
3965 parseerror(parser, "expected array-size");
3969 cexp = parse_expression_leave(parser, true);
3971 if (!cexp || !ast_istype(cexp, ast_value)) {
3975 parseerror(parser, "expected array-size as constant positive integer");
3978 cval = (ast_value*)cexp;
3980 tmp = ast_value_new(ctx, "<type[]>", TYPE_ARRAY);
3981 tmp->expression.next = (ast_expression*)var;
3984 if (cval->expression.vtype == TYPE_INTEGER)
3985 tmp->expression.count = cval->constval.vint;
3986 else if (cval->expression.vtype == TYPE_FLOAT)
3987 tmp->expression.count = cval->constval.vfloat;
3991 parseerror(parser, "array-size must be a positive integer constant");
3996 if (parser->tok != ']') {
3998 parseerror(parser, "expected ']' after array-size");
4001 if (!parser_next(parser)) {
4003 parseerror(parser, "error after parsing array size");
4009 /* Parse a complete typename.
4010 * for single-variables (ie. function parameters or typedefs) storebase should be NULL
4011 * but when parsing variables separated by comma
4012 * 'storebase' should point to where the base-type should be kept.
4013 * The base type makes up every bit of type information which comes *before* the
4016 * The following will be parsed in its entirety:
4018 * The 'basetype' in this case is 'void()'
4019 * and if there's a comma after it, say:
4021 * then the type-information 'void()' can be stored in 'storebase'
4023 static ast_value *parse_typename(parser_t *parser, ast_value **storebase, ast_value *cached_typedef)
4025 ast_value *var, *tmp;
4028 const char *name = NULL;
4029 bool isfield = false;
4030 bool wasarray = false;
4031 size_t morefields = 0;
4033 ctx = parser_ctx(parser);
4035 /* types may start with a dot */
4036 if (parser->tok == '.') {
4038 /* if we parsed a dot we need a typename now */
4039 if (!parser_next(parser)) {
4040 parseerror(parser, "expected typename for field definition");
4044 /* Further dots are handled seperately because they won't be part of the
4047 while (parser->tok == '.') {
4049 if (!parser_next(parser)) {
4050 parseerror(parser, "expected typename for field definition");
4055 if (parser->tok == TOKEN_IDENT)
4056 cached_typedef = parser_find_typedef(parser, parser_tokval(parser), 0);
4057 if (!cached_typedef && parser->tok != TOKEN_TYPENAME) {
4058 parseerror(parser, "expected typename");
4062 /* generate the basic type value */
4063 if (cached_typedef) {
4064 var = ast_value_copy(cached_typedef);
4065 ast_value_set_name(var, "<type(from_def)>");
4067 var = ast_value_new(ctx, "<type>", parser_token(parser)->constval.t);
4069 for (; morefields; --morefields) {
4070 tmp = ast_value_new(ctx, "<.type>", TYPE_FIELD);
4071 tmp->expression.next = (ast_expression*)var;
4075 /* do not yet turn into a field - remember:
4076 * .void() foo; is a field too
4077 * .void()() foo; is a function
4081 if (!parser_next(parser)) {
4083 parseerror(parser, "parse error after typename");
4087 /* an opening paren now starts the parameter-list of a function
4088 * this is where original-QC has parameter lists.
4089 * We allow a single parameter list here.
4090 * Much like fteqcc we don't allow `float()() x`
4092 if (parser->tok == '(') {
4093 var = parse_parameter_list(parser, var);
4098 /* store the base if requested */
4100 *storebase = ast_value_copy(var);
4102 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4103 tmp->expression.next = (ast_expression*)*storebase;
4108 /* there may be a name now */
4109 if (parser->tok == TOKEN_IDENT) {
4110 name = util_strdup(parser_tokval(parser));
4112 if (!parser_next(parser)) {
4114 parseerror(parser, "error after variable or field declaration");
4119 /* now this may be an array */
4120 if (parser->tok == '[') {
4122 var = parse_arraysize(parser, var);
4127 /* This is the point where we can turn it into a field */
4129 /* turn it into a field if desired */
4130 tmp = ast_value_new(ctx, "<type:f>", TYPE_FIELD);
4131 tmp->expression.next = (ast_expression*)var;
4135 /* now there may be function parens again */
4136 if (parser->tok == '(' && opts.standard == COMPILER_QCC)
4137 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4138 if (parser->tok == '(' && wasarray)
4139 parseerror(parser, "arrays as part of a return type is not supported");
4140 while (parser->tok == '(') {
4141 var = parse_parameter_list(parser, var);
4150 /* finally name it */
4152 if (!ast_value_set_name(var, name)) {
4154 parseerror(parser, "internal error: failed to set name");
4157 /* free the name, ast_value_set_name duplicates */
4164 static bool parse_typedef(parser_t *parser)
4166 ast_value *typevar, *oldtype;
4167 ast_expression *old;
4169 typevar = parse_typename(parser, NULL, NULL);
4174 if ( (old = parser_find_var(parser, typevar->name)) ) {
4175 parseerror(parser, "cannot define a type with the same name as a variable: %s\n"
4176 " -> `%s` has been declared here: %s:%i",
4177 typevar->name, ast_ctx(old).file, ast_ctx(old).line);
4178 ast_delete(typevar);
4182 if ( (oldtype = parser_find_typedef(parser, typevar->name, vec_last(parser->_blocktypedefs))) ) {
4183 parseerror(parser, "type `%s` has already been declared here: %s:%i",
4184 typevar->name, ast_ctx(oldtype).file, ast_ctx(oldtype).line);
4185 ast_delete(typevar);
4189 vec_push(parser->_typedefs, typevar);
4190 util_htset(vec_last(parser->typedefs), typevar->name, typevar);
4192 if (parser->tok != ';') {
4193 parseerror(parser, "expected semicolon after typedef");
4196 if (!parser_next(parser)) {
4197 parseerror(parser, "parse error after typedef");
4204 static bool parse_variable(parser_t *parser, ast_block *localblock, bool nofields, int qualifier, ast_value *cached_typedef, bool noref, bool noreturn, bool is_static)
4208 ast_expression *old;
4212 ast_value *basetype = NULL;
4214 bool isparam = false;
4215 bool isvector = false;
4216 bool cleanvar = true;
4217 bool wasarray = false;
4221 if (!localblock && is_static)
4222 parseerror(parser, "`static` qualifier is not supported in global scope");
4224 /* get the first complete variable */
4225 var = parse_typename(parser, &basetype, cached_typedef);
4228 ast_delete(basetype);
4236 /* Part 0: finish the type */
4237 if (parser->tok == '(') {
4238 if (opts.standard == COMPILER_QCC)
4239 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4240 var = parse_parameter_list(parser, var);
4246 /* we only allow 1-dimensional arrays */
4247 if (parser->tok == '[') {
4249 var = parse_arraysize(parser, var);
4255 if (parser->tok == '(' && wasarray) {
4256 parseerror(parser, "arrays as part of a return type is not supported");
4257 /* we'll still parse the type completely for now */
4259 /* for functions returning functions */
4260 while (parser->tok == '(') {
4261 if (opts.standard == COMPILER_QCC)
4262 parseerror(parser, "C-style function syntax is not allowed in -std=qcc");
4263 var = parse_parameter_list(parser, var);
4270 var->cvq = qualifier;
4271 /* in a noref section we simply bump the usecount */
4272 if (noref || parser->noref)
4275 var->expression.flags |= AST_FLAG_NORETURN;
4278 * check for validity: (end_sys_..., multiple-definitions, prototypes, ...)
4279 * Also: if there was a prototype, `var` will be deleted and set to `proto` which
4280 * is then filled with the previous definition and the parameter-names replaced.
4283 /* Deal with end_sys_ vars */
4285 if (!strcmp(var->name, "end_sys_globals")) {
4287 parser->crc_globals = vec_size(parser->globals);
4290 else if (!strcmp(var->name, "end_sys_fields")) {
4292 parser->crc_fields = vec_size(parser->fields);
4295 if (was_end && var->expression.vtype == TYPE_FIELD) {
4296 if (parsewarning(parser, WARN_END_SYS_FIELDS,
4297 "global '%s' hint should not be a field",
4298 parser_tokval(parser)))
4305 if (!nofields && var->expression.vtype == TYPE_FIELD)
4307 /* deal with field declarations */
4308 old = parser_find_field(parser, var->name);
4310 if (parsewarning(parser, WARN_FIELD_REDECLARED, "field `%s` already declared here: %s:%i",
4311 var->name, ast_ctx(old).file, (int)ast_ctx(old).line))
4320 parseerror(parser, "field `%s` already declared here: %s:%i",
4321 var->name, ast_ctx(old).file, ast_ctx(old).line);
4326 if (opts.standard == COMPILER_QCC &&
4327 (old = parser_find_global(parser, var->name)))
4329 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4330 parseerror(parser, "field `%s` already declared here: %s:%i",
4331 var->name, ast_ctx(old).file, ast_ctx(old).line);
4338 /* deal with other globals */
4339 old = parser_find_global(parser, var->name);
4340 if (old && var->expression.vtype == TYPE_FUNCTION && old->expression.vtype == TYPE_FUNCTION)
4342 /* This is a function which had a prototype */
4343 if (!ast_istype(old, ast_value)) {
4344 parseerror(parser, "internal error: prototype is not an ast_value");
4348 proto = (ast_value*)old;
4349 if (!ast_compare_type((ast_expression*)proto, (ast_expression*)var)) {
4350 parseerror(parser, "conflicting types for `%s`, previous declaration was here: %s:%i",
4352 ast_ctx(proto).file, ast_ctx(proto).line);
4356 /* we need the new parameter-names */
4357 for (i = 0; i < vec_size(proto->expression.params); ++i)
4358 ast_value_set_name(proto->expression.params[i], var->expression.params[i]->name);
4366 if (opts.standard == COMPILER_GMQCC) {
4367 parseerror(parser, "global `%s` already declared here: %s:%i",
4368 var->name, ast_ctx(old).file, ast_ctx(old).line);
4372 if (parsewarning(parser, WARN_DOUBLE_DECLARATION,
4373 "global `%s` already declared here: %s:%i",
4374 var->name, ast_ctx(old).file, ast_ctx(old).line))
4379 proto = (ast_value*)old;
4380 if (!ast_istype(old, ast_value)) {
4381 parseerror(parser, "internal error: not an ast_value");
4390 if (opts.standard == COMPILER_QCC &&
4391 (old = parser_find_field(parser, var->name)))
4393 parseerror(parser, "cannot declare a field and a global of the same name with -std=qcc");
4394 parseerror(parser, "global `%s` already declared here: %s:%i",
4395 var->name, ast_ctx(old).file, ast_ctx(old).line);
4402 else /* it's not a global */
4404 old = parser_find_local(parser, var->name, vec_size(parser->variables)-1, &isparam);
4405 if (old && !isparam) {
4406 parseerror(parser, "local `%s` already declared here: %s:%i",
4407 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4411 old = parser_find_local(parser, var->name, 0, &isparam);
4412 if (old && isparam) {
4413 if (parsewarning(parser, WARN_LOCAL_SHADOWS,
4414 "local `%s` is shadowing a parameter", var->name))
4416 parseerror(parser, "local `%s` already declared here: %s:%i",
4417 var->name, ast_ctx(old).file, (int)ast_ctx(old).line);
4421 if (opts.standard != COMPILER_GMQCC) {
4430 * Create the global/local, and deal with vector types.
4433 if (var->expression.vtype == TYPE_VECTOR)
4435 else if (var->expression.vtype == TYPE_FIELD &&
4436 var->expression.next->expression.vtype == TYPE_VECTOR)
4440 if (!create_vector_members(var, me)) {
4447 /* deal with global variables, fields, functions */
4448 if (!nofields && var->expression.vtype == TYPE_FIELD && parser->tok != '=') {
4449 var->isfield = true;
4450 vec_push(parser->fields, (ast_expression*)var);
4451 util_htset(parser->htfields, var->name, var);
4453 for (i = 0; i < 3; ++i) {
4454 vec_push(parser->fields, (ast_expression*)me[i]);
4455 util_htset(parser->htfields, me[i]->name, me[i]);
4460 vec_push(parser->globals, (ast_expression*)var);
4461 util_htset(parser->htglobals, var->name, var);
4463 for (i = 0; i < 3; ++i) {
4464 vec_push(parser->globals, (ast_expression*)me[i]);
4465 util_htset(parser->htglobals, me[i]->name, me[i]);
4471 /* a static adds itself to be generated like any other global
4472 * but is added to the local namespace instead
4474 char *defname = NULL;
4475 size_t prefix_len, ln;
4477 ln = strlen(parser->function->name);
4478 vec_append(defname, ln, parser->function->name);
4480 vec_append(defname, 2, "::");
4481 /* remember the length up to here */
4482 prefix_len = vec_size(defname);
4484 /* Add it to the local scope */
4485 util_htset(vec_last(parser->variables), var->name, (void*)var);
4486 /* now rename the global */
4487 ln = strlen(var->name);
4488 vec_append(defname, ln, var->name);
4489 ast_value_set_name(var, defname);
4491 /* push it to the to-be-generated globals */
4492 vec_push(parser->globals, (ast_expression*)var);
4494 /* same game for the vector members */
4496 for (i = 0; i < 3; ++i) {
4497 util_htset(vec_last(parser->variables), me[i]->name, (void*)(me[i]));
4499 vec_shrinkto(defname, prefix_len);
4500 ln = strlen(me[i]->name);
4501 vec_append(defname, ln, me[i]->name);
4502 ast_member_set_name(me[i], defname);
4504 vec_push(parser->globals, (ast_expression*)me[i]);
4509 vec_push(localblock->locals, var);
4510 parser_addlocal(parser, var->name, (ast_expression*)var);
4512 for (i = 0; i < 3; ++i) {
4513 parser_addlocal(parser, me[i]->name, (ast_expression*)me[i]);
4514 ast_block_collect(localblock, (ast_expression*)me[i]);
4520 me[0] = me[1] = me[2] = NULL;
4525 if (var->expression.vtype == TYPE_ARRAY) {
4527 snprintf(name, sizeof(name), "%s##SET", var->name);
4528 if (!parser_create_array_setter(parser, var, name))
4530 snprintf(name, sizeof(name), "%s##GET", var->name);
4531 if (!parser_create_array_getter(parser, var, var->expression.next, name))
4534 else if (!localblock && !nofields &&
4535 var->expression.vtype == TYPE_FIELD &&
4536 var->expression.next->expression.vtype == TYPE_ARRAY)
4539 ast_expression *telem;
4541 ast_value *array = (ast_value*)var->expression.next;
4543 if (!ast_istype(var->expression.next, ast_value)) {
4544 parseerror(parser, "internal error: field element type must be an ast_value");
4548 snprintf(name, sizeof(name), "%s##SETF", var->name);
4549 if (!parser_create_array_field_setter(parser, array, name))
4552 telem = ast_type_copy(ast_ctx(var), array->expression.next);
4553 tfield = ast_value_new(ast_ctx(var), "<.type>", TYPE_FIELD);
4554 tfield->expression.next = telem;
4555 snprintf(name, sizeof(name), "%s##GETFP", var->name);
4556 if (!parser_create_array_getter(parser, array, (ast_expression*)tfield, name)) {
4564 if (parser->tok == ';') {
4565 ast_delete(basetype);
4566 if (!parser_next(parser)) {
4567 parseerror(parser, "error after variable declaration");
4573 if (parser->tok == ',')
4577 if (!var || (!localblock && !nofields && basetype->expression.vtype == TYPE_FIELD)) {
4580 parseerror(parser, "missing comma or semicolon while parsing variables");
4584 if (localblock && opts.standard == COMPILER_QCC) {
4585 if (parsewarning(parser, WARN_LOCAL_CONSTANTS,
4586 "initializing expression turns variable `%s` into a constant in this standard",
4593 if (parser->tok != '{') {
4594 if (parser->tok != '=') {
4595 parseerror(parser, "missing semicolon or initializer, got: `%s`", parser_tokval(parser));
4599 if (!parser_next(parser)) {
4600 parseerror(parser, "error parsing initializer");
4604 else if (opts.standard == COMPILER_QCC) {
4605 parseerror(parser, "expected '=' before function body in this standard");
4608 if (parser->tok == '#') {
4609 ast_function *func = NULL;
4612 parseerror(parser, "cannot declare builtins within functions");
4615 if (var->expression.vtype != TYPE_FUNCTION) {
4616 parseerror(parser, "unexpected builtin number, '%s' is not a function", var->name);
4619 if (!parser_next(parser)) {
4620 parseerror(parser, "expected builtin number");
4623 if (parser->tok != TOKEN_INTCONST) {
4624 parseerror(parser, "builtin number must be an integer constant");
4627 if (parser_token(parser)->constval.i < 0) {
4628 parseerror(parser, "builtin number must be an integer greater than zero");
4632 if (var->hasvalue) {
4633 (void)!parsewarning(parser, WARN_DOUBLE_DECLARATION,
4634 "builtin `%s` has already been defined\n"
4635 " -> previous declaration here: %s:%i",
4636 var->name, ast_ctx(var).file, (int)ast_ctx(var).line);
4640 func = ast_function_new(ast_ctx(var), var->name, var);
4642 parseerror(parser, "failed to allocate function for `%s`", var->name);
4645 vec_push(parser->functions, func);
4647 func->builtin = -parser_token(parser)->constval.i-1;
4650 if (!parser_next(parser)) {
4651 parseerror(parser, "expected comma or semicolon");
4653 ast_function_delete(func);
4654 var->constval.vfunc = NULL;
4658 else if (parser->tok == '{' || parser->tok == '[')
4661 parseerror(parser, "cannot declare functions within functions");
4666 ast_ctx(proto) = parser_ctx(parser);
4668 if (!parse_function_body(parser, var))
4670 ast_delete(basetype);
4671 for (i = 0; i < vec_size(parser->gotos); ++i)
4672 parseerror(parser, "undefined label: `%s`", parser->gotos[i]->name);
4673 vec_free(parser->gotos);
4674 vec_free(parser->labels);
4677 ast_expression *cexp;
4680 cexp = parse_expression_leave(parser, true);
4685 cval = (ast_value*)cexp;
4686 if (!ast_istype(cval, ast_value) || ((!cval->hasvalue || cval->cvq != CV_CONST) && !cval->isfield))
4687 parseerror(parser, "cannot initialize a global constant variable with a non-constant expression");
4690 if (opts.standard != COMPILER_GMQCC &&
4691 !OPTS_FLAG(INITIALIZED_NONCONSTANTS) &&
4692 qualifier != CV_VAR)
4694 var->cvq = CV_CONST;
4696 var->hasvalue = true;
4697 if (cval->expression.vtype == TYPE_STRING)
4698 var->constval.vstring = parser_strdup(cval->constval.vstring);
4699 else if (cval->expression.vtype == TYPE_FIELD)
4700 var->constval.vfield = cval;
4702 memcpy(&var->constval, &cval->constval, sizeof(var->constval));
4707 shunt sy = { NULL, NULL };
4710 vec_push(sy.out, syexp(ast_ctx(var), (ast_expression*)var));
4711 vec_push(sy.out, syexp(ast_ctx(cexp), (ast_expression*)cexp));
4712 vec_push(sy.ops, syop(ast_ctx(var), parser->assign_op));
4713 if (!parser_sy_apply_operator(parser, &sy))
4716 if (vec_size(sy.out) != 1 && vec_size(sy.ops) != 0)
4717 parseerror(parser, "internal error: leaked operands");
4718 if (!ast_block_add_expr(localblock, (ast_expression*)sy.out[0].out))
4728 if (parser->tok == ',') {
4729 if (!parser_next(parser)) {
4730 parseerror(parser, "expected another variable");
4734 if (parser->tok != TOKEN_IDENT) {
4735 parseerror(parser, "expected another variable");
4738 var = ast_value_copy(basetype);
4740 ast_value_set_name(var, parser_tokval(parser));
4741 if (!parser_next(parser)) {
4742 parseerror(parser, "error parsing variable declaration");
4748 if (parser->tok != ';') {
4749 parseerror(parser, "missing semicolon after variables");
4753 if (!parser_next(parser)) {
4754 parseerror(parser, "parse error after variable declaration");
4758 ast_delete(basetype);
4762 if (cleanvar && var)
4764 ast_delete(basetype);
4768 ast_delete(basetype);
4769 if (cleanvar && var)
4771 if (me[0]) ast_member_delete(me[0]);
4772 if (me[1]) ast_member_delete(me[1]);
4773 if (me[2]) ast_member_delete(me[2]);
4777 static bool parser_global_statement(parser_t *parser)
4781 bool noreturn = false;
4782 bool is_static = false;
4783 ast_value *istype = NULL;
4785 if (parser->tok == TOKEN_IDENT)
4786 istype = parser_find_typedef(parser, parser_tokval(parser), 0);
4788 if (istype || parser->tok == TOKEN_TYPENAME || parser->tok == '.')
4790 return parse_variable(parser, NULL, false, CV_NONE, istype, false, false, false);
4792 else if (parse_var_qualifiers(parser, false, &cvq, &noref, &noreturn, &is_static))
4794 if (cvq == CV_WRONG)
4796 return parse_variable(parser, NULL, true, cvq, NULL, noref, noreturn, is_static);
4798 else if (parser->tok == TOKEN_KEYWORD)
4800 if (!strcmp(parser_tokval(parser), "typedef")) {
4801 if (!parser_next(parser)) {
4802 parseerror(parser, "expected type definition after 'typedef'");
4805 return parse_typedef(parser);
4807 parseerror(parser, "unrecognized keyword `%s`", parser_tokval(parser));
4810 else if (parser->tok == '#')
4812 return parse_pragma(parser);
4814 else if (parser->tok == '$')
4816 if (!parser_next(parser)) {
4817 parseerror(parser, "parse error");
4823 parseerror(parser, "unexpected token: %s", parser->lex->tok.value);
4829 static uint16_t progdefs_crc_sum(uint16_t old, const char *str)
4831 return util_crc16(old, str, strlen(str));
4834 static void progdefs_crc_file(const char *str)
4836 /* write to progdefs.h here */
4840 static uint16_t progdefs_crc_both(uint16_t old, const char *str)
4842 old = progdefs_crc_sum(old, str);
4843 progdefs_crc_file(str);
4847 static void generate_checksum(parser_t *parser)
4849 uint16_t crc = 0xFFFF;
4853 crc = progdefs_crc_both(crc, "\n/* file generated by qcc, do not modify */\n\ntypedef struct\n{");
4854 crc = progdefs_crc_sum(crc, "\tint\tpad[28];\n");
4856 progdefs_crc_file("\tint\tpad;\n");
4857 progdefs_crc_file("\tint\tofs_return[3];\n");
4858 progdefs_crc_file("\tint\tofs_parm0[3];\n");
4859 progdefs_crc_file("\tint\tofs_parm1[3];\n");
4860 progdefs_crc_file("\tint\tofs_parm2[3];\n");
4861 progdefs_crc_file("\tint\tofs_parm3[3];\n");
4862 progdefs_crc_file("\tint\tofs_parm4[3];\n");
4863 progdefs_crc_file("\tint\tofs_parm5[3];\n");
4864 progdefs_crc_file("\tint\tofs_parm6[3];\n");
4865 progdefs_crc_file("\tint\tofs_parm7[3];\n");
4867 for (i = 0; i < parser->crc_globals; ++i) {
4868 if (!ast_istype(parser->globals[i], ast_value))
4870 value = (ast_value*)(parser->globals[i]);
4871 switch (value->expression.vtype) {
4872 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4873 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4874 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4875 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4877 crc = progdefs_crc_both(crc, "\tint\t");
4880 crc = progdefs_crc_both(crc, value->name);
4881 crc = progdefs_crc_both(crc, ";\n");
4883 crc = progdefs_crc_both(crc, "} globalvars_t;\n\ntypedef struct\n{\n");
4884 for (i = 0; i < parser->crc_fields; ++i) {
4885 if (!ast_istype(parser->fields[i], ast_value))
4887 value = (ast_value*)(parser->fields[i]);
4888 switch (value->expression.next->expression.vtype) {
4889 case TYPE_FLOAT: crc = progdefs_crc_both(crc, "\tfloat\t"); break;
4890 case TYPE_VECTOR: crc = progdefs_crc_both(crc, "\tvec3_t\t"); break;
4891 case TYPE_STRING: crc = progdefs_crc_both(crc, "\tstring_t\t"); break;
4892 case TYPE_FUNCTION: crc = progdefs_crc_both(crc, "\tfunc_t\t"); break;
4894 crc = progdefs_crc_both(crc, "\tint\t");
4897 crc = progdefs_crc_both(crc, value->name);
4898 crc = progdefs_crc_both(crc, ";\n");
4900 crc = progdefs_crc_both(crc, "} entvars_t;\n\n");
4905 static parser_t *parser;
4911 parser = (parser_t*)mem_a(sizeof(parser_t));
4915 memset(parser, 0, sizeof(*parser));
4917 for (i = 0; i < operator_count; ++i) {
4918 if (operators[i].id == opid1('=')) {
4919 parser->assign_op = operators+i;
4923 if (!parser->assign_op) {
4924 printf("internal error: initializing parser: failed to find assign operator\n");
4929 vec_push(parser->variables, parser->htfields = util_htnew(PARSER_HT_SIZE));
4930 vec_push(parser->variables, parser->htglobals = util_htnew(PARSER_HT_SIZE));
4931 vec_push(parser->typedefs, util_htnew(TYPEDEF_HT_SIZE));
4932 vec_push(parser->_blocktypedefs, 0);
4936 bool parser_compile()
4938 /* initial lexer/parser state */
4939 parser->lex->flags.noops = true;
4941 if (parser_next(parser))
4943 while (parser->tok != TOKEN_EOF && parser->tok < TOKEN_ERROR)
4945 if (!parser_global_statement(parser)) {
4946 if (parser->tok == TOKEN_EOF)
4947 parseerror(parser, "unexpected eof");
4948 else if (compile_errors)
4949 parseerror(parser, "there have been errors, bailing out");
4950 lex_close(parser->lex);
4956 parseerror(parser, "parse error");
4957 lex_close(parser->lex);
4962 lex_close(parser->lex);
4965 return !compile_errors;
4968 bool parser_compile_file(const char *filename)
4970 parser->lex = lex_open(filename);
4972 con_err("failed to open file \"%s\"\n", filename);
4975 return parser_compile();
4978 bool parser_compile_string(const char *name, const char *str, size_t len)
4980 parser->lex = lex_open_string(str, len, name);
4982 con_err("failed to create lexer for string \"%s\"\n", name);
4985 return parser_compile();
4988 void parser_cleanup()
4991 for (i = 0; i < vec_size(parser->accessors); ++i) {
4992 ast_delete(parser->accessors[i]->constval.vfunc);
4993 parser->accessors[i]->constval.vfunc = NULL;
4994 ast_delete(parser->accessors[i]);
4996 for (i = 0; i < vec_size(parser->functions); ++i) {
4997 ast_delete(parser->functions[i]);
4999 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5000 ast_delete(parser->imm_vector[i]);
5002 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5003 ast_delete(parser->imm_string[i]);
5005 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5006 ast_delete(parser->imm_float[i]);
5008 for (i = 0; i < vec_size(parser->fields); ++i) {
5009 ast_delete(parser->fields[i]);
5011 for (i = 0; i < vec_size(parser->globals); ++i) {
5012 ast_delete(parser->globals[i]);
5014 vec_free(parser->accessors);
5015 vec_free(parser->functions);
5016 vec_free(parser->imm_vector);
5017 vec_free(parser->imm_string);
5018 vec_free(parser->imm_float);
5019 vec_free(parser->globals);
5020 vec_free(parser->fields);
5022 for (i = 0; i < vec_size(parser->variables); ++i)
5023 util_htdel(parser->variables[i]);
5024 vec_free(parser->variables);
5025 vec_free(parser->_blocklocals);
5026 vec_free(parser->_locals);
5028 for (i = 0; i < vec_size(parser->_typedefs); ++i)
5029 ast_delete(parser->_typedefs[i]);
5030 vec_free(parser->_typedefs);
5031 for (i = 0; i < vec_size(parser->typedefs); ++i)
5032 util_htdel(parser->typedefs[i]);
5033 vec_free(parser->typedefs);
5034 vec_free(parser->_blocktypedefs);
5036 vec_free(parser->_block_ctx);
5038 vec_free(parser->labels);
5039 vec_free(parser->gotos);
5040 vec_free(parser->breaks);
5041 vec_free(parser->continues);
5046 bool parser_finish(const char *output)
5052 if (compile_errors) {
5053 con_out("*** there were compile errors\n");
5057 ir = ir_builder_new("gmqcc_out");
5059 con_out("failed to allocate builder\n");
5063 for (i = 0; i < vec_size(parser->fields); ++i) {
5066 if (!ast_istype(parser->fields[i], ast_value))
5068 field = (ast_value*)parser->fields[i];
5069 hasvalue = field->hasvalue;
5070 field->hasvalue = false;
5071 if (!ast_global_codegen((ast_value*)field, ir, true)) {
5072 con_out("failed to generate field %s\n", field->name);
5073 ir_builder_delete(ir);
5078 ast_expression *subtype;
5079 field->hasvalue = true;
5080 subtype = field->expression.next;
5081 ifld = ir_builder_create_field(ir, field->name, subtype->expression.vtype);
5082 if (subtype->expression.vtype == TYPE_FIELD)
5083 ifld->fieldtype = subtype->expression.next->expression.vtype;
5084 else if (subtype->expression.vtype == TYPE_FUNCTION)
5085 ifld->outtype = subtype->expression.next->expression.vtype;
5086 (void)!ir_value_set_field(field->ir_v, ifld);
5089 for (i = 0; i < vec_size(parser->globals); ++i) {
5091 if (!ast_istype(parser->globals[i], ast_value))
5093 asvalue = (ast_value*)(parser->globals[i]);
5094 if (!asvalue->uses && !asvalue->hasvalue && asvalue->expression.vtype != TYPE_FUNCTION) {
5095 retval = retval && !genwarning(ast_ctx(asvalue), WARN_UNUSED_VARIABLE,
5096 "unused global: `%s`", asvalue->name);
5098 if (!ast_global_codegen(asvalue, ir, false)) {
5099 con_out("failed to generate global %s\n", asvalue->name);
5100 ir_builder_delete(ir);
5104 for (i = 0; i < vec_size(parser->imm_float); ++i) {
5105 if (!ast_global_codegen(parser->imm_float[i], ir, false)) {
5106 con_out("failed to generate global %s\n", parser->imm_float[i]->name);
5107 ir_builder_delete(ir);
5111 for (i = 0; i < vec_size(parser->imm_string); ++i) {
5112 if (!ast_global_codegen(parser->imm_string[i], ir, false)) {
5113 con_out("failed to generate global %s\n", parser->imm_string[i]->name);
5114 ir_builder_delete(ir);
5118 for (i = 0; i < vec_size(parser->imm_vector); ++i) {
5119 if (!ast_global_codegen(parser->imm_vector[i], ir, false)) {
5120 con_out("failed to generate global %s\n", parser->imm_vector[i]->name);
5121 ir_builder_delete(ir);
5125 for (i = 0; i < vec_size(parser->globals); ++i) {
5127 if (!ast_istype(parser->globals[i], ast_value))
5129 asvalue = (ast_value*)(parser->globals[i]);
5130 if (!ast_generate_accessors(asvalue, ir)) {
5131 ir_builder_delete(ir);
5135 for (i = 0; i < vec_size(parser->fields); ++i) {
5137 asvalue = (ast_value*)(parser->fields[i]->expression.next);
5139 if (!ast_istype((ast_expression*)asvalue, ast_value))
5141 if (asvalue->expression.vtype != TYPE_ARRAY)
5143 if (!ast_generate_accessors(asvalue, ir)) {
5144 ir_builder_delete(ir);
5148 for (i = 0; i < vec_size(parser->functions); ++i) {
5149 if (!ast_function_codegen(parser->functions[i], ir)) {
5150 con_out("failed to generate function %s\n", parser->functions[i]->name);
5151 ir_builder_delete(ir);
5156 ir_builder_dump(ir, con_out);
5157 for (i = 0; i < vec_size(parser->functions); ++i) {
5158 if (!ir_function_finalize(parser->functions[i]->ir_func)) {
5159 con_out("failed to finalize function %s\n", parser->functions[i]->name);
5160 ir_builder_delete(ir);
5165 if (compile_Werrors) {
5166 con_out("*** there were warnings treated as errors\n");
5167 compile_show_werrors();
5173 ir_builder_dump(ir, con_out);
5175 generate_checksum(parser);
5177 if (!ir_builder_generate(ir, output)) {
5178 con_out("*** failed to generate output file\n");
5179 ir_builder_delete(ir);
5184 ir_builder_delete(ir);