]> git.xonotic.org Git - xonotic/gmqcc.git/blob - gmqcc.h
No more hacks
[xonotic/gmqcc.git] / gmqcc.h
1 /*
2  * Copyright (C) 2012
3  *     Dale Weiler
4  *     Wolfgang Bumiller
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_HDR
25 #define GMQCC_HDR
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <ctype.h>
32
33 /*
34  * Disable some over protective warnings in visual studio because fixing them is a waste
35  * of my time.
36  */
37 #ifdef _MSC_VER
38 #       pragma warning(disable : 4244 ) /* conversion from 'int' to 'float', possible loss of data */
39 #       pragma warning(disable : 4018 ) /* signed/unsigned mismatch                                */
40 #       pragma warning(disable : 4996 ) /* This function or variable may be unsafe                 */
41 #       pragma warning(disable : 4700 ) /* uninitialized local variable used                       */
42 #endif
43
44 #define GMQCC_VERSION_MAJOR 0
45 #define GMQCC_VERSION_MINOR 2
46 #define GMQCC_VERSION_PATCH 0
47 #define GMQCC_VERSION_BUILD(J,N,P) (((J)<<16)|((N)<<8)|(P))
48 #define GMQCC_VERSION \
49     GMQCC_VERSION_BUILD(GMQCC_VERSION_MAJOR, GMQCC_VERSION_MINOR, GMQCC_VERSION_PATCH)
50
51 /*
52  * We cannoy rely on C99 at all, since compilers like MSVC
53  * simply don't support it.  We define our own boolean type
54  * as a result (since we cannot include <stdbool.h>). For
55  * compilers that are in 1999 mode (C99 compliant) we can use
56  * the language keyword _Bool which can allow for better code
57  * on GCC and GCC-like compilers, opposed to `int`.
58  */
59 #ifndef __cplusplus
60 #   ifdef  false
61 #       undef  false
62 #   endif /* !false */
63 #   ifdef  true
64 #       undef true
65 #   endif /* !true  */
66 #   define false (0)
67 #   define true  (1)
68 #   ifdef __STDC_VERSION__
69 #       if __STDC_VERSION__ < 199901L && __GNUC__ < 3
70             typedef int  bool;
71 #       else
72             typedef _Bool bool;
73 #       endif
74 #   else
75         typedef int bool;
76 #   endif /* !__STDC_VERSION__ */
77 #endif    /* !__cplusplus      */
78
79 /*
80  * Of some functions which are generated we want to make sure
81  * that the result isn't ignored. To find such function calls,
82  * we use this macro.
83  */
84 #if defined(__GNUC__) || defined(__CLANG__)
85 #   define GMQCC_WARN __attribute__((warn_unused_result))
86 #else
87 #   define GMQCC_WARN
88 #endif
89 /*
90  * This is a hack to silent clang regarding empty
91  * body if statements.
92  */
93 #define GMQCC_SUPPRESS_EMPTY_BODY do { } while (0)
94
95 /*
96  * Inline is not supported in < C90, however some compilers
97  * like gcc and clang might have an inline attribute we can
98  * use if present.
99  */
100 #ifdef __STDC_VERSION__
101 #    if __STDC_VERSION__ < 199901L
102 #       if defined(__GNUC__) || defined (__CLANG__)
103 #           if __GNUC__ < 2
104 #               define GMQCC_INLINE
105 #           else
106 #               define GMQCC_INLINE __attribute__ ((always_inline))
107 #           endif
108 #       else
109 #           define GMQCC_INLINE
110 #       endif
111 #    else
112 #       define GMQCC_INLINE inline
113 #    endif
114 /*
115  * Visual studio has __forcinline we can use.  So lets use that
116  * I suspect it also has just __inline of some sort, but our use
117  * of inline is correct (not guessed), WE WANT IT TO BE INLINE
118  */
119 #elif defined(_MSC_VER)
120 #    define GMQCC_INLINE __forceinline
121 #else
122 #    define GMQCC_INLINE
123 #endif /* !__STDC_VERSION__ */
124
125 /*
126  * noreturn is present in GCC and clang
127  * it's required for _ast_node_destory otherwise -Wmissing-noreturn
128  * in clang complains about there being no return since abort() is
129  * called.
130  */
131 #if (defined(__GNUC__) && __GNUC__ >= 2) || defined(__CLANG__)
132 #    define GMQCC_NORETURN __attribute__ ((noreturn))
133 #else
134 #    define GMQCC_NORETURN
135 #endif
136
137 /* TODO: visual studiblows work around */
138 #ifndef _MSC_VER
139 #   include <stdint.h>
140 #endif
141
142 /*===================================================================*/
143 /*=========================== util.c ================================*/
144 /*===================================================================*/
145 FILE *util_fopen(const char *filename, const char *mode);
146
147 void *util_memory_a      (size_t,       unsigned int, const char *);
148 void  util_memory_d      (void       *, unsigned int, const char *);
149 void *util_memory_r      (void       *, size_t,       unsigned int, const char *);
150 void  util_meminfo       ();
151
152 bool  util_filexists     (const char *);
153 bool  util_strupper      (const char *);
154 bool  util_strdigit      (const char *);
155 bool  util_strncmpexact  (const char *, const char *, size_t);
156 char *util_strdup        (const char *);
157 char *util_strrq         (const char *);
158 char *util_strrnl        (const char *);
159 char *util_strsws        (const char *);
160 char *util_strchp        (const char *, const char *);
161 void  util_debug         (const char *, const char *, ...);
162 int   util_getline       (char **, size_t *, FILE *);
163 void  util_endianswap    (void *,  int, int);
164
165 size_t util_strtocmd    (const char *, char *, size_t);
166 size_t util_strtononcmd (const char *, char *, size_t);
167
168 uint16_t util_crc16(uint16_t crc, const char *data, size_t len);
169 uint32_t util_crc32(uint32_t crc, const char *data, size_t len);
170
171 #ifdef NOTRACK
172 #    define mem_a(x)    malloc (x)
173 #    define mem_d(x)    free   (x)
174 #    define mem_r(x, n) realloc(x, n)
175 #else
176 #    define mem_a(x)    util_memory_a((x), __LINE__, __FILE__)
177 #    define mem_d(x)    util_memory_d((x), __LINE__, __FILE__)
178 #    define mem_r(x, n) util_memory_r((x), (n), __LINE__, __FILE__)
179 #endif
180
181 /*
182  * TODO: make these safer to use.  Currently this only works on
183  * x86 and x86_64, some systems will likely not like this. Such
184  * as BE systems.
185  */
186 #define FLT2INT(Y) *((int32_t*)&(Y))
187 #define INT2FLT(Y) *((float  *)&(Y))
188
189 /* New flexible vector implementation from Dale */
190 #define _vec_raw(A) (((size_t*)(void*)(A)) - 2)
191 #define _vec_beg(A) (_vec_raw(A)[0])
192 #define _vec_end(A) (_vec_raw(A)[1])
193 #define _vec_needsgrow(A,N) ((!(A)) || (_vec_end(A) + (N) >= _vec_beg(A)))
194 #define _vec_mightgrow(A,N) (_vec_needsgrow((A), (N)) ? (void)_vec_forcegrow((A),(N)) : (void)0)
195 #define _vec_forcegrow(A,N) _util_vec_grow(((void**)&(A)), (N), sizeof(*(A)))
196 #define _vec_remove(A,S,I,N) (memmove((char*)(A)+(I)*(S),(char*)(A)+((I)+(N))*(S),(S)*(_vec_end(A)-(I)-(N))), _vec_end(A)-=(N))
197 void _util_vec_grow(void **a, size_t i, size_t s);
198 /* exposed interface */
199 #define vec_free(A)          ((A) ? (mem_d((void*)_vec_raw(A)), (A) = NULL) : 0)
200 #define vec_push(A,V)        (_vec_mightgrow((A),1), (A)[_vec_end(A)++] = (V))
201 #define vec_size(A)          ((A) ? _vec_end(A) : 0)
202 #define vec_add(A,N)         (_vec_mightgrow((A),(N)), _vec_end(A)+=(N), &(A)[_vec_end(A)-(N)])
203 #define vec_last(A)          ((A)[_vec_end(A)-1])
204 #define vec_append(A,N,S)    memcpy(vec_add((A), (N)), (S), N * sizeof(*(S)))
205 #define vec_remove(A,I,N)    _vec_remove((A), sizeof(*(A)), (I), (N))
206 #define vec_pop(A)           (_vec_end(A)-=1)
207 /* these are supposed to NOT reallocate */
208 #define vec_shrinkto(A,N)    (_vec_end(A) = (N))
209 #define vec_shrinkby(A,N)    (_vec_end(A) -= (N))
210
211 #define vec_upload(X,Y,S)      \
212     do {                       \
213         size_t E = 0;          \
214         while (E < S) {        \
215             vec_push(X, Y[E]); \
216             E ++;              \
217         }                      \
218     } while(0)
219
220 typedef struct hash_table_t {
221     size_t                size;
222     struct hash_node_t **table;
223 } hash_table_t, *ht;
224
225 /*
226  * hashtable implementation:
227  *
228  * Note:
229  *      This was designed for pointers:  you manage the life of the object yourself
230  *      if you do use this for non-pointers please be warned that the object may not
231  *      be valid if the duration of it exceeds (i.e on stack).  So you need to allocate
232  *      yourself, or put those in global scope to ensure duration is for the whole
233  *      runtime.
234  *
235  * util_htnew(size)                             -- to make a new hashtable
236  * util_htset(table, key, value, sizeof(value)) -- to set something in the table
237  * util_htget(table, key)                       -- to get something from the table
238  * util_htdel(table)                            -- to delete the table
239  *
240  * example of use:
241  *
242  * ht    foo  = util_htnew(1024);
243  * int   data = 100;
244  * char *test = "hello world\n";
245  * util_htset(foo, "foo", (void*)&data);
246  * util_gtset(foo, "bar", (void*)test);
247  *
248  * printf("foo: %d, bar %s",
249  *     *((int *)util_htget(foo, "foo")),
250  *      ((char*)util_htget(foo, "bar"))
251  * );
252  *
253  * util_htdel(foo);
254  */
255 hash_table_t *util_htnew (size_t size);
256 void          util_htset (hash_table_t *ht, const char *key, void *value);
257 void         *util_htget (hash_table_t *ht, const char *key);
258 void          util_htdel (hash_table_t *ht);
259 size_t        util_hthash(hash_table_t *ht, const char *key);
260 void         *util_htgeth(hash_table_t *ht, const char *key, size_t hash);
261 void          util_htseth(hash_table_t *ht, const char *key, size_t hash, void *value);
262 /*===================================================================*/
263 /*=========================== code.c ================================*/
264 /*===================================================================*/
265
266 /* Note: if you change the order, fix type_sizeof in ir.c */
267 enum {
268     TYPE_VOID     ,
269     TYPE_STRING   ,
270     TYPE_FLOAT    ,
271     TYPE_VECTOR   ,
272     TYPE_ENTITY   ,
273     TYPE_FIELD    ,
274     TYPE_FUNCTION ,
275     TYPE_POINTER  ,
276     TYPE_INTEGER  ,
277     TYPE_VARIANT  ,
278     TYPE_STRUCT   ,
279     TYPE_UNION    ,
280     TYPE_ARRAY    ,
281
282     TYPE_COUNT
283 };
284
285 /* const/var qualifiers */
286 #define CV_NONE  0
287 #define CV_CONST 1
288 #define CV_VAR  -1
289 /* magic number to help parsing */
290 #define CV_WRONG  0x8000
291
292 extern const char *type_name        [TYPE_COUNT];
293 extern size_t      type_sizeof      [TYPE_COUNT];
294 extern uint16_t    type_store_instr [TYPE_COUNT];
295 extern uint16_t    field_store_instr[TYPE_COUNT];
296
297 /*
298  * could use type_store_instr + INSTR_STOREP_F - INSTR_STORE_F
299  * but this breaks when TYPE_INTEGER is added, since with the enhanced
300  * instruction set, the old ones are left untouched, thus the _I instructions
301  * are at a seperate place.
302  */
303 extern uint16_t type_storep_instr[TYPE_COUNT];
304 extern uint16_t type_eq_instr    [TYPE_COUNT];
305 extern uint16_t type_ne_instr    [TYPE_COUNT];
306 extern uint16_t type_not_instr   [TYPE_COUNT];
307
308 typedef struct {
309     uint32_t offset;      /* Offset in file of where data begins  */
310     uint32_t length;      /* Length of section (how many of)      */
311 } prog_section;
312
313 typedef struct {
314     uint32_t     version;      /* Program version (6)     */
315     uint16_t     crc16;
316     uint16_t     skip;
317
318     prog_section statements;   /* prog_section_statement  */
319     prog_section defs;         /* prog_section_def        */
320     prog_section fields;       /* prog_section_field      */
321     prog_section functions;    /* prog_section_function   */
322     prog_section strings;
323     prog_section globals;
324     uint32_t     entfield;     /* Number of entity fields */
325 } prog_header;
326
327 /*
328  * Each paramater incerements by 3 since vector types hold
329  * 3 components (x,y,z).
330  */
331 #define OFS_NULL      0
332 #define OFS_RETURN    1
333 #define OFS_PARM0     (OFS_RETURN+3)
334 #define OFS_PARM1     (OFS_PARM0 +3)
335 #define OFS_PARM2     (OFS_PARM1 +3)
336 #define OFS_PARM3     (OFS_PARM2 +3)
337 #define OFS_PARM4     (OFS_PARM3 +3)
338 #define OFS_PARM5     (OFS_PARM4 +3)
339 #define OFS_PARM6     (OFS_PARM5 +3)
340 #define OFS_PARM7     (OFS_PARM6 +3)
341
342 typedef struct {
343     uint16_t opcode;
344
345     /* operand 1 */
346     union {
347         int16_t  s1; /* signed   */
348         uint16_t u1; /* unsigned */
349     } o1;
350     /* operand 2 */
351     union {
352         int16_t  s1; /* signed   */
353         uint16_t u1; /* unsigned */
354     } o2;
355     /* operand 3 */
356     union {
357         int16_t  s1; /* signed   */
358         uint16_t u1; /* unsigned */
359     } o3;
360
361     /*
362      * This is the same as the structure in darkplaces
363      * {
364      *     unsigned short op;
365      *     short          a,b,c;
366      * }
367      * But this one is more sane to work with, and the
368      * type sizes are guranteed.
369      */
370 } prog_section_statement;
371
372 typedef struct {
373     /*
374      * The types:
375      * 0 = ev_void
376      * 1 = ev_string
377      * 2 = ev_float
378      * 3 = ev_vector
379      * 4 = ev_entity
380      * 5 = ev_field
381      * 6 = ev_function
382      * 7 = ev_pointer -- engine only
383      * 8 = ev_bad     -- engine only
384      */
385     uint16_t type;
386     uint16_t offset;
387     uint32_t name;
388 } prog_section_both;
389
390 typedef prog_section_both prog_section_def;
391 typedef prog_section_both prog_section_field;
392
393 /* this is ORed to the type */
394 #define DEF_SAVEGLOBAL (1<<15)
395 #define DEF_TYPEMASK   ((1<<15)-1)
396
397 typedef struct {
398     int32_t   entry;      /* in statement table for instructions  */
399     uint32_t  firstlocal; /* First local in local table           */
400     uint32_t  locals;     /* Total ints of params + locals        */
401     uint32_t  profile;    /* Always zero (engine uses this)       */
402     uint32_t  name;       /* name of function in string table     */
403     uint32_t  file;       /* file of the source file              */
404     int32_t   nargs;      /* number of arguments                  */
405     uint8_t   argsize[8]; /* size of arguments (keep 8 always?)   */
406 } prog_section_function;
407
408 /*
409  * Instructions
410  * These are the external instructions supported by the interperter
411  * this is what things compile to (from the C code).
412  */
413 enum {
414     INSTR_DONE,
415     INSTR_MUL_F,
416     INSTR_MUL_V,
417     INSTR_MUL_FV, /* NOTE: the float operands must NOT be at the same locations: A != C */
418     INSTR_MUL_VF, /* and here: B != C */
419     INSTR_DIV_F,
420     INSTR_ADD_F,
421     INSTR_ADD_V,
422     INSTR_SUB_F,
423     INSTR_SUB_V,
424     INSTR_EQ_F,
425     INSTR_EQ_V,
426     INSTR_EQ_S,
427     INSTR_EQ_E,
428     INSTR_EQ_FNC,
429     INSTR_NE_F,
430     INSTR_NE_V,
431     INSTR_NE_S,
432     INSTR_NE_E,
433     INSTR_NE_FNC,
434     INSTR_LE,
435     INSTR_GE,
436     INSTR_LT,
437     INSTR_GT,
438     INSTR_LOAD_F,
439     INSTR_LOAD_V,
440     INSTR_LOAD_S,
441     INSTR_LOAD_ENT,
442     INSTR_LOAD_FLD,
443     INSTR_LOAD_FNC,
444     INSTR_ADDRESS,
445     INSTR_STORE_F,
446     INSTR_STORE_V,
447     INSTR_STORE_S,
448     INSTR_STORE_ENT,
449     INSTR_STORE_FLD,
450     INSTR_STORE_FNC,
451     INSTR_STOREP_F,
452     INSTR_STOREP_V,
453     INSTR_STOREP_S,
454     INSTR_STOREP_ENT,
455     INSTR_STOREP_FLD,
456     INSTR_STOREP_FNC,
457     INSTR_RETURN,
458     INSTR_NOT_F,
459     INSTR_NOT_V,
460     INSTR_NOT_S,
461     INSTR_NOT_ENT,
462     INSTR_NOT_FNC,
463     INSTR_IF,
464     INSTR_IFNOT,
465     INSTR_CALL0,
466     INSTR_CALL1,
467     INSTR_CALL2,
468     INSTR_CALL3,
469     INSTR_CALL4,
470     INSTR_CALL5,
471     INSTR_CALL6,
472     INSTR_CALL7,
473     INSTR_CALL8,
474     INSTR_STATE,
475     INSTR_GOTO,
476     INSTR_AND,
477     INSTR_OR,
478     INSTR_BITAND,
479     INSTR_BITOR,
480
481     /*
482      * Virtual instructions used by the assembler
483      * keep at the end but before virtual instructions
484      * for the IR below.
485      */
486     AINSTR_END,
487
488     /*
489      * Virtual instructions used by the IR
490      * Keep at the end!
491      */
492     VINSTR_PHI,
493     VINSTR_JUMP,
494     VINSTR_COND,
495     /* A never returning CALL.
496      * Creating this causes IR blocks to be marked as 'final'.
497      * No-Return-Call
498      */
499     VINSTR_NRCALL
500 };
501
502 extern prog_section_statement *code_statements;
503 extern int                    *code_linenums;
504 extern prog_section_def       *code_defs;
505 extern prog_section_field     *code_fields;
506 extern prog_section_function  *code_functions;
507 extern int                    *code_globals;
508 extern char                   *code_chars;
509 extern uint16_t code_crc;
510
511 typedef float   qcfloat;
512 typedef int32_t qcint;
513
514 /*
515  * code_write -- writes out the compiled file
516  * code_init  -- prepares the code file
517  */
518 bool     code_write       (const char *filename, const char *lno);
519 void     code_init        ();
520 uint32_t code_genstring   (const char *string);
521 uint32_t code_cachedstring(const char *string);
522 qcint    code_alloc_field (size_t qcsize);
523
524 /* this function is used to keep statements and linenumbers together */
525 void     code_push_statement(prog_section_statement *stmt, int linenum);
526 void     code_pop_statement();
527
528 /*
529  * A shallow copy of a lex_file to remember where which ast node
530  * came from.
531  */
532 typedef struct {
533     const char *file;
534     size_t      line;
535 } lex_ctx;
536
537 /*===================================================================*/
538 /*============================ con.c ================================*/
539 /*===================================================================*/
540 enum {
541     CON_BLACK   = 30,
542     CON_RED,
543     CON_GREEN,
544     CON_BROWN,
545     CON_BLUE,
546     CON_MAGENTA,
547     CON_CYAN ,
548     CON_WHITE
549 };
550
551 /* message level */
552 enum {
553     LVL_MSG,
554     LVL_WARNING,
555     LVL_ERROR
556 };
557
558 void con_vprintmsg (int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap);
559 void con_printmsg  (int level, const char *name, size_t line, const char *msgtype, const char *msg, ...);
560 void con_cvprintmsg(void *ctx, int lvl, const char *msgtype, const char *msg, va_list ap);
561 void con_cprintmsg (void *ctx, int lvl, const char *msgtype, const char *msg, ...);
562
563 void con_close ();
564 void con_init  ();
565 void con_reset ();
566 void con_color (int);
567 int  con_change(const char *, const char *);
568 int  con_verr  (const char *, va_list);
569 int  con_vout  (const char *, va_list);
570 int  con_err   (const char *, ...);
571 int  con_out   (const char *, ...);
572
573 /* error/warning interface */
574 extern size_t compile_errors;
575 extern size_t compile_warnings;
576
577 void /********/ compile_error   (lex_ctx ctx, /*LVL_ERROR*/ const char *msg, ...);
578 void /********/ vcompile_error  (lex_ctx ctx, /*LVL_ERROR*/ const char *msg, va_list ap);
579 bool GMQCC_WARN compile_warning (lex_ctx ctx, int warntype, const char *fmt, ...);
580 bool GMQCC_WARN vcompile_warning(lex_ctx ctx, int warntype, const char *fmt, va_list ap);
581
582 /*===================================================================*/
583 /*========================= assembler.c =============================*/
584 /*===================================================================*/
585 static const struct {
586     const char  *m; /* menomic     */
587     const size_t o; /* operands    */
588     const size_t l; /* menomic len */
589 } asm_instr[] = {
590     { "DONE"      , 1, 4 },
591     { "MUL_F"     , 3, 5 },
592     { "MUL_V"     , 3, 5 },
593     { "MUL_FV"    , 3, 6 },
594     { "MUL_VF"    , 3, 6 },
595     { "DIV"       , 0, 3 },
596     { "ADD_F"     , 3, 5 },
597     { "ADD_V"     , 3, 5 },
598     { "SUB_F"     , 3, 5 },
599     { "SUB_V"     , 3, 5 },
600     { "EQ_F"      , 0, 4 },
601     { "EQ_V"      , 0, 4 },
602     { "EQ_S"      , 0, 4 },
603     { "EQ_E"      , 0, 4 },
604     { "EQ_FNC"    , 0, 6 },
605     { "NE_F"      , 0, 4 },
606     { "NE_V"      , 0, 4 },
607     { "NE_S"      , 0, 4 },
608     { "NE_E"      , 0, 4 },
609     { "NE_FNC"    , 0, 6 },
610     { "LE"        , 0, 2 },
611     { "GE"        , 0, 2 },
612     { "LT"        , 0, 2 },
613     { "GT"        , 0, 2 },
614     { "FIELD_F"   , 0, 7 },
615     { "FIELD_V"   , 0, 7 },
616     { "FIELD_S"   , 0, 7 },
617     { "FIELD_ENT" , 0, 9 },
618     { "FIELD_FLD" , 0, 9 },
619     { "FIELD_FNC" , 0, 9 },
620     { "ADDRESS"   , 0, 7 },
621     { "STORE_F"   , 0, 7 },
622     { "STORE_V"   , 0, 7 },
623     { "STORE_S"   , 0, 7 },
624     { "STORE_ENT" , 0, 9 },
625     { "STORE_FLD" , 0, 9 },
626     { "STORE_FNC" , 0, 9 },
627     { "STOREP_F"  , 0, 8 },
628     { "STOREP_V"  , 0, 8 },
629     { "STOREP_S"  , 0, 8 },
630     { "STOREP_ENT", 0, 10},
631     { "STOREP_FLD", 0, 10},
632     { "STOREP_FNC", 0, 10},
633     { "RETURN"    , 0, 6 },
634     { "NOT_F"     , 0, 5 },
635     { "NOT_V"     , 0, 5 },
636     { "NOT_S"     , 0, 5 },
637     { "NOT_ENT"   , 0, 7 },
638     { "NOT_FNC"   , 0, 7 },
639     { "IF"        , 0, 2 },
640     { "IFNOT"     , 0, 5 },
641     { "CALL0"     , 1, 5 },
642     { "CALL1"     , 2, 5 },
643     { "CALL2"     , 3, 5 },
644     { "CALL3"     , 4, 5 },
645     { "CALL4"     , 5, 5 },
646     { "CALL5"     , 6, 5 },
647     { "CALL6"     , 7, 5 },
648     { "CALL7"     , 8, 5 },
649     { "CALL8"     , 9, 5 },
650     { "STATE"     , 0, 5 },
651     { "GOTO"      , 0, 4 },
652     { "AND"       , 0, 3 },
653     { "OR"        , 0, 2 },
654     { "BITAND"    , 0, 6 },
655     { "BITOR"     , 0, 5 },
656
657     { "END"       , 0, 3 } /* virtual assembler instruction */
658 };
659 /*===================================================================*/
660 /*============================= ir.c ================================*/
661 /*===================================================================*/
662
663 enum store_types {
664     store_global,
665     store_local,  /* local, assignable for now, should get promoted later */
666     store_param,  /* parameters, they are locals with a fixed position */
667     store_value,  /* unassignable */
668     store_return  /* unassignable, at OFS_RETURN */
669 };
670
671 typedef struct {
672     qcfloat x, y, z;
673 } vector;
674
675 vector  vec3_add  (vector, vector);
676 vector  vec3_sub  (vector, vector);
677 qcfloat vec3_mulvv(vector, vector);
678 vector  vec3_mulvf(vector, float);
679
680 /*===================================================================*/
681 /*============================= exec.c ==============================*/
682 /*===================================================================*/
683
684 /*
685  * Darkplaces has (or will have) a 64 bit prog loader
686  * where the 32 bit qc program is autoconverted on load.
687  * Since we may want to support that as well, let's redefine
688  * float and int here.
689  */
690 typedef union {
691     qcint   _int;
692     qcint    string;
693     qcint    function;
694     qcint    edict;
695     qcfloat _float;
696     qcfloat vector[3];
697     qcint   ivector[3];
698 } qcany;
699
700 typedef char qcfloat_size_is_correct [sizeof(qcfloat) == 4 ?1:-1];
701 typedef char qcint_size_is_correct   [sizeof(qcint)   == 4 ?1:-1];
702
703 enum {
704     VMERR_OK,
705     VMERR_TEMPSTRING_ALLOC,
706
707     VMERR_END
708 };
709
710 #define VM_JUMPS_DEFAULT 1000000
711
712 /* execute-flags */
713 #define VMXF_DEFAULT 0x0000     /* default flags - nothing */
714 #define VMXF_TRACE   0x0001     /* trace: print statements before executing */
715 #define VMXF_PROFILE 0x0002     /* profile: increment the profile counters */
716
717 struct qc_program_s;
718
719 typedef int (*prog_builtin)(struct qc_program_s *prog);
720
721 typedef struct {
722     qcint                  stmt;
723     size_t                 localsp;
724     prog_section_function *function;
725 } qc_exec_stack;
726
727 typedef struct qc_program_s {
728     char           *filename;
729
730     prog_section_statement *code;
731     prog_section_def       *defs;
732     prog_section_def       *fields;
733     prog_section_function  *functions;
734     char                   *strings;
735     qcint                  *globals;
736     qcint                  *entitydata;
737     bool                   *entitypool;
738
739     const char*            *function_stack;
740
741     uint16_t crc16;
742
743     size_t tempstring_start;
744     size_t tempstring_at;
745
746     qcint  vmerror;
747
748     size_t *profile;
749
750     prog_builtin *builtins;
751     size_t        builtins_count;
752
753     /* size_t ip; */
754     qcint  entities;
755     size_t entityfields;
756     bool   allowworldwrites;
757
758     qcint         *localstack;
759     qc_exec_stack *stack;
760     size_t statement;
761
762     size_t xflags;
763
764     int    argc; /* current arg count for debugging */
765 } qc_program;
766
767 qc_program* prog_load(const char *filename);
768 void        prog_delete(qc_program *prog);
769
770 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps);
771
772 char*             prog_getstring (qc_program *prog, qcint str);
773 prog_section_def* prog_entfield  (qc_program *prog, qcint off);
774 prog_section_def* prog_getdef    (qc_program *prog, qcint off);
775 qcany*            prog_getedict  (qc_program *prog, qcint e);
776 qcint             prog_tempstring(qc_program *prog, const char *_str);
777
778
779 /*===================================================================*/
780 /*===================== parser.c commandline ========================*/
781 /*===================================================================*/
782
783 bool parser_init          ();
784 bool parser_compile_file  (const char *filename);
785 bool parser_compile_string(const char *name, const char *str);
786 bool parser_finish        (const char *output);
787 void parser_cleanup       ();
788 /* There's really no need to strlen() preprocessed files */
789 bool parser_compile_string_len(const char *name, const char *str, size_t len);
790
791 /*===================================================================*/
792 /*====================== ftepp.c commandline ========================*/
793 /*===================================================================*/
794 bool ftepp_init             ();
795 bool ftepp_preprocess_file  (const char *filename);
796 bool ftepp_preprocess_string(const char *name, const char *str);
797 void ftepp_finish           ();
798 const char *ftepp_get       ();
799 void ftepp_flush            ();
800 void ftepp_add_define       (const char *source, const char *name);
801 void ftepp_add_macro        (const char *name,   const char *value);
802
803 /*===================================================================*/
804 /*======================= main.c commandline ========================*/
805 /*===================================================================*/
806
807 #if 0
808 /* Helpers to allow for a whole lot of flags. Otherwise we'd limit
809  * to 32 or 64 -f options...
810  */
811 typedef struct {
812     size_t  idx; /* index into an array of 32 bit words */
813     uint8_t bit; /* index _into_ the 32 bit word, thus just uint8 */
814 } longbit;
815 #define LONGBIT(bit) { ((bit)/32), ((bit)%32) }
816 #else
817 typedef uint32_t longbit;
818 #define LONGBIT(bit) (bit)
819 #endif
820
821 /*===================================================================*/
822 /*============================= opts.c ==============================*/
823 /*===================================================================*/
824 typedef struct {
825     const char *name;
826     longbit     bit;
827 } opts_flag_def;
828
829 bool opts_setflag (const char *, bool);
830 bool opts_setwarn (const char *, bool);
831 bool opts_setoptim(const char *, bool);
832
833 void opts_init         (const char *, int, size_t);
834 void opts_set          (uint32_t   *, size_t, bool);
835 void opts_setoptimlevel(unsigned int);
836 void opts_ini_init     (const char *);
837
838 enum {
839 # define GMQCC_TYPE_FLAGS
840 # define GMQCC_DEFINE_FLAG(X) X,
841 #  include "opts.def"
842     COUNT_FLAGS
843 };
844 static const opts_flag_def opts_flag_list[] = {
845 # define GMQCC_TYPE_FLAGS
846 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(X) },
847 #  include "opts.def"
848     { NULL, LONGBIT(0) }
849 };
850
851 enum {
852 # define GMQCC_TYPE_WARNS
853 # define GMQCC_DEFINE_FLAG(X) WARN_##X,
854 #  include "opts.def"
855     COUNT_WARNINGS
856 };
857 static const opts_flag_def opts_warn_list[] = {
858 # define GMQCC_TYPE_WARNS
859 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(WARN_##X) },
860 #  include "opts.def"
861     { NULL, LONGBIT(0) }
862 };
863
864 enum {
865 # define GMQCC_TYPE_OPTIMIZATIONS
866 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) OPTIM_##NAME,
867 #  include "opts.def"
868     COUNT_OPTIMIZATIONS
869 };
870 static const opts_flag_def opts_opt_list[] = {
871 # define GMQCC_TYPE_OPTIMIZATIONS
872 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) { #NAME, LONGBIT(OPTIM_##NAME) },
873 #  include "opts.def"
874     { NULL, LONGBIT(0) }
875 };
876 static const unsigned int opts_opt_oflag[] = {
877 # define GMQCC_TYPE_OPTIMIZATIONS
878 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) MIN_O,
879 #  include "opts.def"
880     0
881 };
882 extern unsigned int opts_optimizationcount[COUNT_OPTIMIZATIONS];
883
884 /* other options: */
885 typedef enum {
886     COMPILER_QCC,     /* circa  QuakeC */
887     COMPILER_FTEQCC,  /* fteqcc QuakeC */
888     COMPILER_QCCX,    /* qccx   QuakeC */
889     COMPILER_GMQCC    /* this   QuakeC */
890 } opts_std_t;
891
892 typedef struct {
893     uint32_t    O;              /* -Ox           */
894     const char *output;         /* -o file       */
895     bool        g;              /* -g            */
896     opts_std_t  standard;       /* -std=         */
897     bool        debug;          /* -debug        */
898     bool        memchk;         /* -memchk       */
899     bool        dumpfin;        /* -dumpfin      */
900     bool        dump;           /* -dump         */
901     bool        werror;         /* -Werror       */
902     bool        forcecrc;       /* --force-crc=  */
903     uint16_t    forced_crc;     /* --force-crc=  */
904     bool        pp_only;        /* -E            */
905     size_t      max_array_size; /* --max-array=  */
906
907     uint32_t flags       [1 + (COUNT_FLAGS         / 32)];
908     uint32_t warn        [1 + (COUNT_WARNINGS      / 32)];
909     uint32_t optimization[1 + (COUNT_OPTIMIZATIONS / 32)];
910 } opts_cmd_t;
911
912 extern opts_cmd_t opts;
913
914 /*===================================================================*/
915 #define OPTS_FLAG(i)         (!! (opts.flags       [(i)/32] & (1<< ((i)%32))))
916 #define OPTS_WARN(i)         (!! (opts.warn        [(i)/32] & (1<< ((i)%32))))
917 #define OPTS_OPTIMIZATION(i) (!! (opts.optimization[(i)/32] & (1<< ((i)%32))))
918
919 #endif