]> git.xonotic.org Git - xonotic/gmqcc.git/blob - gmqcc.h
Windows stuff for visual studio now offical works with exception to colorized output...
[xonotic/gmqcc.git] / gmqcc.h
1 /*
2  * Copyright (C) 2012
3  *     Dale Weiler
4  *     Wolfgang Bumiller
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy of
7  * this software and associated documentation files (the "Software"), to deal in
8  * the Software without restriction, including without limitation the rights to
9  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10  * of the Software, and to permit persons to whom the Software is furnished to do
11  * so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in all
14  * copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  */
24 #ifndef GMQCC_HDR
25 #define GMQCC_HDR
26 #include <limits.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <stdio.h>
30 #include <stdarg.h>
31 #include <ctype.h>
32
33 /*
34  * Disable some over protective warnings in visual studio because fixing them is a waste
35  * of my time.
36  */
37 #ifdef _MSC_VER
38 #       pragma warning(disable : 4244 ) /* conversion from 'int' to 'float', possible loss of data */
39 #       pragma warning(disable : 4018 ) /* signed/unsigned mismatch                                */
40 #       pragma warning(disable : 4996 ) /* This function or variable may be unsafe                 */
41 #       pragma warning(disable : 4700 ) /* uninitialized local variable used                       */
42 #       pragma warning(disable : 4129 ) /* unrecognized character secape sequence                  */
43 #endif
44
45 #define GMQCC_VERSION_MAJOR 0
46 #define GMQCC_VERSION_MINOR 2
47 #define GMQCC_VERSION_PATCH 0
48 #define GMQCC_VERSION_BUILD(J,N,P) (((J)<<16)|((N)<<8)|(P))
49 #define GMQCC_VERSION \
50     GMQCC_VERSION_BUILD(GMQCC_VERSION_MAJOR, GMQCC_VERSION_MINOR, GMQCC_VERSION_PATCH)
51
52 /*
53  * We cannoy rely on C99 at all, since compilers like MSVC
54  * simply don't support it.  We define our own boolean type
55  * as a result (since we cannot include <stdbool.h>). For
56  * compilers that are in 1999 mode (C99 compliant) we can use
57  * the language keyword _Bool which can allow for better code
58  * on GCC and GCC-like compilers, opposed to `int`.
59  */
60 #ifndef __cplusplus
61 #   ifdef  false
62 #       undef  false
63 #   endif /* !false */
64 #   ifdef  true
65 #       undef true
66 #   endif /* !true  */
67 #   define false (0)
68 #   define true  (1)
69 #   ifdef __STDC_VERSION__
70 #       if __STDC_VERSION__ < 199901L && __GNUC__ < 3
71             typedef int  bool;
72 #       else
73             typedef _Bool bool;
74 #       endif
75 #   else
76         typedef int bool;
77 #   endif /* !__STDC_VERSION__ */
78 #endif    /* !__cplusplus      */
79
80
81
82 /*
83  * Of some functions which are generated we want to make sure
84  * that the result isn't ignored. To find such function calls,
85  * we use this macro.
86  */
87 #if defined(__GNUC__) || defined(__CLANG__)
88 #   define GMQCC_WARN __attribute__((warn_unused_result))
89 #else
90 #   define GMQCC_WARN
91 #endif
92 /*
93  * This is a hack to silent clang regarding empty
94  * body if statements.
95  */
96 #define GMQCC_SUPPRESS_EMPTY_BODY do { } while (0)
97
98 /*
99  * Inline is not supported in < C90, however some compilers
100  * like gcc and clang might have an inline attribute we can
101  * use if present.
102  */
103 #ifdef __STDC_VERSION__
104 #    if __STDC_VERSION__ < 199901L
105 #       if defined(__GNUC__) || defined (__CLANG__)
106 #           if __GNUC__ < 2
107 #               define GMQCC_INLINE
108 #           else
109 #               define GMQCC_INLINE __attribute__ ((always_inline))
110 #           endif
111 #       else
112 #           define GMQCC_INLINE
113 #       endif
114 #    else
115 #       define GMQCC_INLINE inline
116 #    endif
117 /*
118  * Visual studio has __forcinline we can use.  So lets use that
119  * I suspect it also has just __inline of some sort, but our use
120  * of inline is correct (not guessed), WE WANT IT TO BE INLINE
121  */
122 #elif defined(_MSC_VER)
123 #    define GMQCC_INLINE __forceinline
124 #else
125 #    define GMQCC_INLINE
126 #endif /* !__STDC_VERSION__ */
127
128 /*
129  * noreturn is present in GCC and clang
130  * it's required for _ast_node_destory otherwise -Wmissing-noreturn
131  * in clang complains about there being no return since abort() is
132  * called.
133  */
134 #if (defined(__GNUC__) && __GNUC__ >= 2) || defined(__CLANG__)
135 #    define GMQCC_NORETURN __attribute__ ((noreturn))
136 #else
137 #    define GMQCC_NORETURN
138 #endif
139
140 #ifndef _MSC_VER
141 #   include <stdint.h>
142 #else
143     typedef unsigned __int8  uint8_t;
144     typedef unsigned __int16 uint16_t;
145     typedef unsigned __int32 uint32_t;
146     typedef unsigned __int64 uint64_t;
147
148     typedef __int16          int16_t;
149     typedef __int32          int32_t;
150     typedef __int64          int64_t;
151 #endif
152
153 /* 
154  *windows makes these prefixed because they're C99
155  * TODO: utility versions that are type-safe and not
156  * just plain textual subsitution.
157  */
158 #ifdef _MSC_VER
159 #       define snprintf(X, Y, Z, ...) _snprintf(X, Y, Z, __VA_ARGS__)
160     /* strtof doesn't exist -> strtod does though :) */
161 #       define strtof(X, Y)          (float)(strtod(X, Y))
162 #endif
163
164
165 /*
166  * Very roboust way at determining endianess at compile time: this handles
167  * almost every possible situation.  Otherwise a runtime check has to be
168  * performed.
169  */
170 #define GMQCC_BYTE_ORDER_LITTLE 1234
171 #define GMQCC_BYTE_ORDER_BIG    4321
172
173 #if defined (__GNUC__) || defined (__GNU_LIBRARY__)
174 #   if defined (__FreeBSD__) || defined (__OpenBSD__)
175 #       include <sys/endian.h>
176 #   elif defined (BSD) && (BSD >= 199103) || defined (__DJGPP__) || defined (__CYGWIN32__)
177 #       include <machine/endiane.h>
178 #   elif defined (__APPLE__)
179 #       if defined (__BIG_ENDIAN__) && !defined(BIG_ENDIAN)
180 #           define BIG_ENDIAN
181 #       elif defined (__LITTLE_ENDIAN__) && !defined (LITTLE_ENDIAN)
182 #           define LITTLE_ENDIAN
183 #       endif
184 #   elif !defined (__MINGW32__)
185 #       include <endian.h>
186 #       if !defined (__BEOS__)
187 #           include <byteswap.h>
188 #       endif
189 #   endif
190 #endif
191 #if !defined(PLATFORM_BYTE_ORDER)
192 #   if defined (LITTLE_ENDIAN) || defined (BIG_ENDIAN)
193 #       if defined (LITTLE_ENDIAN) && !defined(BIG_ENDIAN)
194 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
195 #       elif !defined (LITTLE_ENDIAN) && defined (BIG_ENDIAN)
196 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
197 #       elif defined (BYTE_ORDER) && (BYTE_ORDER == LITTLE_ENDIAN)
198 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
199 #       elif defined (BYTE_ORDER) && (BYTE_ORDER == BIG_ENDIAN)
200 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
201 #       endif
202 #   elif defined (_LITTLE_ENDIAN) || defined (_BIG_ENDIAN)
203 #       if defined (_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
204 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
205 #       elif !defined (_LITTLE_ENDIAN) && defined (_BIG_ENDIAN)
206 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
207 #       elif defined (_BYTE_ORDER) && (_BYTE_ORDER == _LITTLE_ENDIAN)
208 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
209 #       elif defined (_BYTE_ORDER) && (_BYTE_ORDER == _BIG_ENDIAN)
210 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
211 #       endif
212 #   elif defined (__LITTLE_ENDIAN__) || defined (__BIG_ENDIAN__)
213 #       if defined (__LITTLE_ENDIAN__) && !defined (__BIG_ENDIAN__)
214 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
215 #       elif !defined (__LITTLE_ENDIAN__) && defined (__BIG_ENDIAN__)
216 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
217 #       elif defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __LITTLE_ENDIAN__)
218 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
219 #       elif defined (__BYTE_ORDER__) && (__BYTE_ORDER__ == __BIG_ENDIAN__)
220 #           define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
221 #       endif
222 #   endif
223 #endif
224 #if !defined (PLATFORM_BYTE_ORDER)
225 #   if   defined (__aplha__) || defined (__aplha)    || defined (i386)       || \
226          defined (__i386__)  || defined (_M_I86)     || defined (_M_IX86)    || \
227          defined (__OS2__)   || defined (sun386)     || defined (__TURBOC__) || \
228          defined (vax)       || defined (vms)        || defined (VMS)        || \
229          defined (__VMS)     || defined (__x86_64__) || defined (_M_IA64)    || \
230          defined (_M_X64)    || defined (__i386)     || defined (__x86_64)
231 #       define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_LITTLE
232 #   elif defined (AMIGA)     || defined (applec)     || defined (__AS400__)  || \
233          defined (_CRAY)     || defined (__hppa)     || defined (__hp9000)   || \
234          defined (ibm370)    || defined (mc68000)    || defined (m68k)       || \
235          defined (__MRC__)   || defined (__MVS__)    || defined (__MWERKS__) || \
236          defined (sparc)     || defined (__sparc)    || defined (SYMANTEC_C) || \
237          defined (__TANDEM)  || defined (THINK_C)    || defined (__VMCMS__)  || \
238          defined (__PPC__)   || defined (__PPC)      || defined (PPC)
239 #       define PLATFORM_BYTE_ORDER GMQCC_BYTE_ORDER_BIG
240 #   else
241 #       define PLATFORM_BYTE_ORDER -1
242 #   endif
243 #endif
244
245
246
247 /*===================================================================*/
248 /*=========================== util.c ================================*/
249 /*===================================================================*/
250 FILE *util_fopen(const char *filename, const char *mode);
251
252 void *util_memory_a      (size_t,       unsigned int, const char *);
253 void  util_memory_d      (void       *, unsigned int, const char *);
254 void *util_memory_r      (void       *, size_t,       unsigned int, const char *);
255 void  util_meminfo       ();
256
257 bool  util_filexists     (const char *);
258 bool  util_strupper      (const char *);
259 bool  util_strdigit      (const char *);
260 bool  util_strncmpexact  (const char *, const char *, size_t);
261 char *util_strdup        (const char *);
262 char *util_strrq         (const char *);
263 char *util_strrnl        (const char *);
264 char *util_strsws        (const char *);
265 char *util_strchp        (const char *, const char *);
266 void  util_debug         (const char *, const char *, ...);
267 int   util_getline       (char **, size_t *, FILE *);
268 void  util_endianswap    (void *,  size_t, unsigned int);
269
270 size_t util_strtocmd    (const char *, char *, size_t);
271 size_t util_strtononcmd (const char *, char *, size_t);
272
273 uint16_t util_crc16(uint16_t crc, const char *data, size_t len);
274 uint32_t util_crc32(uint32_t crc, const char *data, size_t len);
275
276 /*
277  * If we're compiling as C++ code we need to fix some subtle issues regarding casts between mem_a/mem_d
278  * since C++ doesn't allow implicit conversions between void*
279  */
280 #ifdef __cplusplus
281         /*
282          * void * will be implicitally converted to gmqcc_voidptr using gmqcc_voidptr(void*).  This is what
283          * essentially allows us to allow implicit conversion to whatever pointer type we're trying to assign
284          * to because it acks as a default assignment constructor.
285          */
286         class gmqcc_voidptr {
287             void *m_pointer;
288         public:
289             gmqcc_voidptr(void *pointer) :
290                 m_pointer(pointer)
291             { };
292
293             template <typename T>
294             GMQCC_INLINE operator T *() {
295                 return m_pointer;
296             }
297         };
298
299 #       define GMQCC_IMPLICIT_POINTER(X) (gmqcc_voidptr(X))
300 #else
301 #       define GMQCC_IMPLICIT_POINTER(X) (X)
302 #endif
303
304 #ifdef NOTRACK
305 #    define mem_a(x)    GMQCC_IMPLICIT_POINTER(malloc (x))
306 #    define mem_d(x)    free   ((void*)x)
307 #    define mem_r(x, n) realloc((void*)x, n)
308 #else
309 #    define mem_a(x)    GMQCC_IMPLICIT_POINTER(util_memory_a((x), __LINE__, __FILE__))
310 #    define mem_d(x)    util_memory_d((void*)(x),      __LINE__, __FILE__)
311 #    define mem_r(x, n) util_memory_r((void*)(x), (n), __LINE__, __FILE__)
312 #endif
313
314 /*
315  * TODO: make these safer to use.  Currently this only works on
316  * x86 and x86_64, some systems will likely not like this. Such
317  * as BE systems. (and clean this up to use a structure ... )
318  */
319 #define FLT2INT(Y) *((int32_t*)&(Y))
320 #define INT2FLT(Y) *((float  *)&(Y))
321
322 /* New flexible vector implementation from Dale */
323 #define _vec_raw(A) (((size_t*)(void*)(A)) - 2)
324 #define _vec_beg(A) (_vec_raw(A)[0])
325 #define _vec_end(A) (_vec_raw(A)[1])
326 #define _vec_needsgrow(A,N) ((!(A)) || (_vec_end(A) + (N) >= _vec_beg(A)))
327 #define _vec_mightgrow(A,N) (_vec_needsgrow((A), (N)) ? (void)_vec_forcegrow((A),(N)) : (void)0)
328 #define _vec_forcegrow(A,N) _util_vec_grow(((void**)&(A)), (N), sizeof(*(A)))
329 #define _vec_remove(A,S,I,N) (memmove((char*)(A)+(I)*(S),(char*)(A)+((I)+(N))*(S),(S)*(_vec_end(A)-(I)-(N))), _vec_end(A)-=(N))
330 void _util_vec_grow(void **a, size_t i, size_t s);
331 /* exposed interface */
332 #define vec_free(A)          ((A) ? (mem_d((void*)_vec_raw(A)), (A) = NULL) : 0)
333 #define vec_push(A,V)        (_vec_mightgrow((A),1), (A)[_vec_end(A)++] = (V))
334 #define vec_size(A)          ((A) ? _vec_end(A) : 0)
335 #define vec_add(A,N)         (_vec_mightgrow((A),(N)), _vec_end(A)+=(N), &(A)[_vec_end(A)-(N)])
336 #define vec_last(A)          ((A)[_vec_end(A)-1])
337 #define vec_append(A,N,S)    memcpy(vec_add((A), (N)), (S), N * sizeof(*(S)))
338 #define vec_remove(A,I,N)    _vec_remove((A), sizeof(*(A)), (I), (N))
339 #define vec_pop(A)           (_vec_end(A)-=1)
340 /* these are supposed to NOT reallocate */
341 #define vec_shrinkto(A,N)    (_vec_end(A) = (N))
342 #define vec_shrinkby(A,N)    (_vec_end(A) -= (N))
343
344 /* vec_upload needs to be cleaned up as well to be a function */
345 #define vec_upload(X,Y,S)      \
346     do {                       \
347         size_t E = 0;          \
348         while (E < S) {        \
349             vec_push(X, Y[E]); \
350             E ++;              \
351         }                      \
352     } while(0)
353
354 typedef struct hash_table_t {
355     size_t                size;
356     struct hash_node_t **table;
357 } hash_table_t, *ht;
358
359 /*
360  * hashtable implementation:
361  *
362  * Note:
363  *      This was designed for pointers:  you manage the life of the object yourself
364  *      if you do use this for non-pointers please be warned that the object may not
365  *      be valid if the duration of it exceeds (i.e on stack).  So you need to allocate
366  *      yourself, or put those in global scope to ensure duration is for the whole
367  *      runtime.
368  *
369  * util_htnew(size)                             -- to make a new hashtable
370  * util_htset(table, key, value, sizeof(value)) -- to set something in the table
371  * util_htget(table, key)                       -- to get something from the table
372  * util_htdel(table)                            -- to delete the table
373  *
374  * example of use:
375  *
376  * ht    foo  = util_htnew(1024);
377  * int   data = 100;
378  * char *test = "hello world\n";
379  * util_htset(foo, "foo", (void*)&data);
380  * util_gtset(foo, "bar", (void*)test);
381  *
382  * printf("foo: %d, bar %s",
383  *     *((int *)util_htget(foo, "foo")),
384  *      ((char*)util_htget(foo, "bar"))
385  * );
386  *
387  * util_htdel(foo);
388  */
389 hash_table_t *util_htnew (size_t size);
390 void          util_htset (hash_table_t *ht, const char *key, void *value);
391 void         *util_htget (hash_table_t *ht, const char *key);
392 void          util_htdel (hash_table_t *ht);
393 size_t        util_hthash(hash_table_t *ht, const char *key);
394 void         *util_htgeth(hash_table_t *ht, const char *key, size_t hash);
395 void          util_htseth(hash_table_t *ht, const char *key, size_t hash, void *value);
396 /*===================================================================*/
397 /*=========================== code.c ================================*/
398 /*===================================================================*/
399
400 /* Note: if you change the order, fix type_sizeof in ir.c */
401 enum {
402     TYPE_VOID     ,
403     TYPE_STRING   ,
404     TYPE_FLOAT    ,
405     TYPE_VECTOR   ,
406     TYPE_ENTITY   ,
407     TYPE_FIELD    ,
408     TYPE_FUNCTION ,
409     TYPE_POINTER  ,
410     TYPE_INTEGER  ,
411     TYPE_VARIANT  ,
412     TYPE_STRUCT   ,
413     TYPE_UNION    ,
414     TYPE_ARRAY    ,
415
416     TYPE_COUNT
417 };
418
419 /* const/var qualifiers */
420 #define CV_NONE   0
421 #define CV_CONST  1
422 #define CV_VAR   -1
423 #define CV_WRONG  0x8000 /* magic number to help parsing */
424
425 extern const char *type_name        [TYPE_COUNT];
426 extern uint16_t    type_store_instr [TYPE_COUNT];
427 extern uint16_t    field_store_instr[TYPE_COUNT];
428
429 /*
430  * could use type_store_instr + INSTR_STOREP_F - INSTR_STORE_F
431  * but this breaks when TYPE_INTEGER is added, since with the enhanced
432  * instruction set, the old ones are left untouched, thus the _I instructions
433  * are at a seperate place.
434  */
435 extern uint16_t type_storep_instr[TYPE_COUNT];
436 extern uint16_t type_eq_instr    [TYPE_COUNT];
437 extern uint16_t type_ne_instr    [TYPE_COUNT];
438 extern uint16_t type_not_instr   [TYPE_COUNT];
439
440 typedef struct {
441     uint32_t offset;      /* Offset in file of where data begins  */
442     uint32_t length;      /* Length of section (how many of)      */
443 } prog_section;
444
445 typedef struct {
446     uint32_t     version;      /* Program version (6)     */
447     uint16_t     crc16;
448     uint16_t     skip;
449
450     prog_section statements;   /* prog_section_statement  */
451     prog_section defs;         /* prog_section_def        */
452     prog_section fields;       /* prog_section_field      */
453     prog_section functions;    /* prog_section_function   */
454     prog_section strings;
455     prog_section globals;
456     uint32_t     entfield;     /* Number of entity fields */
457 } prog_header;
458
459 /*
460  * Each paramater incerements by 3 since vector types hold
461  * 3 components (x,y,z).
462  */
463 #define OFS_NULL      0
464 #define OFS_RETURN    1
465 #define OFS_PARM0     (OFS_RETURN+3)
466 #define OFS_PARM1     (OFS_PARM0 +3)
467 #define OFS_PARM2     (OFS_PARM1 +3)
468 #define OFS_PARM3     (OFS_PARM2 +3)
469 #define OFS_PARM4     (OFS_PARM3 +3)
470 #define OFS_PARM5     (OFS_PARM4 +3)
471 #define OFS_PARM6     (OFS_PARM5 +3)
472 #define OFS_PARM7     (OFS_PARM6 +3)
473
474 typedef struct {
475     uint16_t opcode;
476
477     /* operand 1 */
478     union {
479         int16_t  s1; /* signed   */
480         uint16_t u1; /* unsigned */
481     } o1;
482     /* operand 2 */
483     union {
484         int16_t  s1; /* signed   */
485         uint16_t u1; /* unsigned */
486     } o2;
487     /* operand 3 */
488     union {
489         int16_t  s1; /* signed   */
490         uint16_t u1; /* unsigned */
491     } o3;
492
493     /*
494      * This is the same as the structure in darkplaces
495      * {
496      *     unsigned short op;
497      *     short          a,b,c;
498      * }
499      * But this one is more sane to work with, and the
500      * type sizes are guranteed.
501      */
502 } prog_section_statement;
503
504 typedef struct {
505     /*
506      * The types:
507      * 0 = ev_void
508      * 1 = ev_string
509      * 2 = ev_float
510      * 3 = ev_vector
511      * 4 = ev_entity
512      * 5 = ev_field
513      * 6 = ev_function
514      * 7 = ev_pointer -- engine only
515      * 8 = ev_bad     -- engine only
516      */
517     uint16_t type;
518     uint16_t offset;
519     uint32_t name;
520 } prog_section_both;
521
522 typedef prog_section_both prog_section_def;
523 typedef prog_section_both prog_section_field;
524
525 /* this is ORed to the type */
526 #define DEF_SAVEGLOBAL (1<<15)
527 #define DEF_TYPEMASK   ((1<<15)-1)
528
529 typedef struct {
530     int32_t   entry;      /* in statement table for instructions  */
531     uint32_t  firstlocal; /* First local in local table           */
532     uint32_t  locals;     /* Total ints of params + locals        */
533     uint32_t  profile;    /* Always zero (engine uses this)       */
534     uint32_t  name;       /* name of function in string table     */
535     uint32_t  file;       /* file of the source file              */
536     int32_t   nargs;      /* number of arguments                  */
537     uint8_t   argsize[8]; /* size of arguments (keep 8 always?)   */
538 } prog_section_function;
539
540 /*
541  * Instructions
542  * These are the external instructions supported by the interperter
543  * this is what things compile to (from the C code).
544  */
545 enum {
546     INSTR_DONE,
547     INSTR_MUL_F,
548     INSTR_MUL_V,
549     INSTR_MUL_FV, /* NOTE: the float operands must NOT be at the same locations: A != C */
550     INSTR_MUL_VF, /* and here: B != C */
551     INSTR_DIV_F,
552     INSTR_ADD_F,
553     INSTR_ADD_V,
554     INSTR_SUB_F,
555     INSTR_SUB_V,
556     INSTR_EQ_F,
557     INSTR_EQ_V,
558     INSTR_EQ_S,
559     INSTR_EQ_E,
560     INSTR_EQ_FNC,
561     INSTR_NE_F,
562     INSTR_NE_V,
563     INSTR_NE_S,
564     INSTR_NE_E,
565     INSTR_NE_FNC,
566     INSTR_LE,
567     INSTR_GE,
568     INSTR_LT,
569     INSTR_GT,
570     INSTR_LOAD_F,
571     INSTR_LOAD_V,
572     INSTR_LOAD_S,
573     INSTR_LOAD_ENT,
574     INSTR_LOAD_FLD,
575     INSTR_LOAD_FNC,
576     INSTR_ADDRESS,
577     INSTR_STORE_F,
578     INSTR_STORE_V,
579     INSTR_STORE_S,
580     INSTR_STORE_ENT,
581     INSTR_STORE_FLD,
582     INSTR_STORE_FNC,
583     INSTR_STOREP_F,
584     INSTR_STOREP_V,
585     INSTR_STOREP_S,
586     INSTR_STOREP_ENT,
587     INSTR_STOREP_FLD,
588     INSTR_STOREP_FNC,
589     INSTR_RETURN,
590     INSTR_NOT_F,
591     INSTR_NOT_V,
592     INSTR_NOT_S,
593     INSTR_NOT_ENT,
594     INSTR_NOT_FNC,
595     INSTR_IF,
596     INSTR_IFNOT,
597     INSTR_CALL0,
598     INSTR_CALL1,
599     INSTR_CALL2,
600     INSTR_CALL3,
601     INSTR_CALL4,
602     INSTR_CALL5,
603     INSTR_CALL6,
604     INSTR_CALL7,
605     INSTR_CALL8,
606     INSTR_STATE,
607     INSTR_GOTO,
608     INSTR_AND,
609     INSTR_OR,
610     INSTR_BITAND,
611     INSTR_BITOR,
612
613     /*
614      * Virtual instructions used by the assembler
615      * keep at the end but before virtual instructions
616      * for the IR below.
617      */
618     AINSTR_END,
619
620     /*
621      * Virtual instructions used by the IR
622      * Keep at the end!
623      */
624     VINSTR_PHI,
625     VINSTR_JUMP,
626     VINSTR_COND,
627     /* A never returning CALL.
628      * Creating this causes IR blocks to be marked as 'final'.
629      * No-Return-Call
630      */
631     VINSTR_NRCALL
632 };
633
634 /* TODO: cleanup this mess */
635 extern prog_section_statement *code_statements;
636 extern int                    *code_linenums;
637 extern prog_section_def       *code_defs;
638 extern prog_section_field     *code_fields;
639 extern prog_section_function  *code_functions;
640 extern int                    *code_globals;
641 extern char                   *code_chars;
642 extern uint16_t code_crc;
643
644 /* uhh? */
645 typedef float   qcfloat;
646 typedef int32_t qcint;
647
648 /*
649  * code_write -- writes out the compiled file
650  * code_init  -- prepares the code file
651  */
652 bool     code_write       (const char *filename, const char *lno);
653 void     code_init        ();
654 uint32_t code_genstring   (const char *string);
655 uint32_t code_cachedstring(const char *string);
656 qcint    code_alloc_field (size_t qcsize);
657
658 /* this function is used to keep statements and linenumbers together */
659 void     code_push_statement(prog_section_statement *stmt, int linenum);
660 void     code_pop_statement();
661
662 /*
663  * A shallow copy of a lex_file to remember where which ast node
664  * came from.
665  */
666 typedef struct {
667     const char *file;
668     size_t      line;
669 } lex_ctx;
670
671 /*===================================================================*/
672 /*============================ con.c ================================*/
673 /*===================================================================*/
674 enum {
675     CON_BLACK   = 30,
676     CON_RED,
677     CON_GREEN,
678     CON_BROWN,
679     CON_BLUE,
680     CON_MAGENTA,
681     CON_CYAN ,
682     CON_WHITE
683 };
684
685 /* message level */
686 enum {
687     LVL_MSG,
688     LVL_WARNING,
689     LVL_ERROR
690 };
691
692 void con_vprintmsg (int level, const char *name, size_t line, const char *msgtype, const char *msg, va_list ap);
693 void con_printmsg  (int level, const char *name, size_t line, const char *msgtype, const char *msg, ...);
694 void con_cvprintmsg(void *ctx, int lvl, const char *msgtype, const char *msg, va_list ap);
695 void con_cprintmsg (void *ctx, int lvl, const char *msgtype, const char *msg, ...);
696
697 void con_close ();
698 void con_init  ();
699 void con_reset ();
700 void con_color (int);
701 int  con_change(const char *, const char *);
702 int  con_verr  (const char *, va_list);
703 int  con_vout  (const char *, va_list);
704 int  con_err   (const char *, ...);
705 int  con_out   (const char *, ...);
706
707 /* error/warning interface */
708 extern size_t compile_errors;
709 extern size_t compile_warnings;
710
711 void /********/ compile_error   (lex_ctx ctx, /*LVL_ERROR*/ const char *msg, ...);
712 void /********/ vcompile_error  (lex_ctx ctx, /*LVL_ERROR*/ const char *msg, va_list ap);
713 bool GMQCC_WARN compile_warning (lex_ctx ctx, int warntype, const char *fmt, ...);
714 bool GMQCC_WARN vcompile_warning(lex_ctx ctx, int warntype, const char *fmt, va_list ap);
715
716 /*===================================================================*/
717 /*========================= assembler.c =============================*/
718 /*===================================================================*/
719 /* TODO: remove this ... */
720 static const struct {
721     const char  *m; /* menomic     */
722     const size_t o; /* operands    */
723     const size_t l; /* menomic len */
724 } asm_instr[] = {
725     { "DONE"      , 1, 4 },
726     { "MUL_F"     , 3, 5 },
727     { "MUL_V"     , 3, 5 },
728     { "MUL_FV"    , 3, 6 },
729     { "MUL_VF"    , 3, 6 },
730     { "DIV"       , 0, 3 },
731     { "ADD_F"     , 3, 5 },
732     { "ADD_V"     , 3, 5 },
733     { "SUB_F"     , 3, 5 },
734     { "SUB_V"     , 3, 5 },
735     { "EQ_F"      , 0, 4 },
736     { "EQ_V"      , 0, 4 },
737     { "EQ_S"      , 0, 4 },
738     { "EQ_E"      , 0, 4 },
739     { "EQ_FNC"    , 0, 6 },
740     { "NE_F"      , 0, 4 },
741     { "NE_V"      , 0, 4 },
742     { "NE_S"      , 0, 4 },
743     { "NE_E"      , 0, 4 },
744     { "NE_FNC"    , 0, 6 },
745     { "LE"        , 0, 2 },
746     { "GE"        , 0, 2 },
747     { "LT"        , 0, 2 },
748     { "GT"        , 0, 2 },
749     { "FIELD_F"   , 0, 7 },
750     { "FIELD_V"   , 0, 7 },
751     { "FIELD_S"   , 0, 7 },
752     { "FIELD_ENT" , 0, 9 },
753     { "FIELD_FLD" , 0, 9 },
754     { "FIELD_FNC" , 0, 9 },
755     { "ADDRESS"   , 0, 7 },
756     { "STORE_F"   , 0, 7 },
757     { "STORE_V"   , 0, 7 },
758     { "STORE_S"   , 0, 7 },
759     { "STORE_ENT" , 0, 9 },
760     { "STORE_FLD" , 0, 9 },
761     { "STORE_FNC" , 0, 9 },
762     { "STOREP_F"  , 0, 8 },
763     { "STOREP_V"  , 0, 8 },
764     { "STOREP_S"  , 0, 8 },
765     { "STOREP_ENT", 0, 10},
766     { "STOREP_FLD", 0, 10},
767     { "STOREP_FNC", 0, 10},
768     { "RETURN"    , 0, 6 },
769     { "NOT_F"     , 0, 5 },
770     { "NOT_V"     , 0, 5 },
771     { "NOT_S"     , 0, 5 },
772     { "NOT_ENT"   , 0, 7 },
773     { "NOT_FNC"   , 0, 7 },
774     { "IF"        , 0, 2 },
775     { "IFNOT"     , 0, 5 },
776     { "CALL0"     , 1, 5 },
777     { "CALL1"     , 2, 5 },
778     { "CALL2"     , 3, 5 },
779     { "CALL3"     , 4, 5 },
780     { "CALL4"     , 5, 5 },
781     { "CALL5"     , 6, 5 },
782     { "CALL6"     , 7, 5 },
783     { "CALL7"     , 8, 5 },
784     { "CALL8"     , 9, 5 },
785     { "STATE"     , 0, 5 },
786     { "GOTO"      , 0, 4 },
787     { "AND"       , 0, 3 },
788     { "OR"        , 0, 2 },
789     { "BITAND"    , 0, 6 },
790     { "BITOR"     , 0, 5 },
791
792     { "END"       , 0, 3 } /* virtual assembler instruction */
793 };
794 /*===================================================================*/
795 /*============================= ir.c ================================*/
796 /*===================================================================*/
797
798 enum store_types {
799     store_global,
800     store_local,  /* local, assignable for now, should get promoted later */
801     store_param,  /* parameters, they are locals with a fixed position */
802     store_value,  /* unassignable */
803     store_return  /* unassignable, at OFS_RETURN */
804 };
805
806 typedef struct {
807     qcfloat x, y, z;
808 } vector;
809
810 vector  vec3_add  (vector, vector);
811 vector  vec3_sub  (vector, vector);
812 qcfloat vec3_mulvv(vector, vector);
813 vector  vec3_mulvf(vector, float);
814
815 /*===================================================================*/
816 /*============================= exec.c ==============================*/
817 /*===================================================================*/
818
819 /*
820  * Darkplaces has (or will have) a 64 bit prog loader
821  * where the 32 bit qc program is autoconverted on load.
822  * Since we may want to support that as well, let's redefine
823  * float and int here.
824  */
825 typedef union {
826     qcint   _int;
827     qcint    string;
828     qcint    function;
829     qcint    edict;
830     qcfloat _float;
831     qcfloat vector[3];
832     qcint   ivector[3];
833 } qcany;
834
835 typedef char qcfloat_size_is_correct [sizeof(qcfloat) == 4 ?1:-1];
836 typedef char qcint_size_is_correct   [sizeof(qcint)   == 4 ?1:-1];
837
838 enum {
839     VMERR_OK,
840     VMERR_TEMPSTRING_ALLOC,
841
842     VMERR_END
843 };
844
845 #define VM_JUMPS_DEFAULT 1000000
846
847 /* execute-flags */
848 #define VMXF_DEFAULT 0x0000     /* default flags - nothing */
849 #define VMXF_TRACE   0x0001     /* trace: print statements before executing */
850 #define VMXF_PROFILE 0x0002     /* profile: increment the profile counters */
851
852 struct qc_program_s;
853
854 typedef int (*prog_builtin)(struct qc_program_s *prog);
855
856 typedef struct {
857     qcint                  stmt;
858     size_t                 localsp;
859     prog_section_function *function;
860 } qc_exec_stack;
861
862 typedef struct qc_program_s {
863     char           *filename;
864
865     prog_section_statement *code;
866     prog_section_def       *defs;
867     prog_section_def       *fields;
868     prog_section_function  *functions;
869     char                   *strings;
870     qcint                  *globals;
871     qcint                  *entitydata;
872     bool                   *entitypool;
873
874     const char*            *function_stack;
875
876     uint16_t crc16;
877
878     size_t tempstring_start;
879     size_t tempstring_at;
880
881     qcint  vmerror;
882
883     size_t *profile;
884
885     prog_builtin *builtins;
886     size_t        builtins_count;
887
888     /* size_t ip; */
889     qcint  entities;
890     size_t entityfields;
891     bool   allowworldwrites;
892
893     qcint         *localstack;
894     qc_exec_stack *stack;
895     size_t statement;
896
897     size_t xflags;
898
899     int    argc; /* current arg count for debugging */
900 } qc_program;
901
902 qc_program* prog_load(const char *filename);
903 void        prog_delete(qc_program *prog);
904
905 bool prog_exec(qc_program *prog, prog_section_function *func, size_t flags, long maxjumps);
906
907 char*             prog_getstring (qc_program *prog, qcint str);
908 prog_section_def* prog_entfield  (qc_program *prog, qcint off);
909 prog_section_def* prog_getdef    (qc_program *prog, qcint off);
910 qcany*            prog_getedict  (qc_program *prog, qcint e);
911 qcint             prog_tempstring(qc_program *prog, const char *_str);
912
913
914 /*===================================================================*/
915 /*===================== parser.c commandline ========================*/
916 /*===================================================================*/
917
918 bool parser_init          ();
919 bool parser_compile_file  (const char *filename);
920 bool parser_compile_string(const char *name, const char *str);
921 bool parser_finish        (const char *output);
922 void parser_cleanup       ();
923 /* There's really no need to strlen() preprocessed files */
924 bool parser_compile_string_len(const char *name, const char *str, size_t len);
925
926 /*===================================================================*/
927 /*====================== ftepp.c commandline ========================*/
928 /*===================================================================*/
929 bool ftepp_init             ();
930 bool ftepp_preprocess_file  (const char *filename);
931 bool ftepp_preprocess_string(const char *name, const char *str);
932 void ftepp_finish           ();
933 const char *ftepp_get       ();
934 void ftepp_flush            ();
935 void ftepp_add_define       (const char *source, const char *name);
936 void ftepp_add_macro        (const char *name,   const char *value);
937
938 /*===================================================================*/
939 /*======================= main.c commandline ========================*/
940 /*===================================================================*/
941
942 #if 0
943 /* Helpers to allow for a whole lot of flags. Otherwise we'd limit
944  * to 32 or 64 -f options...
945  */
946 typedef struct {
947     size_t  idx; /* index into an array of 32 bit words */
948     uint8_t bit; /* index _into_ the 32 bit word, thus just uint8 */
949 } longbit;
950 #define LONGBIT(bit) { ((bit)/32), ((bit)%32) }
951 #else
952 typedef uint32_t longbit;
953 #define LONGBIT(bit) (bit)
954 #endif
955
956 /*===================================================================*/
957 /*============================= opts.c ==============================*/
958 /*===================================================================*/
959 typedef struct {
960     const char *name;
961     longbit     bit;
962 } opts_flag_def;
963
964 bool opts_setflag  (const char *, bool);
965 bool opts_setwarn  (const char *, bool);
966 bool opts_setwerror(const char *, bool);
967 bool opts_setoptim (const char *, bool);
968
969 void opts_init         (const char *, int, size_t);
970 void opts_set          (uint32_t   *, size_t, bool);
971 void opts_setoptimlevel(unsigned int);
972 void opts_ini_init     (const char *);
973
974 enum {
975 # define GMQCC_TYPE_FLAGS
976 # define GMQCC_DEFINE_FLAG(X) X,
977 #  include "opts.def"
978     COUNT_FLAGS
979 };
980 static const opts_flag_def opts_flag_list[] = {
981 # define GMQCC_TYPE_FLAGS
982 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(X) },
983 #  include "opts.def"
984     { NULL, LONGBIT(0) }
985 };
986
987 enum {
988 # define GMQCC_TYPE_WARNS
989 # define GMQCC_DEFINE_FLAG(X) WARN_##X,
990 #  include "opts.def"
991     COUNT_WARNINGS
992 };
993 static const opts_flag_def opts_warn_list[] = {
994 # define GMQCC_TYPE_WARNS
995 # define GMQCC_DEFINE_FLAG(X) { #X, LONGBIT(WARN_##X) },
996 #  include "opts.def"
997     { NULL, LONGBIT(0) }
998 };
999
1000 enum {
1001 # define GMQCC_TYPE_OPTIMIZATIONS
1002 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) OPTIM_##NAME,
1003 #  include "opts.def"
1004     COUNT_OPTIMIZATIONS
1005 };
1006 static const opts_flag_def opts_opt_list[] = {
1007 # define GMQCC_TYPE_OPTIMIZATIONS
1008 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) { #NAME, LONGBIT(OPTIM_##NAME) },
1009 #  include "opts.def"
1010     { NULL, LONGBIT(0) }
1011 };
1012 static const unsigned int opts_opt_oflag[] = {
1013 # define GMQCC_TYPE_OPTIMIZATIONS
1014 # define GMQCC_DEFINE_FLAG(NAME, MIN_O) MIN_O,
1015 #  include "opts.def"
1016     0
1017 };
1018 extern unsigned int opts_optimizationcount[COUNT_OPTIMIZATIONS];
1019
1020 /* other options: */
1021 typedef enum {
1022     COMPILER_QCC,     /* circa  QuakeC */
1023     COMPILER_FTEQCC,  /* fteqcc QuakeC */
1024     COMPILER_QCCX,    /* qccx   QuakeC */
1025     COMPILER_GMQCC    /* this   QuakeC */
1026 } opts_std_t;
1027
1028 typedef struct {
1029     uint32_t    O;              /* -Ox           */
1030     const char *output;         /* -o file       */
1031     bool        g;              /* -g            */
1032     opts_std_t  standard;       /* -std=         */
1033     bool        debug;          /* -debug        */
1034     bool        memchk;         /* -memchk       */
1035     bool        dumpfin;        /* -dumpfin      */
1036     bool        dump;           /* -dump         */
1037     bool        forcecrc;       /* --force-crc=  */
1038     uint16_t    forced_crc;     /* --force-crc=  */
1039     bool        pp_only;        /* -E            */
1040     size_t      max_array_size; /* --max-array=  */
1041
1042     uint32_t flags       [1 + (COUNT_FLAGS         / 32)];
1043     uint32_t warn        [1 + (COUNT_WARNINGS      / 32)];
1044     uint32_t werror      [1 + (COUNT_WARNINGS      / 32)];
1045     uint32_t optimization[1 + (COUNT_OPTIMIZATIONS / 32)];
1046 } opts_cmd_t;
1047
1048 extern opts_cmd_t opts;
1049
1050 /*===================================================================*/
1051 #define OPTS_FLAG(i)         (!! (opts.flags       [(i)/32] & (1<< ((i)%32))))
1052 #define OPTS_WARN(i)         (!! (opts.warn        [(i)/32] & (1<< ((i)%32))))
1053 #define OPTS_WERROR(i)       (!! (opts.werror      [(i)/32] & (1<< ((i)%32))))
1054 #define OPTS_OPTIMIZATION(i) (!! (opts.optimization[(i)/32] & (1<< ((i)%32))))
1055
1056 #endif