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