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