beginnings of REPL
[muddle-interpreter.git] / src / alloc.h
1 /*
2 Copyright (C) 2017 Keziah Wesley
3
4 You can redistribute and/or modify this file under the terms of the
5 GNU Affero General Public License as published by the Free Software
6 Foundation, either version 3 of the License, or (at your option) any
7 later version.
8
9 This file is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Affero General Public License for more details.
13
14 You should have received a copy of the GNU Affero General Public
15 License along with this file. If not, see
16 <http://www.gnu.org/licenses/>.
17 */
18
19 #ifndef ALLOC_H
20 #define ALLOC_H
21
22 #include <assert.h>
23 #include <stdbool.h>
24 #include <stdint.h>
25
26 /// 0, or a "pointer" to an object allocated in the pool and fully-initialized
27 typedef uint32_t pool_ptr;
28 /// 0, or a "pointer" to an object allocated in the heap and fully-initialized
29 typedef int32_t heap_ptr;
30
31 typedef union pool_object pool_object;
32 typedef union object object;
33
34 extern char *pool;              // pool_object
35 extern char *vhp_base;          // object
36 extern char *vhp;               // object
37
38 static inline pool_object *
39 POOL_OBJECT (pool_ptr p)
40 {
41   return (pool_object *) (uintptr_t) p;
42 }
43
44 static inline bool
45 IS_VALID_POOL_OBJECT (pool_object * p)
46 {
47   pool_ptr pp = (pool_ptr) (uintptr_t) p;
48   return (uintptr_t) pp == (uintptr_t) p;
49 }
50
51 static inline pool_ptr
52 POOL_PTR (pool_object * p)
53 {
54   pool_ptr pp = (pool_ptr) (uintptr_t) p;
55   assert (IS_VALID_POOL_OBJECT (p));
56   return pp;
57 }
58
59 // TODO make (heap_ptr)0 nullish
60 static inline object *
61 OBJECT_OF_HEAP_PTR (heap_ptr p)
62 {
63   assert (p >= 0);
64   return (object *) (vhp_base + (p << 4));
65 }
66
67 static inline pool_object *
68 pool_alloc (uint32_t len)
69 {
70   char *pp = pool;
71   pool += (len << 4);
72   return (pool_object *) pp;
73 }
74
75 static inline heap_ptr
76 HEAP_PTR_OF_OBJECT (object * p)
77 {
78   assert ((uintptr_t) p >= (uintptr_t) vhp_base);
79   heap_ptr h = (heap_ptr) ((uintptr_t) p - (uintptr_t) vhp_base);
80   return h;
81 }
82
83 static inline object *
84 heap_alloc (uint32_t len)
85 {
86   enum
87   { DOPE_LEN = 1 };
88   char *p = vhp;
89   vhp += (len + DOPE_LEN) << 4;
90   return (object *) p;
91 }
92
93 // given a headerless array of objects of known size,
94 // copy it backwards into newly-allocated pool space
95 pool_ptr pool_copy_array_rev (const pool_object * objs, uint32_t len);
96
97 // given a headerless array of objects of known size,
98 // copy it backwards into a newly-allocated vector body
99 heap_ptr heap_copy_array_rev (const object * objs, uint32_t len);
100
101 #endif // ALLOC_H