]> git.xonotic.org Git - xonotic/gmqcc.git/blob - gmqcc.h
Remove license headers. The LICENSE file is sufficent
[xonotic/gmqcc.git] / gmqcc.h
1 #ifndef GMQCC_HDR
2 #define GMQCC_HDR
3 #include <stdarg.h>
4 #include <stddef.h>
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <time.h>
8
9 #define GMQCC_VERSION_MAJOR 0
10 #define GMQCC_VERSION_MINOR 3
11 #define GMQCC_VERSION_PATCH 6
12 #define GMQCC_VERSION ((GMQCC_VERSION_MAJOR<<16)|(GMQCC_VERSION_MINOR<<8)|GMQCC_VERSION_PATCH)
13
14 #ifdef GMQCC_VERSION_TYPE_RELEASE
15 #    ifdef GMQCC_GITINFO
16 #        define GMQCC_DEV_VERSION_STRING "git build: " GMQCC_GITINFO "\n"
17 #    elif defined(GMQCC_VERSION_TYPE_DEVEL)
18 #        define GMQCC_DEV_VERSION_STRING "development build\n"
19 #    else
20 #        define GMQCC_DEV_VERSION_STRING
21 #    endif /*! GMQCC_GITINGO */
22 #else
23 #    define GMQCC_DEV_VERSION_STRING
24 #endif
25
26 #define GMQCC_STRINGIFY(x) #x
27 #define GMQCC_IND_STRING(x) GMQCC_STRINGIFY(x)
28 #define GMQCC_FULL_VERSION_STRING \
29 "GMQCC " \
30 GMQCC_IND_STRING(GMQCC_VERSION_MAJOR) "." \
31 GMQCC_IND_STRING(GMQCC_VERSION_MINOR) "." \
32 GMQCC_IND_STRING(GMQCC_VERSION_PATCH) \
33 " Built " __DATE__ " " __TIME__ \
34 "\n" GMQCC_DEV_VERSION_STRING
35
36 #ifndef __cplusplus
37 #   define false (unsigned char)(0)
38 #   define true  (unsigned char)(1)
39     typedef unsigned char bool;
40 #endif
41
42 #if defined(__GNUC__) || defined(__CLANG__)
43 #   include <stdint.h>
44 #   if (__GNUC__ >= 2) || defined(__CLANG__)
45 #       define GMQCC_NORETURN    __attribute__((noreturn))
46 #       define GMQCC_FORCEINLINE __attribute__((always_inline))
47 #       define GMQCC_INLINE      __inline
48 #   endif
49 #   define GMQCC_LIKELY(X)   __builtin_expect((X), 1)
50 #   define GMQCC_UNLIKELY(X) __builtin_expect((X), 0)
51 #   define GMQCC_WARN        __attribute__((warn_unused_result))
52 #   define GMQCC_USED        __attribute__((used))
53 #   define GMQCC_RESTRICT    __restrict__
54 #else
55 #   ifdef _MSC_VER
56         /* conversion from 'int' to 'float', possible loss of data */
57 #       pragma warning(disable : 4244)
58
59         typedef unsigned __int8  uint8_t;
60         typedef unsigned __int16 uint16_t;
61         typedef unsigned __int32 uint32_t;
62         typedef unsigned __int64 uint64_t;
63         typedef __int16          int16_t;
64         typedef __int32          int32_t;
65         typedef __int64          int64_t;
66 #       define GMQCC_NORETURN    __declspec(noreturn)
67 #       define GMQCC_FORCEINLINE __forceinline
68 #       define GMQCC_INLINE      __inline
69 #       define GMQCC_RESTRICT    __restrict
70 #   else
71 #       define GMQCC_NORETURN
72 #       define GMQCC_FORCEINLINE
73 #       define GMQCC_INLINE
74 #       define GMQCC_RESTRICT
75 #   endif
76 #   define GMQCC_LIKELY(X)   (X)
77 #   define GMQCC_UNLIKELY(X) (X)
78 #   define GMQCC_WARN
79 #   define GMQCC_USED
80 #endif
81
82 #define GMQCC_BYTE_ORDER_LITTLE 1234
83 #define GMQCC_BYTE_ORDER_BIG    4321
84
85 #if defined (__GNUC__) || defined (__GNU_LIBRARY__)
86 #   if defined (__FreeBSD__) || defined (__OpenBSD__)
87 #       include <sys/endian.h>
88 #   elif defined (BSD) && (BSD >= 199103) || defined (__DJGPP__) || defined (__CYGWIN32__)
89 #       include <machine/endian.h>
90 #   elif defined (__APPLE__)
91 #       if defined (__BIG_ENDIAN__) && !defined(BIG_ENDIAN)
92 #           define BIG_ENDIAN
93 #       elif defined (__LITTLE_ENDIAN__) && !defined (LITTLE_ENDIAN)
94 #           define LITTLE_ENDIAN
95 #       endif /*! defined (__BIG_ENDIAN__) && !defined(BIG_ENDIAN) */
96 #   elif !defined (__MINGW32__)
97 #       include <endian.h>
98 #       if !defined (__BEOS__)
99 #           include <byteswap.h>
100 #       endif /*! !definde (__BEOS__) */
101 #   endif /*! defined (__FreeBSD__) || defined (__OpenBSD__) */
102 #endif /*! defined (__GNUC__) || defined (__GNU_LIBRARY__) */
103 #if !defined(PLATFORM_BYTE_ORDER)
104 #   if defined (LITTLE_ENDIAN) || defined (BIG_ENDIAN)
105 #       if defined (LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
106 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
107 #       elif !defined (LITTLE_ENDIAN) && defined (BIG_ENDIAN)
108 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
109 #       elif defined (BYTE_ORDER) && (BYTE_ORDER == LITTLE_ENDIAN)
110 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
111 #       elif defined (BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
112 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
113 #       endif /*! defined (LITTLE_ENDIAN) && !defined(BIG_ENDIAN) */
114 #   elif defined (_LITTLE_ENDIAN) || defined (_BIG_ENDIAN)
115 #       if defined (_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
116 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
117 #       elif !defined (_LITTLE_ENDIAN) && defined (_BIG_ENDIAN)
118 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
119 #       elif defined (_BYTE_ORDER) && (_BYTE_ORDER == _LITTLE_ENDIAN)
120 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
121 #       elif defined (_BYTE_ORDER) && (_BYTE_ORDER == _BIG_ENDIAN)
122 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
123 #       endif /*! defined (_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN) */
124 #   elif defined (__LITTLE_ENDIAN__) || defined (__BIG_ENDIAN__)
125 #       if defined (__LITTLE_ENDIAN__) && !defined (__BIG_ENDIAN__)
126 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
127 #       elif !defined (__LITTLE_ENDIAN__) && defined (__BIG_ENDIAN__)
128 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
129 #       elif defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __LITTLE_ENDIAN__)
130 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
131 #       elif defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __BIG_ENDIAN__)
132 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
133 #       endif /*! defined (__LITTLE_ENDIAN__) && !defined (__BIG_ENDIAN__) */
134 #   endif /*! defined(LITTLE_ENDIAN) || defined (BIG_ENDIAN) */
135 #endif /*! !defined(PLATFORM_BYTE_ORDER) */
136 #if !defined (PLATFORM_BYTE_ORDER)
137 #   if   defined (__alpha__) || defined (__alpha)    || defined (i386)       || \
138          defined (__i386__)  || defined (_M_I86)     || defined (_M_IX86)    || \
139          defined (__OS2__)   || defined (sun386)     || defined (__TURBOC__) || \
140          defined (vax)       || defined (vms)        || defined (VMS)        || \
141          defined (__VMS)     || defined (__x86_64__) || defined (_M_IA64)    || \
142          defined (_M_X64)    || defined (__i386)     || defined (__x86_64)
143 #       define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
144 #   elif defined (AMIGA)     || defined (applec)     || defined (__AS400__)  || \
145          defined (_CRAY)     || defined (__hppa)     || defined (__hp9000)   || \
146          defined (ibm370)    || defined (mc68000)    || defined (m68k)       || \
147          defined (__MRC__)   || defined (__MVS__)    || defined (__MWERKS__) || \
148          defined (sparc)     || defined (__sparc)    || defined (SYMANTEC_C) || \
149          defined (__TANDEM)  || defined (THINK_C)    || defined (__VMCMS__)  || \
150          defined (__PPC__)   || defined (__PPC)      || defined (PPC)
151 #       define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
152 #   else
153 #       define PLATFORM_BYTE_ORDER -1
154 #   endif
155 #endif
156
157 #define GMQCC_ARRAY_COUNT(X) (sizeof(X) / sizeof((X)[0]))
158
159 /* stat.c */
160 char *stat_mem_strdup(const char *, bool);
161
162 #define mem_a(SIZE)              malloc(SIZE)
163 #define mem_d(PTRN)              free((void*)PTRN)
164 #define mem_r(PTRN, SIZE)        realloc((void*)PTRN, SIZE)
165
166 /* TODO: rename to mem variations */
167 #define util_strdup(SRC)         stat_mem_strdup((char*)(SRC), false)
168 #define util_strdupe(SRC)        stat_mem_strdup((char*)(SRC), true)
169
170 /* util.c */
171
172 /*
173  * Microsoft implements against the spec versions of ctype.h. Which
174  * means what ever the current set locale is will render the actual
175  * results of say isalpha('A') wrong for what ever retarded locale
176  * is used. Simalerly these are also implemented inefficently on
177  * some toolchains and end up becoming actual library calls. Perhaps
178  * this is why tools like yacc provide their own? Regardless implementing
179  * these as functions is equally as silly, the call overhead is not
180  * justified when this could happen on every character from an input
181  * stream. We provide our own as macros for absolute inlinability.
182  */
183 #define util_isalpha(a) ((((unsigned)(a)|32)-'a') < 26)
184 #define util_isdigit(a) (((unsigned)(a)-'0') < 10)
185 #define util_islower(a) (((unsigned)(a)-'a') < 26)
186 #define util_isupper(a) (((unsigned)(a)-'A') < 26)
187 #define util_isprint(a) (((unsigned)(a)-0x20) < 0x5F)
188 #define util_isspace(a) (((a) >= 9 && (a) <= 13) || (a) == ' ')
189
190 bool  util_strupper(const char *);
191 bool  util_strdigit(const char *);
192
193 void  util_endianswap(void *, size_t, unsigned int);
194
195 size_t util_strtocmd         (const char *, char *, size_t);
196 size_t util_strtononcmd      (const char *, char *, size_t);
197 size_t util_optimizationtostr(const char *, char *, size_t);
198
199 uint16_t util_crc16(uint16_t crc, const char *data, size_t len);
200
201 void     util_seed(uint32_t);
202 uint32_t util_rand(void);
203
204 int      util_asprintf (char **ret, const char *fmt, ...);
205 int      util_sscanf   (const char *str, const char *format, ...);
206 char    *util_strncpy  (char *dest, const char *src, size_t n);
207 char    *util_strncat  (char *dest, const char *src, size_t n);
208 char    *util_strcat   (char *dest, const char *src);
209 const char *util_strerror(int err);
210
211 const struct tm *util_localtime(const time_t *timer);
212 const char      *util_ctime    (const time_t *timer);
213
214 bool             util_isatty(FILE *);
215 size_t           hash(const char *key);
216
217 /*
218  * A flexible vector implementation: all vector pointers contain some
219  * data about themselfs exactly - sizeof(vector_t) behind the pointer
220  * this data is represented in the structure below.  Doing this allows
221  * us to use the array [] to access individual elements from the vector
222  * opposed to using set/get methods.
223  */
224 typedef struct {
225     size_t  allocated;
226     size_t  used;
227
228     /* can be extended now! whoot */
229 } vector_t;
230
231 /* hidden interface */
232 void _util_vec_grow(void **a, size_t i, size_t s);
233 void _util_vec_delete(void *vec);
234
235 #define GMQCC_VEC_WILLGROW(X, Y) ( \
236     ((!(X) || vec_meta(X)->used + Y >= vec_meta(X)->allocated)) ? \
237         (void)_util_vec_grow(((void**)&(X)), (Y), sizeof(*(X))) : \
238         (void)0                                                   \
239 )
240
241 /* exposed interface */
242 #define vec_meta(A)       ((vector_t*)(((char *)(A)) - sizeof(vector_t)))
243 #define vec_free(A)       ((void)((A) ? (_util_vec_delete((void *)(A)), (A) = NULL) : 0))
244 #define vec_push(A,V)     (GMQCC_VEC_WILLGROW((A),1), (A)[vec_meta(A)->used++] = (V))
245 #define vec_size(A)       ((A) ? vec_meta(A)->used : 0)
246 #define vec_add(A,N)      (GMQCC_VEC_WILLGROW((A),(N)), vec_meta(A)->used += (N), &(A)[vec_meta(A)->used-(N)])
247 #define vec_last(A)       ((A)[vec_meta(A)->used - 1])
248 #define vec_pop(A)        ((void)(vec_meta(A)->used -= 1))
249 #define vec_shrinkto(A,N) ((void)(vec_meta(A)->used  = (N)))
250 #define vec_shrinkby(A,N) ((void)(vec_meta(A)->used -= (N)))
251 #define vec_append(A,N,S) ((void)(memcpy(vec_add((A), (N)), (S), (N) * sizeof(*(S)))))
252 #define vec_remove(A,I,N) ((void)(memmove((A)+(I),(A)+((I)+(N)),sizeof(*(A))*(vec_meta(A)->used-(I)-(N))),vec_meta(A)->used-=(N)))
253
254 typedef struct hash_table_s {
255     size_t                size;
256     struct hash_node_t **table;
257 } hash_table_t, *ht;
258
259 /*
260  * hashtable implementation:
261  *
262  * Note:
263  *      This was designed for pointers:  you manage the life of the object yourself
264  *      if you do use this for non-pointers please be warned that the object may not
265  *      be valid if the duration of it exceeds (i.e on stack).  So you need to allocate
266  *      yourself, or put those in global scope to ensure duration is for the whole
267  *      runtime.
268  *
269  * util_htnew(size)                             -- to make a new hashtable
270  * util_htset(table, key, value, sizeof(value)) -- to set something in the table
271  * util_htget(table, key)                       -- to get something from the table
272  * util_htdel(table)                            -- to delete the table
273  *
274  * example of use:
275  *
276  * ht    foo  = util_htnew(1024);
277  * int   data = 100;
278  * char *test = "hello world\n";
279  * util_htset(foo, "foo", (void*)&data);
280  * util_gtset(foo, "bar", (void*)test);
281  *
282  * printf("foo: %d, bar %s",
283  *     *((int *)util_htget(foo, "foo")),
284  *      ((char*)util_htget(foo, "bar"))
285  * );
286  *
287  * util_htdel(foo);
288  */
289 hash_table_t *util_htnew (size_t size);
290 void util_htrem(hash_table_t *ht, void (*callback)(void *data));
291 void util_htset(hash_table_t *ht, const char *key, void *value);
292 void util_htdel(hash_table_t *ht);
293 size_t util_hthash(hash_table_t *ht, const char *key);
294 void util_htseth(hash_table_t *ht, const char *key, size_t hash, void *value);
295 void util_htrmh(hash_table_t *ht, const char *key, size_t bin, void (*cb)(void*));
296 void util_htrm(hash_table_t *ht, const char *key, void (*cb)(void*));
297 void *util_htget(hash_table_t *ht, const char *key);
298 void *util_htgeth(hash_table_t *ht, const char *key, size_t hash);
299 int util_snprintf(char *str, size_t, const char *fmt, ...);
300 int util_getline(char  **, size_t *, FILE *);
301
302 /* code.c */
303
304 /* Note: if you change the order, fix type_sizeof in ir.c */
305 enum {
306     TYPE_VOID     ,
307     TYPE_STRING   ,
308     TYPE_FLOAT    ,
309     TYPE_VECTOR   ,
310     TYPE_ENTITY   ,
311     TYPE_FIELD    ,
312     TYPE_FUNCTION ,
313     TYPE_POINTER  ,
314     TYPE_INTEGER  ,
315     TYPE_VARIANT  ,
316     TYPE_STRUCT   ,
317     TYPE_UNION    ,
318     TYPE_ARRAY    ,
319
320     TYPE_NIL      , /* it's its own type / untyped */
321     TYPE_NOEXPR   , /* simply invalid in expressions */
322
323     TYPE_COUNT
324 };
325
326 /* const/var qualifiers */
327 #define CV_NONE   0
328 #define CV_CONST  1
329 #define CV_VAR   -1
330 #define CV_WRONG  0x8000 /* magic number to help parsing */
331
332 extern const char    *type_name        [TYPE_COUNT];
333 extern const uint16_t type_store_instr [TYPE_COUNT];
334 extern const uint16_t field_store_instr[TYPE_COUNT];
335
336 /*
337  * could use type_store_instr + INSTR_STOREP_F - INSTR_STORE_F
338  * but this breaks when TYPE_INTEGER is added, since with the enhanced
339  * instruction set, the old ones are left untouched, thus the _I instructions
340  * are at a seperate place.
341  */
342 extern const uint16_t type_storep_instr[TYPE_COUNT];
343 extern const uint16_t type_eq_instr    [TYPE_COUNT];
344 extern const uint16_t type_ne_instr    [TYPE_COUNT];
345 extern const uint16_t type_not_instr   [TYPE_COUNT];
346
347 typedef struct {
348     uint32_t offset;      /* Offset in file of where data begins  */
349     uint32_t length;      /* Length of section (how many of)      */
350 } prog_section_t;
351
352 typedef struct {
353     uint32_t       version;      /* Program version (6)     */
354     uint16_t       crc16;
355     uint16_t       skip;
356
357     prog_section_t statements;   /* prog_section_statement  */
358     prog_section_t defs;         /* prog_section_def        */
359     prog_section_t fields;       /* prog_section_field      */
360     prog_section_t functions;    /* prog_section_function   */
361     prog_section_t strings;
362     prog_section_t globals;
363     uint32_t       entfield;     /* Number of entity fields */
364 } prog_header_t;
365
366 /*
367  * Each paramater incerements by 3 since vector types hold
368  * 3 components (x,y,z).
369  */
370 #define OFS_NULL      0
371 #define OFS_RETURN    1
372 #define OFS_PARM0     (OFS_RETURN+3)
373 #define OFS_PARM1     (OFS_PARM0 +3)
374 #define OFS_PARM2     (OFS_PARM1 +3)
375 #define OFS_PARM3     (OFS_PARM2 +3)
376 #define OFS_PARM4     (OFS_PARM3 +3)
377 #define OFS_PARM5     (OFS_PARM4 +3)
378 #define OFS_PARM6     (OFS_PARM5 +3)
379 #define OFS_PARM7     (OFS_PARM6 +3)
380
381 typedef struct {
382     uint16_t opcode;
383
384     /* operand 1 */
385     union {
386         int16_t  s1; /* signed   */
387         uint16_t u1; /* unsigned */
388     } o1;
389     /* operand 2 */
390     union {
391         int16_t  s1; /* signed   */
392         uint16_t u1; /* unsigned */
393     } o2;
394     /* operand 3 */
395     union {
396         int16_t  s1; /* signed   */
397         uint16_t u1; /* unsigned */
398     } o3;
399
400     /*
401      * This is the same as the structure in darkplaces
402      * {
403      *     unsigned short op;
404      *     short          a,b,c;
405      * }
406      * But this one is more sane to work with, and the
407      * type sizes are guranteed.
408      */
409 } prog_section_statement_t;
410
411 typedef struct {
412     /*
413      * The types:
414      * 0 = ev_void
415      * 1 = ev_string
416      * 2 = ev_float
417      * 3 = ev_vector
418      * 4 = ev_entity
419      * 5 = ev_field
420      * 6 = ev_function
421      * 7 = ev_pointer -- engine only
422      * 8 = ev_bad     -- engine only
423      */
424     uint16_t type;
425     uint16_t offset;
426     uint32_t name;
427 } prog_section_both_t;
428
429 typedef prog_section_both_t prog_section_def_t;
430 typedef prog_section_both_t prog_section_field_t;
431
432 /* this is ORed to the type */
433 #define DEF_SAVEGLOBAL (1<<15)
434 #define DEF_TYPEMASK   ((1<<15)-1)
435
436 typedef struct {
437     int32_t   entry;      /* in statement table for instructions  */
438     uint32_t  firstlocal; /* First local in local table           */
439     uint32_t  locals;     /* Total ints of params + locals        */
440     uint32_t  profile;    /* Always zero (engine uses this)       */
441     uint32_t  name;       /* name of function in string table     */
442     uint32_t  file;       /* file of the source file              */
443     int32_t   nargs;      /* number of arguments                  */
444     uint8_t   argsize[8]; /* size of arguments (keep 8 always?)   */
445 } prog_section_function_t;
446
447 /*
448  * Instructions
449  * These are the external instructions supported by the interperter
450  * this is what things compile to (from the C code).
451  */
452 enum {
453     INSTR_DONE,
454     INSTR_MUL_F,
455     INSTR_MUL_V,
456     INSTR_MUL_FV, /* NOTE: the float operands must NOT be at the same locations: A != C */
457     INSTR_MUL_VF, /* and here: B != C */
458     INSTR_DIV_F,
459     INSTR_ADD_F,
460     INSTR_ADD_V,
461     INSTR_SUB_F,
462     INSTR_SUB_V,
463     INSTR_EQ_F,
464     INSTR_EQ_V,
465     INSTR_EQ_S,
466     INSTR_EQ_E,
467     INSTR_EQ_FNC,
468     INSTR_NE_F,
469     INSTR_NE_V,
470     INSTR_NE_S,
471     INSTR_NE_E,
472     INSTR_NE_FNC,
473     INSTR_LE,
474     INSTR_GE,
475     INSTR_LT,
476     INSTR_GT,
477     INSTR_LOAD_F,
478     INSTR_LOAD_V,
479     INSTR_LOAD_S,
480     INSTR_LOAD_ENT,
481     INSTR_LOAD_FLD,
482     INSTR_LOAD_FNC,
483     INSTR_ADDRESS,
484     INSTR_STORE_F,
485     INSTR_STORE_V,
486     INSTR_STORE_S,
487     INSTR_STORE_ENT,
488     INSTR_STORE_FLD,
489     INSTR_STORE_FNC,
490     INSTR_STOREP_F,
491     INSTR_STOREP_V,
492     INSTR_STOREP_S,
493     INSTR_STOREP_ENT,
494     INSTR_STOREP_FLD,
495     INSTR_STOREP_FNC,
496     INSTR_RETURN,
497     INSTR_NOT_F,
498     INSTR_NOT_V,
499     INSTR_NOT_S,
500     INSTR_NOT_ENT,
501     INSTR_NOT_FNC,
502     INSTR_IF,
503     INSTR_IFNOT,
504     INSTR_CALL0,
505     INSTR_CALL1,
506     INSTR_CALL2,
507     INSTR_CALL3,
508     INSTR_CALL4,
509     INSTR_CALL5,
510     INSTR_CALL6,
511     INSTR_CALL7,
512     INSTR_CALL8,
513     INSTR_STATE,
514     INSTR_GOTO,
515     INSTR_AND,
516     INSTR_OR,
517     INSTR_BITAND,
518     INSTR_BITOR,
519
520     /*
521      * Virtual instructions used by the IR
522      * Keep at the end!
523      */
524     VINSTR_END,
525     VINSTR_PHI,
526     VINSTR_JUMP,
527     VINSTR_COND,
528
529     /* A never returning CALL.
530      * Creating this causes IR blocks to be marked as 'final'.
531      * No-Return-Call
532      */
533     VINSTR_NRCALL,
534
535     /* Emulated instructions. */
536     VINSTR_BITAND_V, /* BITAND_V must be the first emulated bitop */
537     VINSTR_BITAND_VF,
538     VINSTR_BITOR_V,
539     VINSTR_BITOR_VF,
540     VINSTR_BITXOR,
541     VINSTR_BITXOR_V,
542     VINSTR_BITXOR_VF,
543     VINSTR_CROSS,
544     VINSTR_NEG_F,
545     VINSTR_NEG_V
546 };
547
548 /* TODO: elide */
549 extern const char *util_instr_str[VINSTR_END];
550
551 void util_swap_header     (prog_header_t              *code_header);
552 void util_swap_statements (prog_section_statement_t   *statements);
553 void util_swap_defs_fields(prog_section_both_t        *section);
554 void util_swap_functions  (prog_section_function_t    *functions);
555 void util_swap_globals    (int32_t                    *globals);
556
557 typedef float    qcfloat_t;
558 typedef int32_t  qcint_t;
559 typedef uint32_t qcuint_t;
560
561 typedef struct {
562     prog_section_statement_t *statements;
563     int                      *linenums;
564     int                      *columnnums;
565     prog_section_def_t       *defs;
566     prog_section_field_t     *fields;
567     prog_section_function_t  *functions;
568     int                      *globals;
569     char                     *chars;
570     uint16_t                  crc;
571     uint32_t                  entfields;
572     ht                        string_cache;
573     qcint_t                   string_cached_empty;
574 } code_t;
575
576 /*
577  * A shallow copy of a lex_file to remember where which ast node
578  * came from.
579  */
580 typedef struct {
581     const char *file;
582     size_t      line;
583     size_t      column;
584 } lex_ctx_t;
585
586 /*
587  * code_write          -- writes out the compiled file
588  * code_init           -- prepares the code file
589  * code_genstrin       -- generates string for code
590  * code_alloc_field    -- allocated a field
591  * code_push_statement -- keeps statements and linenumbers together
592  * code_pop_statement  -- keeps statements and linenumbers together
593  */
594 bool      code_write         (code_t *, const char *filename, const char *lno);
595 GMQCC_WARN
596 code_t   *code_init          (void);
597 void      code_cleanup       (code_t *);
598 uint32_t  code_genstring     (code_t *, const char *string);
599 qcint_t   code_alloc_field   (code_t *, size_t qcsize);
600 void      code_push_statement(code_t *, prog_section_statement_t *stmt, lex_ctx_t ctx);
601 void      code_pop_statement (code_t *);
602
603
604 /* conout.c */
605 enum {
606     CON_BLACK   = 30,
607     CON_RED,
608     CON_GREEN,
609     CON_BROWN,
610     CON_BLUE,
611     CON_MAGENTA,
612     CON_CYAN ,
613     CON_WHITE
614 };
615
616 /* message level */
617 enum {
618     LVL_MSG,
619     LVL_WARNING,
620     LVL_ERROR
621 };
622
623 FILE *con_default_out(void);
624 FILE *con_default_err(void);
625
626 void con_vprintmsg (int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, va_list ap);
627 void con_printmsg  (int level, const char *name, size_t line, size_t column, const char *msgtype, const char *msg, ...);
628 void con_cvprintmsg(lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, va_list ap);
629 void con_cprintmsg (lex_ctx_t ctx, int lvl, const char *msgtype, const char *msg, ...);
630
631 void con_close (void);
632 void con_init  (void);
633 void con_reset (void);
634 void con_color (int);
635 int  con_verr  (const char *, va_list);
636 int  con_vout  (const char *, va_list);
637 int  con_err   (const char *, ...);
638 int  con_out   (const char *, ...);
639
640 /* error/warning interface */
641 extern size_t compile_errors;
642 extern size_t compile_Werrors;
643 extern size_t compile_warnings;
644
645 void /********/ compile_error   (lex_ctx_t ctx, /*LVL_ERROR*/ const char *msg, ...);
646 void /********/ vcompile_error  (lex_ctx_t ctx, /*LVL_ERROR*/ const char *msg, va_list ap);
647 bool GMQCC_WARN compile_warning (lex_ctx_t ctx, int warntype, const char *fmt, ...);
648 bool GMQCC_WARN vcompile_warning(lex_ctx_t ctx, int warntype, const char *fmt, va_list ap);
649 void            compile_show_werrors(void);
650
651 /* ir.c */
652 /* TODO: cleanup */
653 enum store_types {
654     store_global,
655     store_local,  /* local, assignable for now, should get promoted later */
656     store_param,  /* parameters, they are locals with a fixed position */
657     store_value,  /* unassignable */
658     store_return  /* unassignable, at OFS_RETURN */
659 };
660
661 typedef struct {
662     qcfloat_t x, y, z;
663 } vec3_t;
664
665 /* exec.c */
666
667 /* TODO: cleanup */
668 /*
669  * Darkplaces has (or will have) a 64 bit prog loader
670  * where the 32 bit qc program is autoconverted on load.
671  * Since we may want to support that as well, let's redefine
672  * float and int here.
673  */
674 typedef union {
675     qcint_t   _int;
676     qcint_t    string;
677     qcint_t    function;
678     qcint_t    edict;
679     qcfloat_t _float;
680     qcfloat_t vector[3];
681     qcint_t   ivector[3];
682 } qcany_t;
683
684 typedef char qcfloat_t_size_is_correct [sizeof(qcfloat_t) == 4 ?1:-1];
685 typedef char qcint_t_size_is_correct   [sizeof(qcint_t)   == 4 ?1:-1];
686
687 enum {
688     VMERR_OK,
689     VMERR_TEMPSTRING_ALLOC,
690     VMERR_END
691 };
692
693 #define VM_JUMPS_DEFAULT 1000000
694
695 /* execute-flags */
696 #define VMXF_DEFAULT 0x0000     /* default flags - nothing */
697 #define VMXF_TRACE   0x0001     /* trace: print statements before executing */
698 #define VMXF_PROFILE 0x0002     /* profile: increment the profile counters */
699
700 struct qc_program_s;
701 typedef int (*prog_builtin_t)(struct qc_program_s *prog);
702
703 typedef struct {
704     qcint_t                    stmt;
705     size_t                   localsp;
706     prog_section_function_t *function;
707 } qc_exec_stack_t;
708
709 typedef struct qc_program_s {
710     char                     *filename;
711     prog_section_statement_t *code;
712     prog_section_def_t       *defs;
713     prog_section_def_t       *fields;
714     prog_section_function_t  *functions;
715     char                     *strings;
716     qcint_t                  *globals;
717     qcint_t                  *entitydata;
718     bool                     *entitypool;
719
720     const char*              *function_stack;
721
722     uint16_t crc16;
723
724     size_t tempstring_start;
725     size_t tempstring_at;
726
727     qcint_t  vmerror;
728
729     size_t *profile;
730
731     prog_builtin_t *builtins;
732     size_t          builtins_count;
733
734     /* size_t ip; */
735     qcint_t  entities;
736     size_t entityfields;
737     bool   allowworldwrites;
738
739     qcint_t         *localstack;
740     qc_exec_stack_t *stack;
741     size_t statement;
742
743     size_t xflags;
744
745     int    argc; /* current arg count for debugging */
746
747     /* cached fields */
748     struct {
749         qcint_t frame;
750         qcint_t nextthink;
751         qcint_t think;
752     } cached_fields;
753
754     struct {
755         qcint_t self;
756         qcint_t time;
757     } cached_globals;
758
759     bool supports_state; /* is INSTR_STATE supported? */
760 } qc_program_t;
761
762 qc_program_t*       prog_load      (const char *filename, bool ignoreversion);
763 void                prog_delete    (qc_program_t *prog);
764 bool                prog_exec      (qc_program_t *prog, prog_section_function_t *func, size_t flags, long maxjumps);
765 const char*         prog_getstring (qc_program_t *prog, qcint_t str);
766 prog_section_def_t* prog_entfield  (qc_program_t *prog, qcint_t off);
767 prog_section_def_t* prog_getdef    (qc_program_t *prog, qcint_t off);
768 qcany_t*            prog_getedict  (qc_program_t *prog, qcint_t e);
769 qcint_t               prog_tempstring(qc_program_t *prog, const char *_str);
770
771
772 /* parser.c */
773 struct parser_s;
774 struct parser_s *parser_create        (void);
775 bool             parser_compile_file  (struct parser_s *parser, const char *);
776 bool             parser_compile_string(struct parser_s *parser, const char *, const char *, size_t);
777 bool             parser_finish        (struct parser_s *parser, const char *);
778 void             parser_cleanup       (struct parser_s *parser);
779
780 /* ftepp.c */
781 struct ftepp_s;
782 struct ftepp_s *ftepp_create           (void);
783 bool            ftepp_preprocess_file  (struct ftepp_s *ftepp, const char *filename);
784 bool            ftepp_preprocess_string(struct ftepp_s *ftepp, const char *name, const char *str);
785 void            ftepp_finish           (struct ftepp_s *ftepp);
786 const char     *ftepp_get              (struct ftepp_s *ftepp);
787 void            ftepp_flush            (struct ftepp_s *ftepp);
788 void            ftepp_add_define       (struct ftepp_s *ftepp, const char *source, const char *name);
789 void            ftepp_add_macro        (struct ftepp_s *ftepp, const char *name,   const char *value);
790
791 /* main.c */
792
793 #if 1
794 /* Helpers to allow for a whole lot of flags. Otherwise we'd limit
795  * to 32 or 64 -f options...
796  */
797 typedef struct {
798     size_t  idx; /* index into an array of 32 bit words */
799     uint8_t bit; /* bit index for the 8 bit group idx points to */
800 } longbit;
801 #define LONGBIT(bit) { ((bit)/32), ((bit)%32) }
802 #define LONGBIT_SET(B, I) ((B).idx = (I)/32, (B).bit = ((I)%32))
803 #else
804 typedef uint32_t longbit;
805 #define LONGBIT(bit) (bit)
806 #define LONGBIT_SET(B, I) ((B) = (I))
807 #endif
808
809 /* utf.8 */
810 typedef long utf8ch_t;
811 int utf8_from(char *, utf8ch_t);
812 int utf8_to(utf8ch_t *, const unsigned char *, size_t);
813
814 /* opts.c */
815 typedef struct {
816     const char *name;
817     longbit     bit;
818 } opts_flag_def_t;
819
820 bool opts_setflag  (const char *, bool);
821 bool opts_setwarn  (const char *, bool);
822 bool opts_setwerror(const char *, bool);
823 bool opts_setoptim (const char *, bool);
824
825 void opts_init         (const char *, int, size_t);
826 void opts_set          (uint32_t   *, size_t, bool);
827 void opts_setoptimlevel(unsigned int);
828 void opts_ini_init     (const char *);
829
830 /* Saner flag handling */
831 void opts_backup_non_Wall(void);
832 void opts_restore_non_Wall(void);
833 void opts_backup_non_Werror_all(void);
834 void opts_restore_non_Werror_all(void);
835
836
837 enum {
838 # define GMQCC_TYPE_FLAGS
839 # define GMQCC_DEFINE_FLAG(X) X,
840 #  include "opts.def"
841     COUNT_FLAGS
842 };
843
844 enum {
845 # define GMQCC_TYPE_WARNS
846 # define GMQCC_DEFINE_FLAG(X) WARN_##X,
847 #  include "opts.def"
848     COUNT_WARNINGS
849 };
850
851 enum {
852 # define GMQCC_TYPE_OPTIMIZATIONS
853 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) OPTIM_##NAME,
854 #  include "opts.def"
855     COUNT_OPTIMIZATIONS
856 };
857
858 enum {
859 #   define GMQCC_TYPE_OPTIONS
860 #   define GMQCC_DEFINE_FLAG(X) OPTION_##X,
861 #   include "opts.def"
862     OPTION_COUNT
863 };
864
865 extern const opts_flag_def_t opts_flag_list[COUNT_FLAGS+1];
866 extern const opts_flag_def_t opts_warn_list[COUNT_WARNINGS+1];
867 extern const opts_flag_def_t opts_opt_list[COUNT_OPTIMIZATIONS+1];
868 extern const unsigned int    opts_opt_oflag[COUNT_OPTIMIZATIONS+1];
869 extern unsigned int          opts_optimizationcount[COUNT_OPTIMIZATIONS];
870
871 /* other options: */
872 typedef enum {
873     COMPILER_QCC,     /* circa  QuakeC */
874     COMPILER_FTEQCC,  /* fteqcc QuakeC */
875     COMPILER_QCCX,    /* qccx   QuakeC */
876     COMPILER_GMQCC    /* this   QuakeC */
877 } opts_std_t;
878
879 typedef struct {
880     union {
881         bool     b;
882         uint16_t u16;
883         uint32_t u32;
884
885         union {
886             char       *p;
887             const char *c;
888         } str;
889     } data;
890
891     bool allocated;
892 } opt_value_t;
893
894
895 typedef struct {
896     opt_value_t  options      [OPTION_COUNT];
897     uint32_t     flags        [1 + (COUNT_FLAGS         / 32)];
898     uint32_t     warn         [1 + (COUNT_WARNINGS      / 32)];
899     uint32_t     werror       [1 + (COUNT_WARNINGS      / 32)];
900     uint32_t     warn_backup  [1 + (COUNT_WARNINGS      / 32)];
901     uint32_t     werror_backup[1 + (COUNT_WARNINGS      / 32)];
902     uint32_t     optimization [1 + (COUNT_OPTIMIZATIONS / 32)];
903     bool         optimizeoff; /* True when -O0 */
904 } opts_cmd_t;
905
906 extern opts_cmd_t opts;
907
908 #define OPTS_GENERIC(f,i)    (!! (((f)[(i)/32]) & (1U << (unsigned)((i)%32))))
909
910 #define OPTS_FLAG(i)         OPTS_GENERIC(opts.flags,        (i))
911 #define OPTS_WARN(i)         OPTS_GENERIC(opts.warn,         (i))
912 #define OPTS_WERROR(i)       OPTS_GENERIC(opts.werror,       (i))
913 #define OPTS_OPTIMIZATION(i) OPTS_GENERIC(opts.optimization, (i))
914
915 #define OPTS_OPTION_DUPED(X) (opts.options[X].allocated)
916 #define OPTS_OPTION_BOOL(X)  (opts.options[X].data.b)
917 #define OPTS_OPTION_U16(X)   (opts.options[X].data.u16)
918 #define OPTS_OPTION_U32(X)   (opts.options[X].data.u32)
919 #define OPTS_OPTION_STR(X)   (opts.options[X].data.str.c)
920 #define OPTS_OPTION_DUP(X)  *(OPTS_OPTION_DUPED(X)=true, &(opts.options[X].data.str.p))
921
922 #endif /*! GMQCC_HDR */