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