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