beginnings of REPL
[muddle-interpreter.git] / src / alloc.h
diff --git a/src/alloc.h b/src/alloc.h
new file mode 100644 (file)
index 0000000..239a7e0
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+Copyright (C) 2017 Keziah Wesley
+
+You can redistribute and/or modify this file under the terms of the
+GNU Affero General Public License as published by the Free Software
+Foundation, either version 3 of the License, or (at your option) any
+later version.
+
+This file is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public
+License along with this file. If not, see
+<http://www.gnu.org/licenses/>.
+*/
+
+#ifndef ALLOC_H
+#define ALLOC_H
+
+#include <assert.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+/// 0, or a "pointer" to an object allocated in the pool and fully-initialized
+typedef uint32_t pool_ptr;
+/// 0, or a "pointer" to an object allocated in the heap and fully-initialized
+typedef int32_t heap_ptr;
+
+typedef union pool_object pool_object;
+typedef union object object;
+
+extern char *pool;             // pool_object
+extern char *vhp_base;         // object
+extern char *vhp;              // object
+
+static inline pool_object *
+POOL_OBJECT (pool_ptr p)
+{
+  return (pool_object *) (uintptr_t) p;
+}
+
+static inline bool
+IS_VALID_POOL_OBJECT (pool_object * p)
+{
+  pool_ptr pp = (pool_ptr) (uintptr_t) p;
+  return (uintptr_t) pp == (uintptr_t) p;
+}
+
+static inline pool_ptr
+POOL_PTR (pool_object * p)
+{
+  pool_ptr pp = (pool_ptr) (uintptr_t) p;
+  assert (IS_VALID_POOL_OBJECT (p));
+  return pp;
+}
+
+// TODO make (heap_ptr)0 nullish
+static inline object *
+OBJECT_OF_HEAP_PTR (heap_ptr p)
+{
+  assert (p >= 0);
+  return (object *) (vhp_base + (p << 4));
+}
+
+static inline pool_object *
+pool_alloc (uint32_t len)
+{
+  char *pp = pool;
+  pool += (len << 4);
+  return (pool_object *) pp;
+}
+
+static inline heap_ptr
+HEAP_PTR_OF_OBJECT (object * p)
+{
+  assert ((uintptr_t) p >= (uintptr_t) vhp_base);
+  heap_ptr h = (heap_ptr) ((uintptr_t) p - (uintptr_t) vhp_base);
+  return h;
+}
+
+static inline object *
+heap_alloc (uint32_t len)
+{
+  enum
+  { DOPE_LEN = 1 };
+  char *p = vhp;
+  vhp += (len + DOPE_LEN) << 4;
+  return (object *) p;
+}
+
+// given a headerless array of objects of known size,
+// copy it backwards into newly-allocated pool space
+pool_ptr pool_copy_array_rev (const pool_object * objs, uint32_t len);
+
+// given a headerless array of objects of known size,
+// copy it backwards into a newly-allocated vector body
+heap_ptr heap_copy_array_rev (const object * objs, uint32_t len);
+
+#endif // ALLOC_H