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