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