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