]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.h
temp committing major c++ification
[xonotic/gmqcc.git] / ast.h
1 #ifndef GMQCC_AST_HDR
2 #define GMQCC_AST_HDR
3 #include <vector>
4 #include "ir.h"
5
6 typedef uint16_t ast_flag_t;
7
8 /* Note: I will not be using a _t suffix for the
9  * "main" ast node types for now.
10  */
11
12 struct ast_node;
13 struct ast_expression;
14 struct ast_value;
15 struct ast_function;
16 struct ast_block;
17 struct ast_binary;
18 struct ast_store;
19 struct ast_binstore;
20 struct ast_entfield;
21 struct ast_ifthen;
22 struct ast_ternary;
23 struct ast_loop;
24 struct ast_call;
25 struct ast_unary;
26 struct ast_return;
27 struct ast_member;
28 struct ast_array_index;
29 struct ast_breakcont;
30 struct ast_switch;
31 struct ast_label;
32 struct ast_goto;
33 struct ast_argpipe;
34 struct ast_state;
35
36 enum {
37     AST_FLAG_VARIADIC       = 1 << 0,
38     AST_FLAG_NORETURN       = 1 << 1,
39     AST_FLAG_INLINE         = 1 << 2,
40     AST_FLAG_INITIALIZED    = 1 << 3,
41     AST_FLAG_DEPRECATED     = 1 << 4,
42     AST_FLAG_INCLUDE_DEF    = 1 << 5,
43     AST_FLAG_IS_VARARG      = 1 << 6,
44     AST_FLAG_ALIAS          = 1 << 7,
45     AST_FLAG_ERASEABLE      = 1 << 8,
46     AST_FLAG_ACCUMULATE     = 1 << 9,
47
48     /* An array declared as []
49      * so that the size is taken from the initializer
50      */
51     AST_FLAG_ARRAY_INIT     = 1 << 10,
52
53     AST_FLAG_FINAL_DECL     = 1 << 11,
54
55     /* Several coverage options
56      * AST_FLAG_COVERAGE means there was an explicit [[coverage]] attribute,
57      * which will overwrite the default set via the commandline switches.
58      * BLOCK_COVERAGE inserts coverage() calls into every basic block.
59      * In the future there might be more options like tracking variable access
60      * by creating get/set wrapper functions.
61      */
62     AST_FLAG_COVERAGE       = 1 << 12,
63     AST_FLAG_BLOCK_COVERAGE = 1 << 13,
64
65     AST_FLAG_LAST,
66     AST_FLAG_TYPE_MASK      = (AST_FLAG_VARIADIC | AST_FLAG_NORETURN),
67     AST_FLAG_COVERAGE_MASK  = (AST_FLAG_BLOCK_COVERAGE)
68 };
69
70 enum {
71     TYPE_ast_node,        /*  0 */
72     TYPE_ast_expression,  /*  1 */
73     TYPE_ast_value,       /*  2 */
74     TYPE_ast_function,    /*  3 */
75     TYPE_ast_block,       /*  4 */
76     TYPE_ast_binary,      /*  5 */
77     TYPE_ast_store,       /*  6 */
78     TYPE_ast_binstore,    /*  7 */
79     TYPE_ast_entfield,    /*  8 */
80     TYPE_ast_ifthen,      /*  9 */
81     TYPE_ast_ternary,     /* 10 */
82     TYPE_ast_loop,        /* 11 */
83     TYPE_ast_call,        /* 12 */
84     TYPE_ast_unary,       /* 13 */
85     TYPE_ast_return,      /* 14 */
86     TYPE_ast_member,      /* 15 */
87     TYPE_ast_array_index, /* 16 */
88     TYPE_ast_breakcont,   /* 17 */
89     TYPE_ast_switch,      /* 18 */
90     TYPE_ast_label,       /* 19 */
91     TYPE_ast_goto,        /* 20 */
92     TYPE_ast_argpipe,     /* 21 */
93     TYPE_ast_state        /* 22 */
94 };
95
96 #define ast_istype(x, t) ( ((ast_node*)x)->node_type == (TYPE_##t) )
97 #define ast_ctx(node) (((ast_node*)(node))->context)
98 #define ast_side_effects(node) (((ast_node*)(node))->side_effects)
99
100 /* Node interface with common components
101  */
102 typedef void ast_node_delete(ast_node*);
103
104 struct ast_node
105 {
106     lex_ctx_t context;
107     /* I don't feel comfortable using keywords like 'delete' as names... */
108     ast_node_delete *destroy;
109     int              node_type;
110     /* keep_node: if a node contains this node, 'keep_node'
111      * prevents its dtor from destroying this node as well.
112      */
113     bool             keep_node;
114     bool             side_effects;
115 };
116
117 #define ast_delete(x) (*( ((ast_node*)(x))->destroy ))((ast_node*)(x))
118 #define ast_unref(x) do                     \
119 {                                           \
120     if (! (((ast_node*)(x))->keep_node) ) { \
121         ast_delete(x);                      \
122     }                                       \
123 } while(0)
124
125 /* Expression interface
126  *
127  * Any expression or block returns an ir_value, and needs
128  * to know the current function.
129  */
130 typedef bool ast_expression_codegen(ast_expression*,
131                                     ast_function*,
132                                     bool lvalue,
133                                     ir_value**);
134 /* TODO: the codegen function should take an output-type parameter
135  * indicating whether a variable, type, label etc. is expected, and
136  * an environment!
137  * Then later an ast_ident could have a codegen using this to figure
138  * out what to look for.
139  * eg. in code which uses a not-yet defined variable, the expression
140  * would take an ast_ident, and the codegen would be called with
141  * type `expression`, so the ast_ident's codegen would search for
142  * variables through the environment (or functions, constants...).
143  */
144 struct ast_expression : ast_node {
145     ast_expression() {}
146
147     ast_expression_codegen *codegen;
148     qc_type                 vtype;
149     ast_expression         *next;
150     /* arrays get a member-count */
151     size_t                  count;
152     std::vector<ast_value*> type_params;
153
154     ast_flag_t              flags;
155     /* void foo(string...) gets varparam set as a restriction
156      * for variadic parameters
157      */
158     ast_expression         *varparam;
159     /* The codegen functions should store their output values
160      * so we can call it multiple times without re-evaluating.
161      * Store lvalue and rvalue seperately though. So that
162      * ast_entfield for example can generate both if required.
163      */
164     ir_value               *outl;
165     ir_value               *outr;
166 };
167
168 /* Value
169  *
170  * Types are also values, both have a type and a name.
171  * especially considering possible constructs like typedefs.
172  * typedef float foo;
173  * is like creating a 'float foo', foo serving as the type's name.
174  */
175 union basic_value_t {
176     qcfloat_t     vfloat;
177     int           vint;
178     vec3_t        vvec;
179     const char   *vstring;
180     int           ventity;
181     ast_function *vfunc;
182     ast_value    *vfield;
183 };
184
185 struct ast_value : ast_expression
186 {
187     const char *name;
188     const char *desc;
189
190     const char *argcounter;
191
192     int cvq;     /* const/var qualifier */
193     bool isfield; /* this declares a field */
194     bool isimm;   /* an immediate, not just const */
195     bool hasvalue;
196     bool inexact; /* inexact coming from folded expression */
197     basic_value_t constval;
198     /* for TYPE_ARRAY we have an optional vector
199      * of constants when an initializer list
200      * was provided.
201      */
202     std::vector<basic_value_t> initlist;
203
204     /* usecount for the parser */
205     size_t uses;
206
207     ir_value *ir_v;
208     ir_value **ir_values;
209     size_t ir_value_count;
210
211     /* ONLY for arrays in progs version up to 6 */
212     ast_value *setter;
213     ast_value *getter;
214
215
216     bool intrinsic; /* true if associated with intrinsic */
217 };
218
219 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, qc_type qctype);
220 ast_value* ast_value_copy(const ast_value *self);
221 /* This will NOT delete an underlying ast_function */
222 void ast_value_delete(ast_value*);
223
224 bool ast_value_set_name(ast_value*, const char *name);
225
226 /*
227 bool ast_value_codegen(ast_value*, ast_function*, bool lvalue, ir_value**);
228 bool ast_local_codegen(ast_value *self, ir_function *func, bool isparam);
229 */
230
231 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield);
232
233 void ast_value_params_add(ast_value*, ast_value*);
234
235 bool ast_compare_type(ast_expression *a, ast_expression *b);
236 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex);
237 #define ast_type_adopt(a, b) ast_type_adopt_impl((ast_expression*)(a), (ast_expression*)(b))
238 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other);
239 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize);
240
241 enum ast_binary_ref {
242     AST_REF_NONE  = 0,
243     AST_REF_LEFT  = 1 << 1,
244     AST_REF_RIGHT = 1 << 2,
245     AST_REF_ALL   = (AST_REF_LEFT | AST_REF_RIGHT)
246 };
247
248
249 /* Binary
250  *
251  * A value-returning binary expression.
252  */
253 struct ast_binary : ast_expression
254 {
255     int op;
256     ast_expression *left;
257     ast_expression *right;
258     ast_binary_ref refs;
259     bool right_first;
260 };
261 ast_binary* ast_binary_new(lex_ctx_t    ctx,
262                            int        op,
263                            ast_expression *left,
264                            ast_expression *right);
265
266 /* Binstore
267  *
268  * An assignment including a binary expression with the source as left operand.
269  * Eg. a += b; is a binstore { INSTR_STORE, INSTR_ADD, a, b }
270  */
271 struct ast_binstore : ast_expression
272 {
273     int opstore;
274     int opbin;
275     ast_expression *dest;
276     ast_expression *source;
277     /* for &~= which uses the destination in a binary in source we can use this */
278     bool keep_dest;
279 };
280 ast_binstore* ast_binstore_new(lex_ctx_t    ctx,
281                                int        storeop,
282                                int        op,
283                                ast_expression *left,
284                                ast_expression *right);
285
286 /* Unary
287  *
288  * Regular unary expressions: not,neg
289  */
290 struct ast_unary : ast_expression
291 {
292     int op;
293     ast_expression *operand;
294 };
295 ast_unary* ast_unary_new(lex_ctx_t ctx,
296                          int op,
297                          ast_expression *expr);
298
299 /* Return
300  *
301  * Make sure 'return' only happens at the end of a block, otherwise the IR
302  * will refuse to create further instructions.
303  * This should be honored by the parser.
304  */
305 struct ast_return : ast_expression
306 {
307     ast_expression *operand;
308 };
309 ast_return* ast_return_new(lex_ctx_t ctx,
310                            ast_expression *expr);
311
312 /* Entity-field
313  *
314  * This must do 2 things:
315  * -) Provide a way to fetch an entity field value. (Rvalue)
316  * -) Provide a pointer to an entity field. (Lvalue)
317  * The problem:
318  * In original QC, there's only a STORE via pointer, but
319  * no LOAD via pointer.
320  * So we must know beforehand if we are going to read or assign
321  * the field.
322  * For this we will have to extend the codegen() functions with
323  * a flag saying whether or not we need an L or an R-value.
324  */
325 struct ast_entfield : ast_expression
326 {
327     /* The entity can come from an expression of course. */
328     ast_expression *entity;
329     /* As can the field, it just must result in a value of TYPE_FIELD */
330     ast_expression *field;
331 };
332 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field);
333 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype);
334
335 /* Member access:
336  *
337  * For now used for vectors. If we get structs or unions
338  * we can have them handled here as well.
339  */
340 struct ast_member : ast_expression
341 {
342     ast_expression *owner;
343     unsigned int field;
344     const char *name;
345     bool rvalue;
346 };
347 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name);
348 void ast_member_delete(ast_member*);
349 bool ast_member_set_name(ast_member*, const char *name);
350
351
352 /* Array index access:
353  *
354  * QC forces us to take special action on arrays:
355  * an ast_store on an ast_array_index must not codegen the index,
356  * but call its setter - unless we have an instruction set which supports
357  * what we need.
358  * Any other array index access will be codegened to a call to the getter.
359  * In any case, accessing an element via a compiletime-constant index will
360  * result in quick access to that variable.
361  */
362 struct ast_array_index : ast_expression
363 {
364     ast_expression *array;
365     ast_expression *index;
366 };
367 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index);
368
369 /* Vararg pipe node:
370  *
371  * copy all varargs starting from a specific index
372  */
373 struct ast_argpipe : ast_expression
374 {
375     ast_expression *index;
376 };
377 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index);
378
379 /* Store
380  *
381  * Stores left<-right and returns left.
382  * Specialized binary expression node
383  */
384 struct ast_store : ast_expression
385 {
386     int op;
387     ast_expression *dest;
388     ast_expression *source;
389 };
390 ast_store* ast_store_new(lex_ctx_t ctx, int op,
391                          ast_expression *d, ast_expression *s);
392
393 /* If
394  *
395  * A general 'if then else' statement, either side can be nullptr and will
396  * thus be omitted. It is an error for *both* cases to be nullptr at once.
397  *
398  * During its 'codegen' it'll be changing the ast_function's block.
399  *
400  * An if is also an "expression". Its codegen will put nullptr into the
401  * output field though. For ternary expressions an ast_ternary will be
402  * added.
403  */
404 struct ast_ifthen : ast_expression
405 {
406     ast_expression *cond;
407     /* It's all just 'expressions', since an ast_block is one too. */
408     ast_expression *on_true;
409     ast_expression *on_false;
410 };
411 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse);
412
413 /* Ternary expressions...
414  *
415  * Contrary to 'if-then-else' nodes, ternary expressions actually
416  * return a value, otherwise they behave the very same way.
417  * The difference in 'codegen' is that it'll return the value of
418  * a PHI node.
419  *
420  * The other difference is that in an ast_ternary, NEITHER side
421  * must be nullptr, there's ALWAYS an else branch.
422  *
423  * This is the only ast_node beside ast_value which contains
424  * an ir_value. Theoretically we don't need to remember it though.
425  */
426 struct ast_ternary : ast_expression
427 {
428     ast_expression *cond;
429     /* It's all just 'expressions', since an ast_block is one too. */
430     ast_expression *on_true;
431     ast_expression *on_false;
432 };
433 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse);
434
435 /* A general loop node
436  *
437  * For convenience it contains 4 parts:
438  * -) (ini) = initializing expression
439  * -) (pre) = pre-loop condition
440  * -) (pst) = post-loop condition
441  * -) (inc) = "increment" expression
442  * The following is a psudo-representation of this loop
443  * note that '=>' bears the logical meaning of "implies".
444  * (a => b) equals (!a || b)
445
446 {ini};
447 while (has_pre => {pre})
448 {
449     {body};
450
451 continue:      // a 'continue' will jump here
452     if (has_pst => {pst})
453         break;
454
455     {inc};
456 }
457  */
458 struct ast_loop : ast_expression
459 {
460     ast_expression *initexpr;
461     ast_expression *precond;
462     ast_expression *postcond;
463     ast_expression *increment;
464     ast_expression *body;
465     /* For now we allow a seperate flag on whether or not the condition
466      * is supposed to be true or false.
467      * That way, the parser can generate a 'while not(!x)' for `while(x)`
468      * if desired, which is useful for the new -f{true,false}-empty-strings
469      * flag.
470      */
471     bool pre_not;
472     bool post_not;
473 };
474 ast_loop* ast_loop_new(lex_ctx_t ctx,
475                        ast_expression *initexpr,
476                        ast_expression *precond, bool pre_not,
477                        ast_expression *postcond, bool post_not,
478                        ast_expression *increment,
479                        ast_expression *body);
480
481 /* Break/Continue
482  */
483 struct ast_breakcont : ast_expression
484 {
485     bool         is_continue;
486     unsigned int levels;
487 };
488 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels);
489
490 /* Switch Statements
491  *
492  * A few notes about this: with the original QCVM, no real optimization
493  * is possible. The SWITCH instruction set isn't really helping a lot, since
494  * it only collapes the EQ and IF instructions into one.
495  * Note: Declaring local variables inside caseblocks is normal.
496  * Since we don't have to deal with a stack there's no unnatural behaviour to
497  * be expected from it.
498  * TODO: Ticket #20
499  */
500 struct ast_switch_case {
501     ast_expression *value; /* #20 will replace this */
502     ast_expression *code;
503 };
504
505 struct ast_switch : ast_expression
506 {
507     ast_expression *operand;
508     std::vector<ast_switch_case> cases;
509 };
510
511 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op);
512
513 /* Label nodes
514  *
515  * Introduce a label which can be used together with 'goto'
516  */
517 struct ast_label : ast_expression
518 {
519     const char *name;
520     ir_block *irblock;
521     std::vector<ast_goto*> gotos;
522
523     /* means it has not yet been defined */
524     bool undefined;
525 };
526
527 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined);
528
529 /* GOTO nodes
530  *
531  * Go to a label, the label node is filled in at a later point!
532  */
533 struct ast_goto : ast_expression
534 {
535     const char *name;
536     ast_label *target;
537     ir_block *irblock_from;
538 };
539
540 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name);
541 void ast_goto_set_label(ast_goto*, ast_label*);
542
543 /* STATE node
544  *
545  * For frame/think state updates: void foo() [framenum, nextthink] {}
546  */
547 struct ast_state : ast_expression
548 {
549     ast_expression *framenum;
550     ast_expression *nextthink;
551 };
552 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think);
553 void ast_state_delete(ast_state*);
554
555 /* CALL node
556  *
557  * Contains an ast_expression as target, rather than an ast_function/value.
558  * Since it's how QC works, every ast_function has an ast_value
559  * associated anyway - in other words, the VM contains function
560  * pointers for every function anyway. Thus, this node will call
561  * expression.
562  * Additionally it contains a list of ast_expressions as parameters.
563  * Since calls can return values, an ast_call is also an ast_expression.
564  */
565 struct ast_call : ast_expression
566 {
567     ast_expression *func;
568     std::vector<ast_expression *> params;
569     ast_expression *va_count;
570 };
571 ast_call* ast_call_new(lex_ctx_t ctx,
572                        ast_expression *funcexpr);
573 bool ast_call_check_types(ast_call*, ast_expression *this_func_va_type);
574
575 /* Blocks
576  *
577  */
578 struct ast_block : ast_expression
579 {
580     std::vector<ast_value*>      locals;
581     std::vector<ast_expression*> exprs;
582     std::vector<ast_expression*> collect;
583 };
584 ast_block* ast_block_new(lex_ctx_t ctx);
585 void ast_block_delete(ast_block*);
586 void ast_block_set_type(ast_block*, ast_expression *from);
587 void ast_block_collect(ast_block*, ast_expression*);
588
589 bool GMQCC_WARN ast_block_add_expr(ast_block*, ast_expression*);
590
591 /* Function
592  *
593  * Contains a list of blocks... at least in theory.
594  * Usually there's just the main block, other blocks are inside that.
595  *
596  * Technically, functions don't need to be an AST node, since we have
597  * neither functions inside functions, nor lambdas, and function
598  * pointers could just work with a name. However, this way could be
599  * more flexible, and adds no real complexity.
600  */
601 struct ast_function
602 {
603     ast_node node;
604
605     ast_value  *function_type;
606     const char *name;
607
608     int builtin;
609
610     /* list of used-up names for statics without the count suffix */
611     std::vector<char*> static_names;
612     /* number of static variables, by convention this includes the
613      * ones without the count-suffix - remember this when dealing
614      * with savegames. uint instead of size_t as %zu in printf is
615      * C99, so no windows support. */
616     unsigned int static_count;
617
618     ir_function *ir_func;
619     ir_block *curblock;
620     std::vector<ir_block*> breakblocks;
621     std::vector<ir_block*> continueblocks;
622
623     size_t labelcount;
624     /* in order for thread safety - for the optional
625      * channel abesed multithreading... keeping a buffer
626      * here to use in ast_function_label.
627      */
628     char labelbuf[64];
629     std::vector<ast_block*> blocks;
630     ast_value *varargs;
631     ast_value *argc;
632     ast_value *fixedparams;
633     ast_value *return_value;
634 };
635 ast_function* ast_function_new(lex_ctx_t ctx, const char *name, ast_value *vtype);
636 /* This will NOT delete the underlying ast_value */
637 void ast_function_delete(ast_function*);
638 /* For "optimized" builds this can just keep returning "foo"...
639  * or whatever...
640  */
641 const char* ast_function_label(ast_function*, const char *prefix);
642
643 bool ast_function_codegen(ast_function *self, ir_builder *builder);
644 bool ast_generate_accessors(ast_value *asvalue, ir_builder *ir);
645
646 /*
647  * If the condition creates a situation where this becomes -1 size it means there are
648  * more AST_FLAGs than the type ast_flag_t is capable of holding. So either eliminate
649  * the AST flag count or change the ast_flag_t typedef to a type large enough to accomodate
650  * all the flags.
651  */
652 typedef int static_assert_is_ast_flag_safe [((AST_FLAG_LAST) <= (ast_flag_t)(-1)) ? 1 : -1];
653 #endif