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