]> git.xonotic.org Git - xonotic/gmqcc.git/blob - ast.h
8a437ab218a4a86d2aff882962b72f685a3a0671
[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) ( (x)->m_node_type == (TYPE_##t) )
97
98 /* Node interface with common components
99  */
100 typedef void ast_node_delete(ast_node*);
101
102 struct ast_node
103 {
104     //ast_node() = delete;
105     //ast_node(lex_ctx_t, int nodetype);
106     //virtual ~ast_node();
107
108     lex_ctx_t m_context;
109     /* I don't feel comfortable using keywords like 'delete' as names... */
110     ast_node_delete *m_destroy;
111     int              m_node_type;
112     /* keep_node: if a node contains this node, 'keep_node'
113      * prevents its dtor from destroying this node as well.
114      */
115     bool             m_keep_node;
116     bool             m_side_effects;
117 };
118
119 #define ast_delete(x) ( (x)->m_destroy((x)) )
120 #define ast_unref(x) do        \
121 {                              \
122     if (! (x)->m_keep_node ) { \
123         ast_delete(x);         \
124     }                          \
125 } while(0)
126
127 /* Expression interface
128  *
129  * Any expression or block returns an ir_value, and needs
130  * to know the current function.
131  */
132 typedef bool ast_expression_codegen(ast_expression*,
133                                     ast_function*,
134                                     bool lvalue,
135                                     ir_value**);
136 /* TODO: the codegen function should take an output-type parameter
137  * indicating whether a variable, type, label etc. is expected, and
138  * an environment!
139  * Then later an ast_ident could have a codegen using this to figure
140  * out what to look for.
141  * eg. in code which uses a not-yet defined variable, the expression
142  * would take an ast_ident, and the codegen would be called with
143  * type `expression`, so the ast_ident's codegen would search for
144  * variables through the environment (or functions, constants...).
145  */
146 struct ast_expression : ast_node {
147     ast_expression() {}
148
149     ast_expression_codegen *m_codegen;
150     qc_type                 m_vtype;
151     ast_expression         *m_next;
152     /* arrays get a member-count */
153     size_t                  m_count;
154     std::vector<ast_value*> m_type_params;
155
156     ast_flag_t              m_flags;
157     /* void foo(string...) gets varparam set as a restriction
158      * for variadic parameters
159      */
160     ast_expression         *m_varparam;
161     /* The codegen functions should store their output values
162      * so we can call it multiple times without re-evaluating.
163      * Store lvalue and rvalue seperately though. So that
164      * ast_entfield for example can generate both if required.
165      */
166     ir_value               *m_outl;
167     ir_value               *m_outr;
168 };
169
170 /* Value
171  *
172  * Types are also values, both have a type and a name.
173  * especially considering possible constructs like typedefs.
174  * typedef float foo;
175  * is like creating a 'float foo', foo serving as the type's name.
176  */
177 union basic_value_t {
178     qcfloat_t     vfloat;
179     int           vint;
180     vec3_t        vvec;
181     const char   *vstring;
182     int           ventity;
183     ast_function *vfunc;
184     ast_value    *vfield;
185 };
186
187 struct ast_value : ast_expression
188 {
189     const char *m_name;
190     const char *m_desc;
191
192     const char *m_argcounter;
193
194     int m_cvq;     /* const/var qualifier */
195     bool m_isfield; /* this declares a field */
196     bool m_isimm;   /* an immediate, not just const */
197     bool m_hasvalue;
198     bool m_inexact; /* inexact coming from folded expression */
199     basic_value_t m_constval;
200     /* for TYPE_ARRAY we have an optional vector
201      * of constants when an initializer list
202      * was provided.
203      */
204     std::vector<basic_value_t> m_initlist;
205
206     /* usecount for the parser */
207     size_t m_uses;
208
209     ir_value *m_ir_v;
210     ir_value **m_ir_values;
211     size_t m_ir_value_count;
212
213     /* ONLY for arrays in progs version up to 6 */
214     ast_value *m_setter;
215     ast_value *m_getter;
216
217
218     bool m_intrinsic; /* true if associated with intrinsic */
219 };
220
221 ast_value* ast_value_new(lex_ctx_t ctx, const char *name, qc_type qctype);
222 ast_value* ast_value_copy(const ast_value *self);
223 /* This will NOT delete an underlying ast_function */
224 void ast_value_delete(ast_value*);
225
226 bool ast_value_set_name(ast_value*, const char *name);
227
228 /*
229 bool ast_value_codegen(ast_value*, ast_function*, bool lvalue, ir_value**);
230 bool ast_local_codegen(ast_value *self, ir_function *func, bool isparam);
231 */
232
233 bool ast_global_codegen(ast_value *self, ir_builder *ir, bool isfield);
234
235 void ast_value_params_add(ast_value*, ast_value*);
236
237 bool ast_compare_type(ast_expression *a, ast_expression *b);
238 ast_expression* ast_type_copy(lex_ctx_t ctx, const ast_expression *ex);
239 #define ast_type_adopt(a, b) ast_type_adopt_impl((ast_expression*)(a), (ast_expression*)(b))
240 void ast_type_adopt_impl(ast_expression *self, const ast_expression *other);
241 void ast_type_to_string(ast_expression *e, char *buf, size_t bufsize);
242
243 enum ast_binary_ref {
244     AST_REF_NONE  = 0,
245     AST_REF_LEFT  = 1 << 1,
246     AST_REF_RIGHT = 1 << 2,
247     AST_REF_ALL   = (AST_REF_LEFT | AST_REF_RIGHT)
248 };
249
250
251 /* Binary
252  *
253  * A value-returning binary expression.
254  */
255 struct ast_binary : ast_expression
256 {
257     int m_op;
258     ast_expression *m_left;
259     ast_expression *m_right;
260     ast_binary_ref m_refs;
261     bool m_right_first;
262 };
263 ast_binary* ast_binary_new(lex_ctx_t    ctx,
264                            int        op,
265                            ast_expression *left,
266                            ast_expression *right);
267
268 /* Binstore
269  *
270  * An assignment including a binary expression with the source as left operand.
271  * Eg. a += b; is a binstore { INSTR_STORE, INSTR_ADD, a, b }
272  */
273 struct ast_binstore : ast_expression
274 {
275     int m_opstore;
276     int m_opbin;
277     ast_expression *m_dest;
278     ast_expression *m_source;
279     /* for &~= which uses the destination in a binary in source we can use this */
280     bool m_keep_dest;
281 };
282 ast_binstore* ast_binstore_new(lex_ctx_t    ctx,
283                                int        storeop,
284                                int        op,
285                                ast_expression *left,
286                                ast_expression *right);
287
288 /* Unary
289  *
290  * Regular unary expressions: not,neg
291  */
292 struct ast_unary : ast_expression
293 {
294     int m_op;
295     ast_expression *m_operand;
296 };
297 ast_unary* ast_unary_new(lex_ctx_t ctx,
298                          int op,
299                          ast_expression *expr);
300
301 /* Return
302  *
303  * Make sure 'return' only happens at the end of a block, otherwise the IR
304  * will refuse to create further instructions.
305  * This should be honored by the parser.
306  */
307 struct ast_return : ast_expression
308 {
309     ast_expression *m_operand;
310 };
311 ast_return* ast_return_new(lex_ctx_t ctx,
312                            ast_expression *expr);
313
314 /* Entity-field
315  *
316  * This must do 2 things:
317  * -) Provide a way to fetch an entity field value. (Rvalue)
318  * -) Provide a pointer to an entity field. (Lvalue)
319  * The problem:
320  * In original QC, there's only a STORE via pointer, but
321  * no LOAD via pointer.
322  * So we must know beforehand if we are going to read or assign
323  * the field.
324  * For this we will have to extend the codegen() functions with
325  * a flag saying whether or not we need an L or an R-value.
326  */
327 struct ast_entfield : ast_expression
328 {
329     /* The entity can come from an expression of course. */
330     ast_expression *m_entity;
331     /* As can the field, it just must result in a value of TYPE_FIELD */
332     ast_expression *m_field;
333 };
334 ast_entfield* ast_entfield_new(lex_ctx_t ctx, ast_expression *entity, ast_expression *field);
335 ast_entfield* ast_entfield_new_force(lex_ctx_t ctx, ast_expression *entity, ast_expression *field, const ast_expression *outtype);
336
337 /* Member access:
338  *
339  * For now used for vectors. If we get structs or unions
340  * we can have them handled here as well.
341  */
342 struct ast_member : ast_expression
343 {
344     ast_expression *m_owner;
345     unsigned int m_field;
346     const char *m_name;
347     bool m_rvalue;
348 };
349 ast_member* ast_member_new(lex_ctx_t ctx, ast_expression *owner, unsigned int field, const char *name);
350 void ast_member_delete(ast_member*);
351 bool ast_member_set_name(ast_member*, const char *name);
352
353
354 /* Array index access:
355  *
356  * QC forces us to take special action on arrays:
357  * an ast_store on an ast_array_index must not codegen the index,
358  * but call its setter - unless we have an instruction set which supports
359  * what we need.
360  * Any other array index access will be codegened to a call to the getter.
361  * In any case, accessing an element via a compiletime-constant index will
362  * result in quick access to that variable.
363  */
364 struct ast_array_index : ast_expression
365 {
366     ast_expression *m_array;
367     ast_expression *m_index;
368 };
369 ast_array_index* ast_array_index_new(lex_ctx_t ctx, ast_expression *array, ast_expression *index);
370
371 /* Vararg pipe node:
372  *
373  * copy all varargs starting from a specific index
374  */
375 struct ast_argpipe : ast_expression
376 {
377     ast_expression *m_index;
378 };
379 ast_argpipe* ast_argpipe_new(lex_ctx_t ctx, ast_expression *index);
380
381 /* Store
382  *
383  * Stores left<-right and returns left.
384  * Specialized binary expression node
385  */
386 struct ast_store : ast_expression
387 {
388     int m_op;
389     ast_expression *m_dest;
390     ast_expression *m_source;
391 };
392 ast_store* ast_store_new(lex_ctx_t ctx, int op,
393                          ast_expression *d, ast_expression *s);
394
395 /* If
396  *
397  * A general 'if then else' statement, either side can be nullptr and will
398  * thus be omitted. It is an error for *both* cases to be nullptr at once.
399  *
400  * During its 'codegen' it'll be changing the ast_function's block.
401  *
402  * An if is also an "expression". Its codegen will put nullptr into the
403  * output field though. For ternary expressions an ast_ternary will be
404  * added.
405  */
406 struct ast_ifthen : ast_expression
407 {
408     ast_expression *m_cond;
409     /* It's all just 'expressions', since an ast_block is one too. */
410     ast_expression *m_on_true;
411     ast_expression *m_on_false;
412 };
413 ast_ifthen* ast_ifthen_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse);
414
415 /* Ternary expressions...
416  *
417  * Contrary to 'if-then-else' nodes, ternary expressions actually
418  * return a value, otherwise they behave the very same way.
419  * The difference in 'codegen' is that it'll return the value of
420  * a PHI node.
421  *
422  * The other difference is that in an ast_ternary, NEITHER side
423  * must be nullptr, there's ALWAYS an else branch.
424  *
425  * This is the only ast_node beside ast_value which contains
426  * an ir_value. Theoretically we don't need to remember it though.
427  */
428 struct ast_ternary : ast_expression
429 {
430     ast_expression *m_cond;
431     /* It's all just 'expressions', since an ast_block is one too. */
432     ast_expression *m_on_true;
433     ast_expression *m_on_false;
434 };
435 ast_ternary* ast_ternary_new(lex_ctx_t ctx, ast_expression *cond, ast_expression *ontrue, ast_expression *onfalse);
436
437 /* A general loop node
438  *
439  * For convenience it contains 4 parts:
440  * -) (ini) = initializing expression
441  * -) (pre) = pre-loop condition
442  * -) (pst) = post-loop condition
443  * -) (inc) = "increment" expression
444  * The following is a psudo-representation of this loop
445  * note that '=>' bears the logical meaning of "implies".
446  * (a => b) equals (!a || b)
447
448 {ini};
449 while (has_pre => {pre})
450 {
451     {body};
452
453 continue:      // a 'continue' will jump here
454     if (has_pst => {pst})
455         break;
456
457     {inc};
458 }
459  */
460 struct ast_loop : ast_expression
461 {
462     ast_expression *m_initexpr;
463     ast_expression *m_precond;
464     ast_expression *m_postcond;
465     ast_expression *m_increment;
466     ast_expression *m_body;
467     /* For now we allow a seperate flag on whether or not the condition
468      * is supposed to be true or false.
469      * That way, the parser can generate a 'while not(!x)' for `while(x)`
470      * if desired, which is useful for the new -f{true,false}-empty-strings
471      * flag.
472      */
473     bool m_pre_not;
474     bool m_post_not;
475 };
476 ast_loop* ast_loop_new(lex_ctx_t ctx,
477                        ast_expression *initexpr,
478                        ast_expression *precond, bool pre_not,
479                        ast_expression *postcond, bool post_not,
480                        ast_expression *increment,
481                        ast_expression *body);
482
483 /* Break/Continue
484  */
485 struct ast_breakcont : ast_expression
486 {
487     bool         m_is_continue;
488     unsigned int m_levels;
489 };
490 ast_breakcont* ast_breakcont_new(lex_ctx_t ctx, bool iscont, unsigned int levels);
491
492 /* Switch Statements
493  *
494  * A few notes about this: with the original QCVM, no real optimization
495  * is possible. The SWITCH instruction set isn't really helping a lot, since
496  * it only collapes the EQ and IF instructions into one.
497  * Note: Declaring local variables inside caseblocks is normal.
498  * Since we don't have to deal with a stack there's no unnatural behaviour to
499  * be expected from it.
500  * TODO: Ticket #20
501  */
502 struct ast_switch_case {
503     ast_expression *m_value; /* #20 will replace this */
504     ast_expression *m_code;
505 };
506
507 struct ast_switch : ast_expression
508 {
509     ast_expression *m_operand;
510     std::vector<ast_switch_case> m_cases;
511 };
512
513 ast_switch* ast_switch_new(lex_ctx_t ctx, ast_expression *op);
514
515 /* Label nodes
516  *
517  * Introduce a label which can be used together with 'goto'
518  */
519 struct ast_label : ast_expression
520 {
521     const char *m_name;
522     ir_block *m_irblock;
523     std::vector<ast_goto*> m_gotos;
524
525     /* means it has not yet been defined */
526     bool m_undefined;
527 };
528
529 ast_label* ast_label_new(lex_ctx_t ctx, const char *name, bool undefined);
530
531 /* GOTO nodes
532  *
533  * Go to a label, the label node is filled in at a later point!
534  */
535 struct ast_goto : ast_expression
536 {
537     const char *m_name;
538     ast_label *m_target;
539     ir_block *m_irblock_from;
540 };
541
542 ast_goto* ast_goto_new(lex_ctx_t ctx, const char *name);
543 void ast_goto_set_label(ast_goto*, ast_label*);
544
545 /* STATE node
546  *
547  * For frame/think state updates: void foo() [framenum, nextthink] {}
548  */
549 struct ast_state : ast_expression
550 {
551     ast_expression *m_framenum;
552     ast_expression *m_nextthink;
553 };
554 ast_state* ast_state_new(lex_ctx_t ctx, ast_expression *frame, ast_expression *think);
555 void ast_state_delete(ast_state*);
556
557 /* CALL node
558  *
559  * Contains an ast_expression as target, rather than an ast_function/value.
560  * Since it's how QC works, every ast_function has an ast_value
561  * associated anyway - in other words, the VM contains function
562  * pointers for every function anyway. Thus, this node will call
563  * expression.
564  * Additionally it contains a list of ast_expressions as parameters.
565  * Since calls can return values, an ast_call is also an ast_expression.
566  */
567 struct ast_call : ast_expression
568 {
569     ast_expression *m_func;
570     std::vector<ast_expression *> m_params;
571     ast_expression *m_va_count;
572 };
573 ast_call* ast_call_new(lex_ctx_t ctx,
574                        ast_expression *funcexpr);
575 bool ast_call_check_types(ast_call*, ast_expression *this_func_va_type);
576
577 /* Blocks
578  *
579  */
580 struct ast_block : ast_expression
581 {
582     std::vector<ast_value*>      m_locals;
583     std::vector<ast_expression*> m_exprs;
584     std::vector<ast_expression*> m_collect;
585 };
586 ast_block* ast_block_new(lex_ctx_t ctx);
587 void ast_block_delete(ast_block*);
588 void ast_block_set_type(ast_block*, ast_expression *from);
589 void ast_block_collect(ast_block*, ast_expression*);
590
591 bool GMQCC_WARN ast_block_add_expr(ast_block*, ast_expression*);
592
593 /* Function
594  *
595  * Contains a list of blocks... at least in theory.
596  * Usually there's just the main block, other blocks are inside that.
597  *
598  * Technically, functions don't need to be an AST node, since we have
599  * neither functions inside functions, nor lambdas, and function
600  * pointers could just work with a name. However, this way could be
601  * more flexible, and adds no real complexity.
602  */
603 struct ast_function : ast_node
604 {
605     ast_value  *m_function_type;
606     const char *m_name;
607
608     int m_builtin;
609
610     /* list of used-up names for statics without the count suffix */
611     std::vector<char*> m_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 m_static_count;
617
618     ir_function *m_ir_func;
619     ir_block *m_curblock;
620     std::vector<ir_block*> m_breakblocks;
621     std::vector<ir_block*> m_continueblocks;
622
623     size_t m_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 m_labelbuf[64];
629     std::vector<std::unique_ptr<ast_block>> m_blocks;
630     ast_value *m_varargs;
631     ast_value *m_argc;
632     ast_value *m_fixedparams;
633     ast_value *m_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