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