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