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