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