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