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