]> git.xonotic.org Git - xonotic/gmqcc.git/blob - gmqcc.h
constant folding for +, - and *
[xonotic/gmqcc.git] / gmqcc.h
1 /*
2  * Copyright (C) 2012
3  *     Dale Weiler, 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_HDR
24 #define GMQCC_HDR
25 #include <limits.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <stdio.h>
29 #include <stdarg.h>
30 #include <ctype.h>
31
32 #define GMQCC_VERSION_MAJOR 0
33 #define GMQCC_VERSION_MINOR 1
34 #define GMQCC_VERSION_PATCH 0
35 #define GMQCC_VERSION_BUILD(J,N,P) (((J)<<16)|((N)<<8)|(P))
36 #define GMQCC_VERSION \
37     GMQCC_VERSION_BUILD(GMQCC_VERSION_MAJOR, GMQCC_VERSION_MINOR, GMQCC_VERSION_PATCH)
38
39 /*
40  * We cannoy rely on C99 at all, since compilers like MSVC
41  * simply don't support it.  We define our own boolean type
42  * as a result (since we cannot include <stdbool.h>). For
43  * compilers that are in 1999 mode (C99 compliant) we can use
44  * the language keyword _Bool which can allow for better code
45  * on GCC and GCC-like compilers, opposed to `int`.
46  */
47 #ifndef __cplusplus
48 #   ifdef  false
49 #       undef  false
50 #   endif /* !false */
51 #   ifdef  true
52 #       undef true
53 #   endif /* !true  */
54 #   define false (0)
55 #   define true  (1)
56 #   ifdef __STDC_VERSION__
57 #       if __STDC_VERSION__ < 199901L && __GNUC__ < 3
58             typedef int  bool;
59 #       else
60             typedef _Bool bool;
61 #       endif
62 #   else
63         typedef int bool;
64 #   endif /* !__STDC_VERSION__ */
65 #endif    /* !__cplusplus      */
66
67 /*
68  * Of some functions which are generated we want to make sure
69  * that the result isn't ignored. To find such function calls,
70  * we use this macro.
71  */
72 #if defined(__GNUC__) || defined(__CLANG__)
73 #   define GMQCC_WARN __attribute__((warn_unused_result))
74 #else
75 #   define GMQCC_WARN
76 #endif
77 /*
78  * This is a hack to silent clang regarding empty
79  * body if statements.
80  */
81 #define GMQCC_SUPPRESS_EMPTY_BODY do { } while (0)
82
83 /*
84  * Inline is not supported in < C90, however some compilers
85  * like gcc and clang might have an inline attribute we can
86  * use if present.
87  */
88 #ifdef __STDC_VERSION__
89 #    if __STDC_VERSION__ < 199901L
90 #       if defined(__GNUC__) || defined (__CLANG__)
91 #           if __GNUC__ < 2
92 #               define GMQCC_INLINE
93 #           else
94 #               define GMQCC_INLINE __attribute__ ((always_inline))
95 #           endif
96 #       else
97 #           define GMQCC_INLINE
98 #       endif
99 #    else
100 #       define GMQCC_INLINE inline
101 #    endif
102 #else
103 #    define GMQCC_INLINE
104 #endif /* !__STDC_VERSION__ */
105
106 /*
107  * noreturn is present in GCC and clang
108  * it's required for _ast_node_destory otherwise -Wmissing-noreturn
109  * in clang complains about there being no return since abort() is
110  * called.
111  */
112 #if (defined(__GNUC__) && __GNUC__ >= 2) || defined(__CLANG__)
113 #    define GMQCC_NORETURN __attribute__ ((noreturn))
114 #else
115 #    define GMQCC_NORETURN
116 #endif
117
118 /*
119  * stdint.h and inttypes.h -less subset
120  * for systems that don't have it, which we must
121  * assume is all systems. (int8_t not required)
122  */
123 #if   CHAR_MIN  == -128
124     typedef unsigned char  uint8_t; /* same as below */
125 #elif SCHAR_MIN == -128
126     typedef unsigned char  uint8_t; /* same as above */
127 #endif
128 #if   SHRT_MAX  == 0x7FFF
129     typedef short          int16_t;
130     typedef unsigned short uint16_t;
131 #elif INT_MAX   == 0x7FFF
132     typedef int            int16_t;
133     typedef unsigned int   uint16_t;
134 #endif
135 #if   INT_MAX   == 0x7FFFFFFF
136     typedef int            int32_t;
137     typedef unsigned int   uint32_t;
138     typedef long           int64_t;
139     typedef unsigned long  uint64_t;
140 #elif LONG_MAX  == 0x7FFFFFFF
141     typedef long           int32_t;
142     typedef unsigned long  uint32_t;
143
144     /*
145      * It's nearly impossible to figure out a 64bit type at
146      * this point without making assumptions about the build
147      * enviroment.  So if clang or gcc is detected use some
148      * compiler builtins to create a 64 signed and unsigned
149      * type.
150      */
151 #   if defined(__GNUC__) || defined (__CLANG__)
152         typedef int          int64_t  __attribute__((__mode__(__DI__)));
153         typedef unsigned int uint64_t __attribute__((__mode__(__DI__)));
154 #   else
155         /*
156          * Incoorectly size the types so static assertions below will
157          * fail.  There is no valid way to get a 64bit type at this point
158          * without making assumptions of too many things.
159          */
160         typedef struct { char _fail : 0; } int64_t;
161         typedef struct { char _fail : 0; } uint64_t;
162 #   endif
163 #endif
164 #ifdef _LP64 /* long pointer == 64 */
165     typedef unsigned long  uintptr_t;
166     typedef long           intptr_t;
167 #else
168     typedef unsigned int   uintptr_t;
169     typedef int            intptr_t;
170 #endif
171 /* Ensure type sizes are correct: */
172 typedef char uint8_size_is_correct  [sizeof(uint8_t)  == 1?1:-1];
173 typedef char uint16_size_is_correct [sizeof(uint16_t) == 2?1:-1];
174 typedef char uint32_size_is_correct [sizeof(uint32_t) == 4?1:-1];
175 typedef char uint64_size_is_correct [sizeof(uint64_t) == 8?1:-1];
176 typedef char int16_size_if_correct  [sizeof(int16_t)  == 2?1:-1];
177 typedef char int32_size_is_correct  [sizeof(int32_t)  == 4?1:-1];
178 typedef char int64_size_is_correct  [sizeof(int64_t)  == 8?1:-1];
179 /* intptr_t / uintptr_t correct size check */
180 typedef char uintptr_size_is_correct[sizeof(intptr_t) == sizeof(int*)?1:-1];
181 typedef char intptr_size_is_correct [sizeof(uintptr_t)== sizeof(int*)?1:-1];
182
183 /*===================================================================*/
184 /*=========================== util.c ================================*/
185 /*===================================================================*/
186 void *util_memory_a      (unsigned int, unsigned int, const char *);
187 void  util_memory_d      (void       *, unsigned int, const char *);
188 void  util_meminfo       ();
189
190 bool  util_strupper      (const char *);
191 bool  util_strdigit      (const char *);
192 bool  util_strncmpexact  (const char *, const char *, size_t);
193 char *util_strdup        (const char *);
194 char *util_strrq         (const char *);
195 char *util_strrnl        (const char *);
196 char *util_strsws        (const char *);
197 char *util_strchp        (const char *, const char *);
198 void  util_debug         (const char *, const char *, ...);
199 int   util_getline       (char **, size_t *, FILE *);
200 void  util_endianswap    (void *,  int, int);
201
202 size_t util_strtocmd    (const char *, char *, size_t);
203 size_t util_strtononcmd (const char *, char *, size_t);
204
205 uint32_t util_crc32(const char *, int, register const short);
206
207 #ifdef NOTRACK
208 #    define mem_a(x) malloc(x)
209 #    define mem_d(x) free  (x)
210 #else
211 #    define mem_a(x) util_memory_a((x), __LINE__, __FILE__)
212 #    define mem_d(x) util_memory_d((x), __LINE__, __FILE__)
213 #endif
214
215 /*
216  * TODO: make these safer to use.  Currently this only works on
217  * x86 and x86_64, some systems will likely not like this. Such
218  * as BE systems.
219  */
220 #define FLT2INT(Y) *((int32_t*)&(Y))
221 #define INT2FLT(Y) *((float  *)&(Y))
222
223 /* Builds vector type (usefull for inside structures) */
224 #define VECTOR_SNAP(X,Y) X ## Y
225 #define VECTOR_FILL(X,Y) VECTOR_SNAP(X,Y)
226 #define VECTOR_TYPE(T,N)                                        \
227     T*     N##_data      = NULL;                                \
228     long   N##_elements  = 0;                                   \
229     long   N##_allocated = 0
230 /* Builds vector add */
231 #define VECTOR_CORE(T,N)                                        \
232     int    N##_add(T element) {                                 \
233         void *temp = NULL;                                      \
234         if (N##_elements == N##_allocated) {                    \
235             if (N##_allocated == 0) {                           \
236                 N##_allocated = 12;                             \
237             } else {                                            \
238                 N##_allocated *= 2;                             \
239             }                                                   \
240             if  (!(temp = mem_a(N##_allocated * sizeof(T)))) {  \
241                 mem_d(temp);                                    \
242                 return -1;                                      \
243             }                                                   \
244             memcpy(temp, N##_data, (N##_elements * sizeof(T))); \
245             mem_d(N##_data);                                    \
246             N##_data = (T*)temp;                                \
247         }                                                       \
248         N##_data[N##_elements] = element;                       \
249         return   N##_elements++;                                \
250     }                                                           \
251     int N##_put(T* elements, size_t len) {                      \
252         len     --;                                             \
253         elements--;                                             \
254         while (N##_add(*++elements) != -1 && len--);            \
255         return N##_elements;                                    \
256     }                                                           \
257     typedef char VECTOR_FILL(extra_semicolon_##N,__COUNTER__)
258 #define VECTOR_PROT(T,N)                                        \
259     extern T*     N##_data     ;                                \
260     extern long   N##_elements ;                                \
261     extern long   N##_allocated;                                \
262     int           N##_add(T);                                   \
263     int           N##_put(T *, size_t)
264 #define VECTOR_MAKE(T,N) \
265     VECTOR_TYPE(T,N);    \
266     VECTOR_CORE(T,N)
267
268 /*===================================================================*/
269 /*=========================== code.c ================================*/
270 /*===================================================================*/
271
272 /* Note: if you change the order, fix type_sizeof in ir.c */
273 enum {
274     TYPE_VOID     ,
275     TYPE_STRING   ,
276     TYPE_FLOAT    ,
277     TYPE_VECTOR   ,
278     TYPE_ENTITY   ,
279     TYPE_FIELD    ,
280     TYPE_FUNCTION ,
281     TYPE_POINTER  ,
282     TYPE_INTEGER  ,
283     TYPE_VARIANT  ,
284
285     TYPE_COUNT
286 };
287
288 extern const char *type_name[TYPE_COUNT];
289
290 extern size_t type_sizeof[TYPE_COUNT];
291 extern uint16_t type_store_instr[TYPE_COUNT];
292 /* could use type_store_instr + INSTR_STOREP_F - INSTR_STORE_F
293  * but this breaks when TYPE_INTEGER is added, since with the enhanced
294  * instruction set, the old ones are left untouched, thus the _I instructions
295  * are at a seperate place.
296  */
297 extern uint16_t type_storep_instr[TYPE_COUNT];
298 /* other useful lists */
299 extern uint16_t type_eq_instr[TYPE_COUNT];
300 extern uint16_t type_ne_instr[TYPE_COUNT];
301
302 typedef struct {
303     uint32_t offset;      /* Offset in file of where data begins  */
304     uint32_t length;      /* Length of section (how many of)      */
305 } prog_section;
306
307 typedef struct {
308     uint32_t     version;      /* Program version (6)     */
309     uint16_t     crc16;        /* What is this?           */
310     uint16_t     skip;         /* see propsal.txt         */
311
312     prog_section statements;   /* prog_section_statement  */
313     prog_section defs;         /* prog_section_def        */
314     prog_section fields;       /* prog_section_field      */
315     prog_section functions;    /* prog_section_function   */
316     prog_section strings;      /* What is this?           */
317     prog_section globals;      /* What is this?           */
318     uint32_t     entfield;     /* Number of entity fields */
319 } prog_header;
320
321 /*
322  * Each paramater incerements by 3 since vector types hold
323  * 3 components (x,y,z).
324  */
325 #define OFS_NULL      0
326 #define OFS_RETURN    1
327 #define OFS_PARM0     (OFS_RETURN+3)
328 #define OFS_PARM1     (OFS_PARM0 +3)
329 #define OFS_PARM2     (OFS_PARM1 +3)
330 #define OFS_PARM3     (OFS_PARM2 +3)
331 #define OFS_PARM4     (OFS_PARM3 +3)
332 #define OFS_PARM5     (OFS_PARM4 +3)
333 #define OFS_PARM6     (OFS_PARM5 +3)
334 #define OFS_PARM7     (OFS_PARM6 +3)
335
336 typedef struct {
337     uint16_t opcode;
338
339     /* operand 1 */
340     union {
341         int16_t  s1; /* signed   */
342         uint16_t u1; /* unsigned */
343     } o1;
344     /* operand 2 */
345     union {
346         int16_t  s1; /* signed   */
347         uint16_t u1; /* unsigned */
348     } o2;
349     /* operand 3 */
350     union {
351         int16_t  s1; /* signed   */
352         uint16_t u1; /* unsigned */
353     } o3;
354
355     /*
356      * This is the same as the structure in darkplaces
357      * {
358      *     unsigned short op;
359      *     short          a,b,c;
360      * }
361      * But this one is more sane to work with, and the
362      * type sizes are guranteed.
363      */
364 } prog_section_statement;
365
366 typedef struct {
367     /* The types:
368      * 0 = ev_void
369      * 1 = ev_string
370      * 2 = ev_float
371      * 3 = ev_vector
372      * 4 = ev_entity
373      * 5 = ev_field
374      * 6 = ev_function
375      * 7 = ev_pointer -- engine only
376      * 8 = ev_bad     -- engine only
377      */
378     uint16_t type;
379     uint16_t offset;
380     uint32_t name;
381 } prog_section_both;
382 typedef prog_section_both prog_section_def;
383 typedef prog_section_both prog_section_field;
384
385 typedef struct {
386     int32_t   entry;      /* in statement table for instructions  */
387     uint32_t  firstlocal; /* First local in local table           */
388     uint32_t  locals;     /* Total ints of params + locals        */
389     uint32_t  profile;    /* Always zero (engine uses this)       */
390     uint32_t  name;       /* name of function in string table     */
391     uint32_t  file;       /* file of the source file              */
392     uint32_t  nargs;      /* number of arguments                  */
393     uint8_t   argsize[8]; /* size of arguments (keep 8 always?)   */
394 } prog_section_function;
395
396 /*
397  * Instructions
398  * These are the external instructions supported by the interperter
399  * this is what things compile to (from the C code).
400  */
401 enum {
402     INSTR_DONE,
403     INSTR_MUL_F,
404     INSTR_MUL_V,
405     INSTR_MUL_FV,
406     INSTR_MUL_VF,
407     INSTR_DIV_F,
408     INSTR_ADD_F,
409     INSTR_ADD_V,
410     INSTR_SUB_F,
411     INSTR_SUB_V,
412     INSTR_EQ_F,
413     INSTR_EQ_V,
414     INSTR_EQ_S,
415     INSTR_EQ_E,
416     INSTR_EQ_FNC,
417     INSTR_NE_F,
418     INSTR_NE_V,
419     INSTR_NE_S,
420     INSTR_NE_E,
421     INSTR_NE_FNC,
422     INSTR_LE,
423     INSTR_GE,
424     INSTR_LT,
425     INSTR_GT,
426     INSTR_LOAD_F,
427     INSTR_LOAD_V,
428     INSTR_LOAD_S,
429     INSTR_LOAD_ENT,
430     INSTR_LOAD_FLD,
431     INSTR_LOAD_FNC,
432     INSTR_ADDRESS,
433     INSTR_STORE_F,
434     INSTR_STORE_V,
435     INSTR_STORE_S,
436     INSTR_STORE_ENT,
437     INSTR_STORE_FLD,
438     INSTR_STORE_FNC,
439     INSTR_STOREP_F,
440     INSTR_STOREP_V,
441     INSTR_STOREP_S,
442     INSTR_STOREP_ENT,
443     INSTR_STOREP_FLD,
444     INSTR_STOREP_FNC,
445     INSTR_RETURN,
446     INSTR_NOT_F,
447     INSTR_NOT_V,
448     INSTR_NOT_S,
449     INSTR_NOT_ENT,
450     INSTR_NOT_FNC,
451     INSTR_IF,
452     INSTR_IFNOT,
453     INSTR_CALL0,
454     INSTR_CALL1,
455     INSTR_CALL2,
456     INSTR_CALL3,
457     INSTR_CALL4,
458     INSTR_CALL5,
459     INSTR_CALL6,
460     INSTR_CALL7,
461     INSTR_CALL8,
462     INSTR_STATE,
463     INSTR_GOTO,
464     INSTR_AND,
465     INSTR_OR,
466     INSTR_BITAND,
467     INSTR_BITOR,
468
469     /*
470      * Virtual instructions used by the assembler
471      * keep at the end but before virtual instructions
472      * for the IR below.
473      */
474     AINSTR_END,
475
476     /*
477      * Virtual instructions used by the IR
478      * Keep at the end!
479      */
480     VINSTR_PHI,
481     VINSTR_JUMP,
482     VINSTR_COND
483 };
484
485 /*
486  * The symbols below are created by the following
487  * expanded macros:
488  *
489  * VECTOR_MAKE(prog_section_statement, code_statements);
490  * VECTOR_MAKE(prog_section_def,       code_defs      );
491  * VECTOR_MAKE(prog_section_field,     code_fields    );
492  * VECTOR_MAKE(prog_section_function,  code_functions );
493  * VECTOR_MAKE(int,                    code_globals   );
494  * VECTOR_MAKE(char,                   code_chars     );
495  */
496 VECTOR_PROT(prog_section_statement, code_statements);
497 VECTOR_PROT(prog_section_statement, code_statements);
498 VECTOR_PROT(prog_section_def,       code_defs      );
499 VECTOR_PROT(prog_section_field,     code_fields    );
500 VECTOR_PROT(prog_section_function,  code_functions );
501 VECTOR_PROT(int,                    code_globals   );
502 VECTOR_PROT(char,                   code_chars     );
503
504 typedef float   qcfloat;
505 typedef int32_t qcint;
506
507 /*
508  * code_write -- writes out the compiled file
509  * code_init  -- prepares the code file
510  */
511 bool     code_write       (const char *filename);
512 void     code_init        ();
513 uint32_t code_genstring   (const char *string);
514 uint32_t code_cachedstring(const char *string);
515 qcint    code_alloc_field (size_t qcsize);
516
517 /*===================================================================*/
518 /*========================= assembler.c =============================*/
519 /*===================================================================*/
520 static const struct {
521     const char  *m; /* menomic     */
522     const size_t o; /* operands    */
523     const size_t l; /* menomic len */
524 } asm_instr[] = {
525     { "DONE"      , 1, 4 },
526     { "MUL_F"     , 3, 5 },
527     { "MUL_V"     , 3, 5 },
528     { "MUL_FV"    , 3, 6 },
529     { "MUL_VF"    , 3, 6 },
530     { "DIV"       , 0, 3 },
531     { "ADD_F"     , 3, 5 },
532     { "ADD_V"     , 3, 5 },
533     { "SUB_F"     , 3, 5 },
534     { "DUB_V"     , 3, 5 },
535     { "EQ_F"      , 0, 4 },
536     { "EQ_V"      , 0, 4 },
537     { "EQ_S"      , 0, 4 },
538     { "EQ_E"      , 0, 4 },
539     { "EQ_FNC"    , 0, 6 },
540     { "NE_F"      , 0, 4 },
541     { "NE_V"      , 0, 4 },
542     { "NE_S"      , 0, 4 },
543     { "NE_E"      , 0, 4 },
544     { "NE_FNC"    , 0, 6 },
545     { "LE"        , 0, 2 },
546     { "GE"        , 0, 2 },
547     { "LT"        , 0, 2 },
548     { "GT"        , 0, 2 },
549     { "FIELD_F"   , 0, 7 },
550     { "FIELD_V"   , 0, 7 },
551     { "FIELD_S"   , 0, 7 },
552     { "FIELD_ENT" , 0, 9 },
553     { "FIELD_FLD" , 0, 9 },
554     { "FIELD_FNC" , 0, 9 },
555     { "ADDRESS"   , 0, 7 },
556     { "STORE_F"   , 0, 7 },
557     { "STORE_V"   , 0, 7 },
558     { "STORE_S"   , 0, 7 },
559     { "STORE_ENT" , 0, 9 },
560     { "STORE_FLD" , 0, 9 },
561     { "STORE_FNC" , 0, 9 },
562     { "STOREP_F"  , 0, 8 },
563     { "STOREP_V"  , 0, 8 },
564     { "STOREP_S"  , 0, 8 },
565     { "STOREP_ENT", 0, 10},
566     { "STOREP_FLD", 0, 10},
567     { "STOREP_FNC", 0, 10},
568     { "RETURN"    , 0, 6 },
569     { "NOT_F"     , 0, 5 },
570     { "NOT_V"     , 0, 5 },
571     { "NOT_S"     , 0, 5 },
572     { "NOT_ENT"   , 0, 7 },
573     { "NOT_FNC"   , 0, 7 },
574     { "IF"        , 0, 2 },
575     { "IFNOT"     , 0, 5 },
576     { "CALL0"     , 1, 5 },
577     { "CALL1"     , 2, 5 },
578     { "CALL2"     , 3, 5 },
579     { "CALL3"     , 4, 5 },
580     { "CALL4"     , 5, 5 },
581     { "CALL5"     , 6, 5 },
582     { "CALL6"     , 7, 5 },
583     { "CALL7"     , 8, 5 },
584     { "CALL8"     , 9, 5 },
585     { "STATE"     , 0, 5 },
586     { "GOTO"      , 0, 4 },
587     { "AND"       , 0, 3 },
588     { "OR"        , 0, 2 },
589     { "BITAND"    , 0, 6 },
590     { "BITOR"     , 0, 5 },
591
592     { "END"       , 0, 3 } /* virtual assembler instruction */
593 };
594
595 void asm_init (const char *, FILE **);
596 void asm_close(FILE *);
597 void asm_parse(FILE *);
598 /*===================================================================*/
599 /*============================= ast.c ===============================*/
600 /*===================================================================*/
601 #define MEM_VECTOR_PROTO(Towner, Tmem, mem)                   \
602     bool GMQCC_WARN Towner##_##mem##_add(Towner*, Tmem);      \
603     bool GMQCC_WARN Towner##_##mem##_remove(Towner*, size_t)
604
605 #define MEM_VECTOR_PROTO_ALL(Towner, Tmem, mem)                    \
606     MEM_VECTOR_PROTO(Towner, Tmem, mem);                           \
607     bool GMQCC_WARN Towner##_##mem##_find(Towner*, Tmem, size_t*); \
608     void Towner##_##mem##_clear(Towner*)
609
610 #define MEM_VECTOR_MAKE(Twhat, name) \
611     Twhat  *name;                    \
612     size_t name##_count;             \
613     size_t name##_alloc
614
615 #define MEM_VEC_FUN_ADD(Tself, Twhat, mem)                           \
616 bool GMQCC_WARN Tself##_##mem##_add(Tself *self, Twhat f)            \
617 {                                                                    \
618     Twhat *reall;                                                    \
619     if (self->mem##_count == self->mem##_alloc) {                    \
620         if (!self->mem##_alloc) {                                    \
621             self->mem##_alloc = 16;                                  \
622         } else {                                                     \
623             self->mem##_alloc *= 2;                                  \
624         }                                                            \
625         reall = (Twhat*)mem_a(sizeof(Twhat) * self->mem##_alloc);    \
626         if (!reall) {                                                \
627             return false;                                            \
628         }                                                            \
629         memcpy(reall, self->mem, sizeof(Twhat) * self->mem##_count); \
630         mem_d(self->mem);                                            \
631         self->mem = reall;                                           \
632     }                                                                \
633     self->mem[self->mem##_count++] = f;                              \
634     return true;                                                     \
635 }
636
637 #define MEM_VEC_FUN_REMOVE(Tself, Twhat, mem)                        \
638 bool GMQCC_WARN Tself##_##mem##_remove(Tself *self, size_t idx)      \
639 {                                                                    \
640     size_t i;                                                        \
641     Twhat *reall;                                                    \
642     if (idx >= self->mem##_count) {                                  \
643         return true; /* huh... */                                    \
644     }                                                                \
645     for (i = idx; i < self->mem##_count-1; ++i) {                    \
646         self->mem[i] = self->mem[i+1];                               \
647     }                                                                \
648     self->mem##_count--;                                             \
649     if (self->mem##_count < self->mem##_count/2) {                   \
650         self->mem##_alloc /= 2;                                      \
651         reall = (Twhat*)mem_a(sizeof(Twhat) * self->mem##_count);    \
652         if (!reall) {                                                \
653             return false;                                            \
654         }                                                            \
655         memcpy(reall, self->mem, sizeof(Twhat) * self->mem##_count); \
656         mem_d(self->mem);                                            \
657         self->mem = reall;                                           \
658     }                                                                \
659     return true;                                                     \
660 }
661
662 #define MEM_VEC_FUN_FIND(Tself, Twhat, mem)                     \
663 bool GMQCC_WARN Tself##_##mem##_find(Tself *self, Twhat obj, size_t *idx) \
664 {                                                               \
665     size_t i;                                                   \
666     for (i = 0; i < self->mem##_count; ++i) {                   \
667         if (self->mem[i] == obj) {                              \
668             if (idx) {                                          \
669                 *idx = i;                                       \
670             }                                                   \
671             return true;                                        \
672         }                                                       \
673     }                                                           \
674     return false;                                               \
675 }
676
677 #define MEM_VEC_FUN_APPEND(Tself, Twhat, mem)                        \
678 bool GMQCC_WARN Tself##_##mem##_append(Tself *s, Twhat *p, size_t c) \
679 {                                                                    \
680     Twhat *reall;                                                    \
681     if (s->mem##_count+c >= s->mem##_alloc) {                        \
682         if (!s->mem##_alloc) {                                       \
683             s->mem##_alloc = c < 16 ? 16 : c;                        \
684         } else {                                                     \
685             s->mem##_alloc *= 2;                                     \
686             if (s->mem##_count+c >= s->mem##_alloc) {                \
687                 s->mem##_alloc = s->mem##_count+c;                   \
688             }                                                        \
689         }                                                            \
690         reall = (Twhat*)mem_a(sizeof(Twhat) * s->mem##_alloc);       \
691         if (!reall) {                                                \
692             return false;                                            \
693         }                                                            \
694         memcpy(reall, s->mem, sizeof(Twhat) * s->mem##_count);       \
695         mem_d(s->mem);                                               \
696         s->mem = reall;                                              \
697     }                                                                \
698     memcpy(&s->mem[s->mem##_count], p, c*sizeof(*p));                \
699     s->mem##_count += c;                                             \
700     return true;                                                     \
701 }
702
703 #define MEM_VEC_FUN_RESIZE(Tself, Twhat, mem)                    \
704 bool GMQCC_WARN Tself##_##mem##_resize(Tself *s, size_t c)       \
705 {                                                                \
706     Twhat *reall;                                                \
707     if (c > s->mem##_alloc) {                                    \
708         reall = (Twhat*)mem_a(sizeof(Twhat) * c);                \
709         if (!reall) { return false; }                            \
710         memcpy(reall, s->mem, sizeof(Twhat) * s->mem##_count);   \
711         s->mem##_alloc = c;                                      \
712         mem_d(s->mem);                                           \
713         s->mem = reall;                                          \
714         return true;                                             \
715     }                                                            \
716     s->mem##_count = c;                                          \
717     if (c < (s->mem##_alloc / 2)) {                              \
718         reall = (Twhat*)mem_a(sizeof(Twhat) * c);                \
719         if (!reall) { return false; }                            \
720         memcpy(reall, s->mem, sizeof(Twhat) * c);                \
721         mem_d(s->mem);                                           \
722         s->mem = reall;                                          \
723     }                                                            \
724     return true;                                                 \
725 }
726
727 #define MEM_VEC_FUN_CLEAR(Tself, mem)   \
728 void Tself##_##mem##_clear(Tself *self) \
729 {                                       \
730     if (!self->mem)                     \
731         return;                         \
732     mem_d((void*) self->mem);           \
733     self->mem = NULL;                   \
734     self->mem##_count = 0;              \
735     self->mem##_alloc = 0;              \
736 }
737
738 #define MEM_VECTOR_CLEAR(owner, mem)  \
739     if ((owner)->mem)                 \
740         mem_d((void*)((owner)->mem)); \
741     (owner)->mem = NULL;              \
742     (owner)->mem##_count = 0;         \
743     (owner)->mem##_alloc = 0
744
745 #define MEM_VECTOR_INIT(owner, mem) \
746 {                                   \
747     (owner)->mem = NULL;            \
748     (owner)->mem##_count = 0;       \
749     (owner)->mem##_alloc = 0;       \
750 }
751
752 #define MEM_VECTOR_MOVE(from, mem, to, tm)   \
753 {                                            \
754     (to)->tm = (from)->mem;                  \
755     (to)->tm##_count = (from)->mem##_count;  \
756     (to)->tm##_alloc = (from)->mem##_alloc;  \
757     (from)->mem = NULL;                      \
758     (from)->mem##_count = 0;                 \
759     (from)->mem##_alloc = 0;                 \
760 }
761
762 #define MEM_VEC_FUNCTIONS(Tself, Twhat, mem) \
763 MEM_VEC_FUN_REMOVE(Tself, Twhat, mem)        \
764 MEM_VEC_FUN_ADD(Tself, Twhat, mem)
765
766 #define MEM_VEC_FUNCTIONS_ALL(Tself, Twhat, mem) \
767 MEM_VEC_FUNCTIONS(Tself, Twhat, mem)             \
768 MEM_VEC_FUN_CLEAR(Tself, mem)                    \
769 MEM_VEC_FUN_FIND(Tself, Twhat, mem)
770
771 enum store_types {
772     store_global,
773     store_local,  /* local, assignable for now, should get promoted later */
774     store_param,  /* parameters, they are locals with a fixed position */
775     store_value,  /* unassignable */
776     store_return  /* unassignable, at OFS_RETURN */
777 };
778
779 typedef struct {
780     float x, y, z;
781 } vector;
782
783 vector  vec3_add  (vector, vector);
784 vector  vec3_sub  (vector, vector);
785 qcfloat vec3_mulvv(vector, vector);
786 vector  vec3_mulvf(vector, float);
787
788 /*
789  * A shallow copy of a lex_file to remember where which ast node
790  * came from.
791  */
792 typedef struct {
793     const char *file;
794     size_t      line;
795 } lex_ctx;
796
797 /*===================================================================*/
798 /*============================= exec.c ==============================*/
799 /*===================================================================*/
800
801 /* darkplaces has (or will have) a 64 bit prog loader
802  * where the 32 bit qc program is autoconverted on load.
803  * Since we may want to support that as well, let's redefine
804  * float and int here.
805  */
806 typedef union {
807     qcint   _int;
808     qcint    string;
809     qcint    function;
810     qcint    edict;
811     qcfloat _float;
812     qcfloat vector[3];
813     qcint   ivector[3];
814 } qcany;
815
816 typedef char qcfloat_size_is_correct [sizeof(qcfloat) == 4 ?1:-1];
817 typedef char qcint_size_is_correct   [sizeof(qcint)   == 4 ?1:-1];
818
819 enum {
820     VMERR_OK,
821     VMERR_TEMPSTRING_ALLOC,
822
823     VMERR_END
824 };
825
826 #define VM_JUMPS_DEFAULT 1000000
827
828 /* execute-flags */
829 #define VMXF_DEFAULT 0x0000     /* default flags - nothing */
830 #define VMXF_TRACE   0x0001     /* trace: print statements before executing */
831 #define VMXF_PROFILE 0x0002     /* profile: increment the profile counters */
832
833 struct qc_program_s;
834
835 typedef int (*prog_builtin)(struct qc_program_s *prog);
836
837 typedef struct {
838     qcint                  stmt;
839     size_t                 localsp;
840     prog_section_function *function;
841 } qc_exec_stack;
842
843 typedef struct qc_program_s {
844     char           *filename;
845
846     MEM_VECTOR_MAKE(prog_section_statement, code);
847     MEM_VECTOR_MAKE(prog_section_def,       defs);
848     MEM_VECTOR_MAKE(prog_section_def,       fields);
849     MEM_VECTOR_MAKE(prog_section_function,  functions);
850     MEM_VECTOR_MAKE(char,                   strings);
851     MEM_VECTOR_MAKE(qcint,                  globals);
852     MEM_VECTOR_MAKE(qcint,                  entitydata);
853     MEM_VECTOR_MAKE(bool,                   entitypool);
854
855     size_t tempstring_start;
856     size_t tempstring_at;
857
858     qcint  vmerror;
859
860     MEM_VECTOR_MAKE(size_t, profile);
861
862     MEM_VECTOR_MAKE(prog_builtin, builtins);
863
864     /* size_t ip; */
865     qcint  entities;
866     size_t entityfields;
867     bool   allowworldwrites;
868
869     MEM_VECTOR_MAKE(qcint,         localstack);
870     MEM_VECTOR_MAKE(qc_exec_stack, stack);
871     size_t statement;
872
873     int    argc; /* current arg count for debugging */
874 } qc_program;
875
876 qc_program* prog_load(const char *filename);
877 void        prog_delete(qc_program *prog);
878
879 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps);
880
881 char*             prog_getstring (qc_program *prog, qcint str);
882 prog_section_def* prog_entfield  (qc_program *prog, qcint off);
883 prog_section_def* prog_getdef    (qc_program *prog, qcint off);
884 qcany*            prog_getedict  (qc_program *prog, qcint e);
885 qcint             prog_tempstring(qc_program *prog, const char *_str);
886
887 /*===================================================================*/
888 /*===================== error.c message printer =====================*/
889 /*===================================================================*/
890
891 #ifndef WIN32
892 enum {
893     CON_BLACK   = 30,
894     CON_RED,
895     CON_GREEN,
896     CON_BROWN,
897     CON_BLUE,
898     CON_MAGENTA,
899     CON_CYAN ,
900     CON_WHITE
901 };
902 #endif
903 enum {
904     LVL_MSG,
905     LVL_WARNING,
906     LVL_ERROR
907 };
908
909 void vprintmsg (int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap);
910 void printmsg  (int level, const char *name, size_t line, const char *msgtype, const char *msg, ...);
911 void cvprintmsg(lex_ctx ctx, int lvl, const char *msgtype, const char *msg, va_list ap);
912 void cprintmsg (lex_ctx ctx, int lvl, const char *msgtype, const char *msg, ...);
913
914 /*===================================================================*/
915 /*===================== parser.c commandline ========================*/
916 /*===================================================================*/
917
918 bool parser_init   ();
919 bool parser_compile(const char *filename);
920 bool parser_finish (const char *output);
921 void parser_cleanup();
922
923 /*===================================================================*/
924 /*======================= main.c commandline ========================*/
925 /*===================================================================*/
926
927 #if 0
928 /* Helpers to allow for a whole lot of flags. Otherwise we'd limit
929  * to 32 or 64 -f options...
930  */
931 typedef struct {
932     size_t  idx; /* index into an array of 32 bit words */
933     uint8_t bit; /* index _into_ the 32 bit word, thus just uint8 */
934 } longbit;
935 #define LONGBIT(bit) { ((bit)/32), ((bit)%32) }
936 #else
937 typedef uint32_t longbit;
938 #define LONGBIT(bit) (bit)
939 #endif
940
941 /* Used to store the list of flags with names */
942 typedef struct {
943     const char *name;
944     longbit    bit;
945 } opts_flag_def;
946
947 /*===================================================================*/
948 /* list of -f flags, like -fdarkplaces-string-table-bug */
949 enum {
950 # define GMQCC_DEFINE_FLAG(X) X,
951 #  include "flags.def"
952 # undef GMQCC_DEFINE_FLAG
953     COUNT_FLAGS
954 };
955 static const opts_flag_def opts_flag_list[] = {
956 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(X) },
957 #  include "flags.def"
958 # undef GMQCC_DEFINE_FLAG
959     { NULL, LONGBIT(0) }
960 };
961
962 enum {
963 # define GMQCC_DEFINE_FLAG(X) WARN_##X,
964 #  include "warns.def"
965 # undef GMQCC_DEFINE_FLAG
966     COUNT_WARNINGS
967 };
968 static const opts_flag_def opts_warn_list[] = {
969 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(WARN_##X) },
970 #  include "warns.def"
971 # undef GMQCC_DEFINE_FLAG
972     { NULL, LONGBIT(0) }
973 };
974
975 /* other options: */
976 enum {
977     COMPILER_QCC,     /* circa  QuakeC */
978     COMPILER_FTEQCC,  /* fteqcc QuakeC */
979     COMPILER_QCCX,    /* qccx   QuakeC */
980     COMPILER_GMQCC    /* this   QuakeC */
981 };
982 extern uint32_t    opts_O;      /* -Ox */
983 extern const char *opts_output; /* -o file */
984 extern int         opts_standard;
985 extern bool        opts_debug;
986 extern bool        opts_memchk;
987 extern bool        opts_dump;
988
989 /*===================================================================*/
990 #define OPTS_FLAG(i) (!! (opts_flags[(i)/32] & (1<< ((i)%32))))
991 extern uint32_t opts_flags[1 + (COUNT_FLAGS / 32)];
992 #define OPTS_WARN(i) (!! (opts_warn[(i)/32] & (1<< ((i)%32))))
993 extern uint32_t opts_warn[1 + (COUNT_WARNINGS / 32)];
994
995 #endif