navid/haze / commit

4aab20aa1d3f

Navid M <navidmomtahen@gmail.com> · 2026-12-02

parents: 9d1d3caf43f3

Browse files at this commit · Download source

all: initial implementation
--- /dev/null+++ b/.vnexclude@@ -0,0 +1,2 @@+build+.xmake--- /dev/null+++ b/runtime/xyzrt.cpp@@ -0,0 +1,1029 @@+#include "xyzrt.h"++#include <cstdarg>+#include <cstddef>+#include <cstdint>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <new>++#if defined(_WIN32)+#ifndef WIN32_LEAN_AND_MEAN+#define WIN32_LEAN_AND_MEAN+#endif+#include <windows.h>+#else+#include <sys/mman.h>+#include <unistd.h>+#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON)+#define MAP_ANONYMOUS MAP_ANON+#endif+#endif++namespace {++constexpr uint32_t GRANULE = 16;+constexpr uint32_t HEADER_SIZE = 8;+constexpr uint32_t LINE_SIZE = 128;+constexpr uint32_t BLOCK_SHIFT = 15;+constexpr uint32_t BLOCK_SIZE = 1u << BLOCK_SHIFT;+constexpr uint32_t LINES_PER_BLOCK = BLOCK_SIZE / LINE_SIZE;+constexpr uint32_t LARGE_THRESHOLD = 8192;+constexpr uint32_t NO_BLOCK = 0xffffffffu;+constexpr uint32_t MAX_TYPES = 1024;+constexpr uint32_t MAX_GLOBAL_ROOTS = 8192;+constexpr uint32_t MAX_PINNED = 8192;+constexpr uint32_t MAX_LARGE = 65536;+constexpr uint32_t MARK_STACK = 1u << 20;+constexpr uint64_t DEFAULT_HEAP = 64ull << 30;+constexpr uint64_t MIN_HEAP = 16ull << 20;++struct alignas(8) Header {+  uint32_t type_id;+  uint8_t mark;+  uint8_t flags;+  uint16_t aux;+};+static_assert(sizeof(Header) == 8, "Header must be 8 bytes");++enum HeaderFlags : uint8_t {+  PINNED = 1u << 0,+  REMEMBERED = 1u << 1,+  LARGE = 1u << 2,+};++enum class BlockState : uint8_t {+  FREE = 0,+  ALLOCATING,+  RECYCLABLE,+  FULL,+  EVAC_SOURCE,+  EVAC_TARGET,+  LOS_RESERVED,+};++struct BlockMeta {+  uint32_t next;+  uint16_t holes;+  uint16_t marked_lines;+  uint8_t state;+  uint8_t generation;+  uint8_t flags;+  uint8_t age;+  uint32_t owner;+};+static_assert(sizeof(BlockMeta) == 16, "BlockMeta must be 16 bytes");++struct TypeDesc {+  uint32_t size;+  uint16_t pointer_count;+  uint16_t flags;+  const uint32_t *pointer_offsets;+};++struct RootMap {+  uint32_t count;+  uint32_t frame_size;+  const uint32_t *offsets;+};++struct alignas(64) Mutator {+  void *cursor;+  void *limit;+  void *ocursor;+  void *olimit;+  void *nursery_cursor;+  void *nursery_limit;+  XyzRootFrame *root_frame;+  uint32_t thread_id;+  uint32_t flags;+  uint8_t poll;+  uint8_t reserved[7];+  uint32_t current_block;+  uint32_t overflow_block;+};++struct LargeObj {+  void *base;+  size_t size;+};++inline uint32_t align_up(uint32_t n, uint32_t a) {+  return (n + a - 1) & ~(a - 1);+}++inline uint64_t align_down64(uint64_t n, uint64_t a) {+  return n & ~(a - 1);+}++inline bool env_on(const char *name) {+  const char *v = std::getenv(name);+  return v && *v && std::strcmp(v, "0") != 0;+}++uint64_t env_u64(const char *name, uint64_t fallback) {+  const char *v = std::getenv(name);+  if (!v || !*v)+    return fallback;+  char *end = nullptr;+  unsigned long long n = std::strtoull(v, &end, 0);+  if (end == v)+    return fallback;+  if (*end == 'k' || *end == 'K')+    n <<= 10;+  else if (*end == 'm' || *end == 'M')+    n <<= 20;+  else if (*end == 'g' || *end == 'G')+    n <<= 30;+  return n;+}++#if defined(_WIN32)+void *os_reserve(size_t n) {+  return VirtualAlloc(nullptr, n, MEM_RESERVE, PAGE_NOACCESS);+}+bool os_commit(void *p, size_t n) {+  return VirtualAlloc(p, n, MEM_COMMIT, PAGE_READWRITE) != nullptr;+}+void *os_alloc_zeroed(size_t n) {+  return VirtualAlloc(nullptr, n, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);+}+void os_free(void *p, size_t) {+  if (p)+    VirtualFree(p, 0, MEM_RELEASE);+}+#else+void *os_reserve(size_t n) {+  int flags = MAP_PRIVATE | MAP_ANONYMOUS;+#ifdef MAP_NORESERVE+  flags |= MAP_NORESERVE;+#endif+  void *p = mmap(nullptr, n, PROT_NONE, flags, -1, 0);+  return p == MAP_FAILED ? nullptr : p;+}+bool os_commit(void *p, size_t n) {+  return mprotect(p, n, PROT_READ | PROT_WRITE) == 0;+}+void *os_alloc_zeroed(size_t n) {+  int flags = MAP_PRIVATE | MAP_ANONYMOUS;+#ifdef MAP_NORESERVE+  flags |= MAP_NORESERVE;+#endif+  void *p = mmap(nullptr, n, PROT_READ | PROT_WRITE, flags, -1, 0);+  return p == MAP_FAILED ? nullptr : p;+}+void os_free(void *p, size_t n) {+  if (p)+    munmap(p, n);+}+#endif++struct Heap {+  uint8_t *base = nullptr;+  size_t size = 0;+  uint32_t nblocks = 0;+  BlockMeta *meta = nullptr;+  uint8_t *line_marks = nullptr;+  uint32_t free_head = NO_BLOCK;+  uint32_t recyclable_head = NO_BLOCK;++  TypeDesc types[MAX_TYPES] = {};+  uint32_t ntypes = 1;++  uint8_t epoch = 1;+  bool initialized = false;+  bool log = false;+  bool verify_mode = false;+  bool poison = false;+  uint32_t stress_n = 0;+  uint32_t stress_counter = 0;+  uint64_t collections = 0;+  uint64_t allocations = 0;+  uint64_t live_lines_last = 0;++  Mutator main_mutator = {};+  Mutator *mutator = nullptr;++  LargeObj large[MAX_LARGE] = {};+  uint32_t nlarge = 0;++  void **global_roots[MAX_GLOBAL_ROOTS] = {};+  uint32_t nroots = 0;++  void *pinned[MAX_PINNED] = {};+  uint32_t npinned = 0;++  bool gc_requested = false;++  bool init();+  bool reserve_heap(size_t wanted);+  bool init_metadata();++  Mutator *current();+  uint32_t block_index(const void *p) const {+    return static_cast<uint32_t>(+        (static_cast<const uint8_t *>(p) - base) >> BLOCK_SHIFT);+  }+  bool in_heap(const void *p) const {+    uintptr_t a = reinterpret_cast<uintptr_t>(p);+    uintptr_t b = reinterpret_cast<uintptr_t>(base);+    return p && a >= b && a < b + size;+  }+  bool is_large_object(const void *p) const {+    for (uint32_t i = 0; i < nlarge; i++)+      if (large[i].base == p)+        return true;+    return false;+  }++  uint32_t type_for_size(uint32_t total);+  uint32_t register_type(uint32_t total, uint32_t ptr_count,+                         const uint32_t *offsets);++  void *allocate(uint32_t payload, uint32_t type_id);+  void *allocate_ordinary(uint32_t total, uint32_t type_id);+  void *allocate_large(uint32_t total, uint32_t type_id);+  uint32_t acquire_block();+  void push_free(uint32_t b);+  void push_recyclable(uint32_t b);+  bool try_alloc(Mutator *m, uint32_t total, uint32_t type_id, void **out);+  bool find_hole(Mutator *m, uint32_t total);++  void collect();+  void mark_roots();+  void mark_object(void *obj);+  void sweep();+  void reset_mutator(Mutator *m);+  void verify(bool after);++  void report(const char *fmt, ...);+};++Heap g_heap;+thread_local Mutator *tls_mutator = nullptr;++bool Heap::reserve_heap(size_t wanted) {+  size_t n = wanted;+  for (;;) {+    base = static_cast<uint8_t *>(os_reserve(n));+    if (base) {+      size = n;+      nblocks = static_cast<uint32_t>(n / BLOCK_SIZE);+      return true;+    }+    if (n <= MIN_HEAP)+      return false;+    n /= 2;+  }+}++bool Heap::init_metadata() {+  size_t line_bytes = static_cast<size_t>(nblocks) * LINES_PER_BLOCK;+  line_marks = static_cast<uint8_t *>(os_alloc_zeroed(line_bytes));+  meta = static_cast<BlockMeta *>(+      os_alloc_zeroed(static_cast<size_t>(nblocks) * sizeof(BlockMeta)));+  if (!line_marks || !meta)+    return false;++  for (uint32_t i = 0; i < nblocks; i++) {+    meta[i].next = (i + 1 < nblocks) ? i + 1 : NO_BLOCK;+    meta[i].state = static_cast<uint8_t>(BlockState::FREE);+    meta[i].owner = 0xffffffffu;+  }+  free_head = nblocks ? 0 : NO_BLOCK;+  recyclable_head = NO_BLOCK;++  types[0].size = 0;+  types[0].pointer_count = 0;+  types[0].flags = 0;+  types[0].pointer_offsets = nullptr;+  ntypes = 1;+  return true;+}++bool Heap::init() {+  if (initialized)+    return true;++  log = env_on("XYZ_GC_LOG");+  verify_mode = env_on("XYZ_GC_VERIFY");+  poison = env_on("XYZ_GC_POISON");+  stress_n = static_cast<uint32_t>(env_u64("XYZ_GC_STRESS", 0));++  uint64_t wanted = env_u64("XYZ_HEAP_SIZE", DEFAULT_HEAP);+  if (wanted < MIN_HEAP)+    wanted = MIN_HEAP;+  wanted = align_down64(wanted, BLOCK_SIZE);++  for (;;) {+    if (!reserve_heap(static_cast<size_t>(wanted))) {+      report("could not reserve a %llu-byte heap",+             static_cast<unsigned long long>(wanted));+      return false;+    }+    if (init_metadata())+      break;+    os_free(line_marks, static_cast<size_t>(nblocks) * LINES_PER_BLOCK);+    os_free(meta, static_cast<size_t>(nblocks) * sizeof(BlockMeta));+    line_marks = nullptr;+    meta = nullptr;+    os_free(base, size);+    base = nullptr;+    if (wanted <= MIN_HEAP) {+      report("could not allocate collector side metadata");+      return false;+    }+    wanted /= 2;+    wanted = align_down64(wanted, BLOCK_SIZE);+  }++  std::memset(&main_mutator, 0, sizeof(main_mutator));+  main_mutator.current_block = NO_BLOCK;+  main_mutator.overflow_block = NO_BLOCK;+  mutator = &main_mutator;+  tls_mutator = &main_mutator;+  initialized = true;++  if (log)+    report("heap: %llu bytes, %u blocks, %u lines/block",+           static_cast<unsigned long long>(size), nblocks, LINES_PER_BLOCK);+  return true;+}++Mutator *Heap::current() {+  if (!initialized)+    init();+  if (!tls_mutator) {+    tls_mutator = &main_mutator;+    mutator = &main_mutator;+  }+  return tls_mutator;+}++uint32_t Heap::type_for_size(uint32_t total) {+  total = align_up(total, GRANULE);+  for (uint32_t i = 1; i < ntypes; i++)+    if (types[i].size == total && types[i].pointer_count == 0)+      return i;+  if (ntypes >= MAX_TYPES) {+    report("type table exhausted");+    std::abort();+  }+  uint32_t id = ntypes++;+  types[id].size = total;+  types[id].pointer_count = 0;+  types[id].flags = 0;+  types[id].pointer_offsets = nullptr;+  return id;+}++uint32_t Heap::register_type(uint32_t total, uint32_t ptr_count,+                             const uint32_t *offsets) {+  total = align_up(total, GRANULE);+  for (uint32_t i = 1; i < ntypes; i++)+    if (types[i].size == total && types[i].pointer_count == ptr_count &&+        types[i].pointer_offsets == offsets)+      return i;+  if (ntypes >= MAX_TYPES) {+    report("type table exhausted");+    std::abort();+  }+  uint32_t id = ntypes++;+  types[id].size = total;+  types[id].pointer_count = static_cast<uint16_t>(ptr_count);+  types[id].flags = 0;+  types[id].pointer_offsets = offsets;+  return id;+}++void Heap::push_free(uint32_t b) {+  meta[b].next = free_head;+  meta[b].state = static_cast<uint8_t>(BlockState::FREE);+  meta[b].holes = LINES_PER_BLOCK;+  meta[b].marked_lines = 0;+  free_head = b;+}++void Heap::push_recyclable(uint32_t b) {+  meta[b].next = recyclable_head;+  meta[b].state = static_cast<uint8_t>(BlockState::RECYCLABLE);+  recyclable_head = b;+}++uint32_t Heap::acquire_block() {+  Mutator *m = current();+  for (;;) {+    uint32_t b = NO_BLOCK;+    if (recyclable_head != NO_BLOCK) {+      b = recyclable_head;+      recyclable_head = meta[b].next;+      meta[b].next = NO_BLOCK;+    } else if (free_head != NO_BLOCK) {+      b = free_head;+      free_head = meta[b].next;+      meta[b].next = NO_BLOCK;++      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+      if (!os_commit(block, BLOCK_SIZE)) {+        report("could not commit block %u", b);+        std::abort();+      }+      std::memset(block, 0, BLOCK_SIZE);+      std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0,+                  LINES_PER_BLOCK);+      meta[b].holes = LINES_PER_BLOCK;+      meta[b].marked_lines = 0;+    } else {+      return NO_BLOCK;+    }++    meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);+    meta[b].owner =+        static_cast<uint32_t>(reinterpret_cast<uintptr_t>(m) & 0xffffffffu);+    meta[b].age = 0;++    uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+    m->current_block = b;+    m->cursor = block;+    m->limit = block + BLOCK_SIZE;++    if (meta[b].marked_lines == 0) {+      std::memset(line_marks + static_cast<size_t>(b) * LINES_PER_BLOCK, 0,+                  LINES_PER_BLOCK);+      return b;+    }++    /* A recyclable block: find a hole.  mark_hole() will fail and we move on+     * when every line is live. */+    return b;+  }+}++bool Heap::find_hole(Mutator *m, uint32_t total) {+  uint32_t b = m->current_block;+  if (b == NO_BLOCK)+    return false;+  uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+  size_t off = static_cast<uint8_t *>(m->cursor) - block;+  if (off >= BLOCK_SIZE)+    return false;+  uint32_t line = static_cast<uint32_t>(off) / LINE_SIZE;+  uint32_t base_line = b * LINES_PER_BLOCK;++  while (line < LINES_PER_BLOCK) {+    if (line_marks[base_line + line] == epoch) {+      line++;+      continue;+    }+    uint32_t end = line;+    while (end < LINES_PER_BLOCK && line_marks[base_line + end] != epoch)+      end++;+    uint32_t bytes = (end - line) * LINE_SIZE;+    if (bytes >= total) {+      m->cursor = block + static_cast<size_t>(line) * LINE_SIZE;+      m->limit = block + static_cast<size_t>(end) * LINE_SIZE;+      return true;+    }+    line = end;+  }+  return false;+}++bool Heap::try_alloc(Mutator *m, uint32_t total, uint32_t type_id,+                     void **out) {+  uint8_t *p = static_cast<uint8_t *>(m->cursor);+  if (!p || p + total > static_cast<uint8_t *>(m->limit))+    return false;++  uint32_t b = m->current_block;+  if (b == NO_BLOCK)+    return false;++  uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+  uint32_t first_line = static_cast<uint32_t>(p - block) / LINE_SIZE;+  uint32_t last_line =+      static_cast<uint32_t>((p + total - 1) - block) / LINE_SIZE;+  uint32_t base_line = b * LINES_PER_BLOCK;++  m->cursor = p + total;++  Header *h = reinterpret_cast<Header *>(p);+  h->type_id = type_id;+  h->mark = 0;+  h->flags = 0;+  h->aux = 0;+  std::memset(p + HEADER_SIZE, 0, total - HEADER_SIZE);++  for (uint32_t line = first_line; line <= last_line; line++)+    line_marks[base_line + line] = epoch;++  meta[b].state = static_cast<uint8_t>(BlockState::ALLOCATING);+  allocations++;+  *out = p;+  return true;+}++void *Heap::allocate_large(uint32_t total, uint32_t type_id) {+  if (nlarge >= MAX_LARGE) {+    report("large object table exhausted");+    std::abort();+  }+  void *p = os_alloc_zeroed(total);+  if (!p)+    return nullptr;+  Header *h = static_cast<Header *>(p);+  h->type_id = type_id;+  h->mark = 0;+  h->flags = LARGE;+  h->aux = 0;+  large[nlarge].base = p;+  large[nlarge].size = total;+  nlarge++;+  allocations++;+  return p;+}++void *Heap::allocate_ordinary(uint32_t total, uint32_t type_id) {+  Mutator *m = current();++  for (uint32_t attempt = 0; attempt < 2; attempt++) {+    for (;;) {+      if (m->current_block != NO_BLOCK) {+        void *p = nullptr;+        if (try_alloc(m, total, type_id, &p))+          return p;+        if (find_hole(m, total) && try_alloc(m, total, type_id, &p))+          return p;+        meta[m->current_block].state = static_cast<uint8_t>(BlockState::FULL);+        m->current_block = NO_BLOCK;+        m->cursor = m->limit = nullptr;+      }++      uint32_t b = acquire_block();+      if (b == NO_BLOCK)+        break;+      m->current_block = b;+      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+      m->cursor = block;+      m->limit = block + BLOCK_SIZE;++      if (meta[b].marked_lines != 0) {+        void *p = nullptr;+        if (find_hole(m, total) && try_alloc(m, total, type_id, &p))+          return p;+        meta[b].state = static_cast<uint8_t>(BlockState::FULL);+        m->current_block = NO_BLOCK;+        m->cursor = m->limit = nullptr;+        continue;+      }++      void *p = nullptr;+      if (try_alloc(m, total, type_id, &p))+        return p;+      meta[b].state = static_cast<uint8_t>(BlockState::FULL);+      m->current_block = NO_BLOCK;+      m->cursor = m->limit = nullptr;+    }+    collect();+  }+  return nullptr;+}++void *Heap::allocate(uint32_t payload, uint32_t type_id) {+  init();++  if (stress_n) {+    if (++stress_counter >= stress_n) {+      stress_counter = 0;+      collect();+    }+  }++  uint32_t total;+  if (type_id == 0) {+    total = align_up(HEADER_SIZE + payload, GRANULE);+    type_id = type_for_size(total);+  } else {+    total = types[type_id].size;+    if (total < align_up(HEADER_SIZE + payload, GRANULE))+      total = align_up(HEADER_SIZE + payload, GRANULE);+  }++  if (total > LARGE_THRESHOLD) {+    void *p = allocate_large(total, type_id);+    if (!p) {+      collect();+      p = allocate_large(total, type_id);+    }+    return p;+  }++  void *p = allocate_ordinary(total, type_id);+  if (!p) {+    collect();+    p = allocate_ordinary(total, type_id);+  }+  if (!p) {+    report("out of heap after collection");+    std::abort();+  }+  return p;+}++void Heap::mark_object(void *obj) {+  static void *stack[MARK_STACK];+  size_t sp = 0;++  if (!obj)+    return;+  stack[sp++] = obj;++  while (sp) {+    void *p = stack[--sp];+    bool large_object = is_large_object(p);+    if (!in_heap(p) && !large_object)+      continue;+    if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))+      continue;++    Header *h = reinterpret_cast<Header *>(p);+    if (h->mark == epoch)+      continue;+    h->mark = epoch;++    if (!(h->flags & LARGE) && !large_object) {+      uint32_t b = block_index(p);+      uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+      uint32_t first = static_cast<uint32_t>(static_cast<uint8_t *>(p) - block) /+                       LINE_SIZE;+      uint32_t total = types[h->type_id].size;+      if (total == 0)+        continue;+      uint32_t last =+          static_cast<uint32_t>((static_cast<uint8_t *>(p) + total - 1) - block) /+          LINE_SIZE;+      uint32_t base_line = b * LINES_PER_BLOCK;+      for (uint32_t line = first; line <= last; line++)+        line_marks[base_line + line] = epoch;+    }++    const TypeDesc &td = types[h->type_id];+    if (td.pointer_count && td.pointer_offsets) {+      for (uint32_t i = 0; i < td.pointer_count; i++) {+        uint32_t off = td.pointer_offsets[i];+        void *child = nullptr;+        std::memcpy(&child, static_cast<uint8_t *>(p) + off, sizeof(child));+        if (child && sp < MARK_STACK)+          stack[sp++] = child;+      }+    }+  }+}++void Heap::mark_roots() {+  Mutator *m = current();++  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {+    if (!f->descriptor || !f->slots)+      continue;+    const RootMap *map = reinterpret_cast<const RootMap *>(f->descriptor);+    for (uint32_t i = 0; i < map->count; i++)+      mark_object(f->slots[i]);+  }++  for (uint32_t i = 0; i < nroots; i++) {+    if (global_roots[i])+      mark_object(*global_roots[i]);+  }++  for (uint32_t i = 0; i < npinned; i++)+    mark_object(pinned[i]);+}++void Heap::sweep() {+  uint64_t live_total = 0;++  for (uint32_t b = 0; b < nblocks; b++) {+    uint8_t state = meta[b].state;+    if (state == static_cast<uint8_t>(BlockState::FREE) ||+        state == static_cast<uint8_t>(BlockState::LOS_RESERVED))+      continue;++    uint32_t base_line = b * LINES_PER_BLOCK;+    uint32_t live = 0;+    for (uint32_t i = 0; i < LINES_PER_BLOCK; i++)+      if (line_marks[base_line + i] == epoch)+        live++;++    live_total += live;++    if (live == 0) {+      if (poison) {+        uint8_t *block = base + static_cast<size_t>(b) * BLOCK_SIZE;+        std::memset(block, 0xDD, BLOCK_SIZE);+      }+      push_free(b);+    } else if (live == LINES_PER_BLOCK) {+      meta[b].state = static_cast<uint8_t>(BlockState::FULL);+      meta[b].marked_lines = LINES_PER_BLOCK;+      meta[b].holes = 0;+    } else {+      uint32_t holes = 0;+      bool in_hole = false;+      for (uint32_t i = 0; i < LINES_PER_BLOCK; i++) {+        bool dead = line_marks[base_line + i] != epoch;+        if (dead && !in_hole) {+          holes++;+          in_hole = true;+        } else if (!dead) {+          in_hole = false;+        }+      }+      meta[b].marked_lines = static_cast<uint16_t>(live);+      meta[b].holes = static_cast<uint16_t>(holes);+      push_recyclable(b);+    }+  }++  for (uint32_t i = 0; i < nlarge;) {+    Header *h = static_cast<Header *>(large[i].base);+    if (h->mark != epoch) {+      os_free(large[i].base, large[i].size);+      large[i] = large[--nlarge];+    } else {+      i++;+    }+  }++  live_lines_last = live_total;+}++void Heap::reset_mutator(Mutator *m) {+  m->cursor = nullptr;+  m->limit = nullptr;+  m->ocursor = nullptr;+  m->olimit = nullptr;+  m->current_block = NO_BLOCK;+  m->overflow_block = NO_BLOCK;+}++void Heap::collect() {+  if (!init())+    return;++  if (verify_mode)+    verify(false);++  collections++;++  if (epoch == 255) {+    std::memset(line_marks, 0,+                static_cast<size_t>(nblocks) * LINES_PER_BLOCK);+    epoch = 1;+  } else {+    epoch++;+  }++  for (uint32_t i = 0; i < nlarge; i++) {+    Header *h = static_cast<Header *>(large[i].base);+    h->mark = 0;+  }++  /* Invalidating mutator cursors first is what makes the collection+   * stop-the-world even in the single-threaded M0 implementation. */+  reset_mutator(current());+  recyclable_head = NO_BLOCK;++  mark_roots();+  sweep();++  gc_requested = false;++  if (verify_mode)+    verify(true);++  if (log)+    report("gc #%llu epoch=%u live_lines=%llu large=%u free_head=%u",+           static_cast<unsigned long long>(collections), epoch,+           static_cast<unsigned long long>(live_lines_last), nlarge,+           free_head);+}++void Heap::verify(bool after) {+  if (!initialized)+    return;++  auto fail = [](const char *what) {+    std::fprintf(stderr, "xyzrt: heap verification failed: %s\n", what);+    std::abort();+  };++  Mutator *m = current();++  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {+    if (!f->descriptor || !f->slots)+      fail("root frame has no descriptor or slots");+    const RootMap *map = reinterpret_cast<const RootMap *>(f->descriptor);+    for (uint32_t i = 0; i < map->count; i++) {+      void *p = f->slots[i];+      if (!p)+        continue;+      if (!in_heap(p) && !is_large_object(p))+        fail("root slot points outside the heap");+      if (reinterpret_cast<uintptr_t>(p) & (GRANULE - 1))+        fail("root slot is not granule aligned");+      Header *h = static_cast<Header *>(p);+      if (h->type_id == 0)+        fail("root slot has no type descriptor");+      if (after && h->mark != epoch)+        fail("live root was not marked");+    }+  }++  for (uint32_t i = 0; i < nroots; i++)+    if (global_roots[i] && *global_roots[i] && !in_heap(*global_roots[i]))+      fail("global root points outside the heap");++  for (uint32_t i = 0; i < nlarge; i++)+    if (reinterpret_cast<uintptr_t>(large[i].base) & (GRANULE - 1))+      fail("large object is not granule aligned");++  for (uint32_t b = 0; b < nblocks; b++) {+    uint8_t state = meta[b].state;+    if (state > static_cast<uint8_t>(BlockState::LOS_RESERVED))+      fail("invalid block state");+    if (state != static_cast<uint8_t>(BlockState::FREE) &&+        state != static_cast<uint8_t>(BlockState::LOS_RESERVED) &&+        after && meta[b].marked_lines == 0 && meta[b].holes == LINES_PER_BLOCK)+      fail("allocated block has no marked lines");+  }+}++void Heap::report(const char *fmt, ...) {+  va_list ap;+  va_start(ap, fmt);+  std::vfprintf(stderr, fmt, ap);+  va_end(ap);+  std::fputc('\n', stderr);+}++} // namespace++extern "C" {++void xyz_runtime_init(void) { g_heap.init(); }++void *xyz_alloc_slow(uint32_t payload_size, uint32_t type_id) {+  return g_heap.allocate(payload_size, type_id);+}++void *xyz_alloc_large(uint32_t payload_size, uint32_t type_id) {+  g_heap.init();+  uint32_t total = align_up(HEADER_SIZE + payload_size, GRANULE);+  if (type_id == 0)+    type_id = g_heap.type_for_size(total);+  return g_heap.allocate_large(total, type_id);+}++uint32_t xyz_type_for_size(uint32_t total_size) {+  g_heap.init();+  return g_heap.type_for_size(total_size);+}++uint32_t xyz_register_type(uint32_t total_size, uint32_t pointer_count,+                           const uint32_t *pointer_offsets) {+  g_heap.init();+  return g_heap.register_type(total_size, pointer_count, pointer_offsets);+}++void xyz_gc_request(void) { g_heap.gc_requested = true; }++void xyz_gc_poll(void) {+  if (g_heap.gc_requested)+    g_heap.collect();+}++void xyz_gc_collect(void) { g_heap.collect(); }++void xyz_gc_verify(void) { g_heap.verify(true); }++int xyz_gc_object_alive(void *object) {+  if (!g_heap.initialized || !object)+    return 0;+  if (!g_heap.in_heap(object) && !g_heap.is_large_object(object))+    return 0;+  Header *h = static_cast<Header *>(object);+  return h->mark == g_heap.epoch;+}++void xyz_thread_attach(void) {+  g_heap.init();+  if (!tls_mutator) {+    Mutator *m = static_cast<Mutator *>(os_alloc_zeroed(sizeof(Mutator)));+    if (!m) {+      xyz_panic("could not allocate mutator");+      return;+    }+    m->current_block = NO_BLOCK;+    m->overflow_block = NO_BLOCK;+    tls_mutator = m;+  }+}++void xyz_thread_detach(void) { tls_mutator = nullptr; }++void xyz_root_enter(XyzRootFrame *frame) {+  if (!frame)+    return;+  Mutator *m = g_heap.current();+  frame->previous = m->root_frame;+  m->root_frame = frame;+}++void xyz_root_leave(XyzRootFrame *frame) {+  if (!frame)+    return;+  Mutator *m = g_heap.current();+  if (m->root_frame == frame) {+    m->root_frame = frame->previous;+    return;+  }+  for (XyzRootFrame *f = m->root_frame; f; f = f->previous) {+    if (f->previous == frame) {+      f->previous = frame->previous;+      return;+    }+  }+}++void xyz_root_add(void **slot) {+  g_heap.init();+  if (g_heap.nroots < MAX_GLOBAL_ROOTS)+    g_heap.global_roots[g_heap.nroots++] = slot;+}++void xyz_root_remove(void **slot) {+  for (uint32_t i = 0; i < g_heap.nroots; i++) {+    if (g_heap.global_roots[i] == slot) {+      g_heap.global_roots[i] = g_heap.global_roots[--g_heap.nroots];+      return;+    }+  }+}++void xyz_native_enter(void) {}+void xyz_native_exit(void) {}++void xyz_pin(void *object) {+  if (!object || !g_heap.in_heap(object))+    return;+  Header *h = static_cast<Header *>(object);+  h->flags |= PINNED;+  if (g_heap.npinned < MAX_PINNED)+    g_heap.pinned[g_heap.npinned++] = object;+}++void xyz_unpin(void *object) {+  if (!object)+    return;+  Header *h = static_cast<Header *>(object);+  h->flags &= ~PINNED;+  for (uint32_t i = 0; i < g_heap.npinned; i++) {+    if (g_heap.pinned[i] == object) {+      g_heap.pinned[i] = g_heap.pinned[--g_heap.npinned];+      return;+    }+  }+}++void xyz_wb(void *object, void **slot, void *value) {+  if (!object || !slot)+    return;+  *slot = value;+  Header *h = static_cast<Header *>(object);+  h->flags |= REMEMBERED;+}++void xyz_print_i32(int32_t value) { std::printf("%d\n", value); }++void xyz_print_i64(int64_t value) {+  std::printf("%lld\n", static_cast<long long>(value));+}++void xyz_print_bool(int32_t value) {+  std::fputs(value ? "true\n" : "false\n", stdout);+}++void xyz_print_str(const char *value) {+  std::fputs(value ? value : "", stdout);+  std::fputc('\n', stdout);+}++void xyz_panic(const char *message) {+  std::fprintf(stderr, "xyz: %s\n", message ? message : "panic");+  std::fflush(stderr);+  std::exit(1);+}++} // extern "C"--- /dev/null+++ b/runtime/xyzrt.h@@ -0,0 +1,61 @@+#ifndef XYZRT_H+#define XYZRT_H++#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++typedef struct XyzRootMap {+    uint32_t count;+    uint32_t frame_size;+    const uint32_t *offsets;+} XyzRootMap;++typedef struct XyzRootFrame {+    struct XyzRootFrame *previous;+    const XyzRootMap *descriptor;+    void **slots;+} XyzRootFrame;++/* Collector entry points.  All of these use the C ABI. */+void xyz_runtime_init(void);+void *xyz_alloc_slow(uint32_t payload_size, uint32_t type_id);+void *xyz_alloc_large(uint32_t payload_size, uint32_t type_id);+uint32_t xyz_type_for_size(uint32_t total_size);+uint32_t xyz_register_type(uint32_t total_size, uint32_t pointer_count,+                           const uint32_t *pointer_offsets);++void xyz_gc_poll(void);+void xyz_gc_request(void);+void xyz_gc_collect(void);+void xyz_gc_verify(void);+int xyz_gc_object_alive(void *object);++void xyz_thread_attach(void);+void xyz_thread_detach(void);++void xyz_root_enter(XyzRootFrame *frame);+void xyz_root_leave(XyzRootFrame *frame);+void xyz_root_add(void **slot);+void xyz_root_remove(void **slot);++void xyz_native_enter(void);+void xyz_native_exit(void);+void xyz_pin(void *object);+void xyz_unpin(void *object);+void xyz_wb(void *object, void **slot, void *value);++/* Small runtime used by generated programs. */+void xyz_print_i32(int32_t value);+void xyz_print_i64(int64_t value);+void xyz_print_bool(int32_t value);+void xyz_print_str(const char *value);+void xyz_panic(const char *message);++#ifdef __cplusplus+}+#endif++#endifBinary files a/samples/baseline/01_hello and b/samples/baseline/01_hello differBinary files a/samples/baseline/03_functions and b/samples/baseline/03_functions differ--- /dev/null+++ b/src/codegen.cpp@@ -0,0 +1,982 @@+#include "xyz.h"++#include <cassert>+#include <sstream>+#include <utility>++namespace xyz {++namespace {++struct Value {+  TypePtr ty;+  std::string s;+  bool valid = false;+};++struct Local {+  TypePtr ty;+  std::string slot;+  int root_index = -1;+};++struct LoopCtx {+  std::string break_label;+  std::string continue_label;+};++struct BlockOut {+  std::string label;+  std::vector<std::string> lines;+  bool terminated = false;+};++class Gen {+public:+  Gen(Program &p, std::string source_name)+      : program_(p), source_name_(std::move(source_name)) {+    for (auto &fn : program_.functions) {+      FuncSig sig;+      sig.ret = fn->ret;+      for (auto &p : fn->params)+        sig.params.push_back(p.type);+      sigs_[fn->name] = std::move(sig);+    }+  }++  std::string run() {+    for (auto &fn : program_.functions)+      gen_function(*fn);++    std::ostringstream out;+    out << "# generated by xyz from " << source_name_ << "\n\n";+    out << data_.str();+    out << funcs_.str();+    return out.str();+  }++private:+  Program &program_;+  std::string source_name_;+  SigMap sigs_;+  std::ostringstream data_;+  std::ostringstream funcs_;+  std::unordered_map<std::string, std::string> string_syms_;+  int string_counter_ = 0;+  int rootmap_counter_ = 0;++  Function *fn_ = nullptr;+  std::vector<BlockOut> blocks_;+  int cur_ = -1;+  int next_temp_ = 0;+  int next_slot_ = 0;+  int next_block_ = 0;+  std::vector<std::string> allocs_;+  std::vector<std::string> entry_;+  std::vector<std::unordered_map<std::string, Local>> scopes_;+  std::vector<LoopCtx> loops_;+  bool has_root_frame_ = false;+  std::string root_frame_;+  std::string root_slots_;+  std::string rootmap_sym_;+  std::string rootoffs_sym_;+  int root_count_ = 0;+  bool word_return_ = false;+  bool has_post_ = false;+  bool checking_post_ = false;+  std::unordered_map<std::string, std::string> post_slots_;++  std::string new_temp() { return "%t" + std::to_string(next_temp_++); }++  std::string new_label(const std::string &hint) {+    (void)hint;+    return "@bb" + std::to_string(next_block_++);+  }++  void emit(const std::string &line) {+    assert(cur_ >= 0);+    blocks_[cur_].lines.push_back(line);+  }++  void emit_entry(const std::string &line) { entry_.push_back(line); }++  bool terminated() const { return cur_ >= 0 && blocks_[cur_].terminated; }++  void start_block(const std::string &label) {+    if (cur_ >= 0 && !blocks_[cur_].terminated) {+      emit("jmp " + label);+      blocks_[cur_].terminated = true;+    }+    BlockOut b;+    b.label = label;+    blocks_.push_back(std::move(b));+    cur_ = static_cast<int>(blocks_.size()) - 1;+  }++  void jump(const std::string &label) {+    emit("jmp " + label);+    blocks_[cur_].terminated = true;+  }++  void branch(const Value &cond, const std::string &t, const std::string &f) {+    emit("jnz " + cond.s + ", " + t + ", " + f);+    blocks_[cur_].terminated = true;+  }++  std::string alloc_slot(TypePtr ty) {+    std::string s = "%s" + std::to_string(next_slot_++);+    bool wide = qbe_type(ty) == "l";+    allocs_.push_back(s + " =l alloc" + (wide ? "8" : "4") + " " ++                      (wide ? "8" : "4"));+    return s;+  }++  Value load_slot(const std::string &slot, TypePtr ty) {+    std::string t = new_temp();+    emit(t + " =" + qbe_type(ty) + " load" + (qbe_type(ty) == "l" ? "l" : "w") ++         " " + slot);+    return Value{ty, t, true};+  }++  Value coerce(Value v, TypePtr to) {+    if (!v.valid || !to || same_type(v.ty, to))+      return v;+    if (to->kind == Type::Kind::I64 && v.ty &&+        v.ty->kind == Type::Kind::I32) {+      std::string t = new_temp();+      emit(t + " =l extsw " + v.s);+      return Value{to, t, true};+    }+    return v;+  }++  std::string store_suffix(TypePtr ty) {+    return qbe_type(ty) == "l" ? "l" : "w";+  }++  void store_local(const Local &l, Value v) {+    v = coerce(v, l.ty);+    emit("store" + store_suffix(l.ty) + " " + v.s + ", " + l.slot);+    if (l.root_index >= 0)+      store_root(l.root_index, v);+  }++  void store_root(int index, const Value &v) {+    std::string addr = new_temp();+    emit(addr + " =l add " + root_slots_ + ", " ++         std::to_string(index * 8));+    emit("storel " + v.s + ", " + addr);+  }++  Local *lookup_local(const std::string &name) {+    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {+      auto f = it->find(name);+      if (f != it->end())+        return &f->second;+    }+    return nullptr;+  }++  void push_scope() { scopes_.emplace_back(); }+  void pop_scope() { scopes_.pop_back(); }++  Local &declare_local(const std::string &name, TypePtr ty, Value init) {+    Local l;+    l.ty = ty;+    l.slot = alloc_slot(ty);+    if (is_managed(ty)) {+      if (root_count_ >= 64)+        throw Error(fn_->pos, "too many managed locals in function '" ++                                  fn_->name + "'");+      l.root_index = root_count_++;+    }+    scopes_.back()[name] = l;+    store_local(scopes_.back()[name], std::move(init));+    return scopes_.back()[name];+  }++  std::string intern_string(const std::string &s) {+    auto it = string_syms_.find(s);+    if (it != string_syms_.end())+      return it->second;+    std::string sym = "xyz_str_" + std::to_string(string_counter_++);+    data_ << "data $" << sym << " = { b";+    if (s.empty()) {+      data_ << " 0";+    } else {+      for (unsigned char c : s)+        data_ << " " << static_cast<unsigned>(c);+      data_ << " 0";+    }+    data_ << " }\n\n";+    string_syms_[s] = sym;+    return sym;+  }++  void panic_block(const std::string &message) {+    std::string sym = intern_string(message);+    emit("call $xyz_panic(l $" + sym + ")");+    emit("hlt");+    blocks_[cur_].terminated = true;+  }++  void gen_pre_checks() {+    for (auto &c : fn_->contracts) {+      if (c.kind != Contract::Kind::Pre)+        continue;+      Value v = gen_expr(*c.expr);+      std::string ok = new_label("pre.ok");+      std::string fail = new_label("pre.fail");+      branch(v, ok, fail);+      start_block(fail);+      panic_block("precondition failed");+      start_block(ok);+    }+  }++  void gen_post_checks(Value v) {+    for (auto &entry : post_slots_)+      store_local(Local{fn_->ret, entry.second, -1}, v);+    for (auto &c : fn_->contracts) {+      if (c.kind != Contract::Kind::Post)+        continue;+      Value okv = gen_expr(*c.expr);+      std::string ok = new_label("post.ok");+      std::string fail = new_label("post.fail");+      branch(okv, ok, fail);+      start_block(fail);+      panic_block("postcondition failed");+      start_block(ok);+    }+  }++  void emit_ret(Value v, bool has_value) {+    if (has_value && has_post_ && !checking_post_) {+      checking_post_ = true;+      gen_post_checks(v);+      checking_post_ = false;+    }+    if (has_root_frame_)+      emit("call $xyz_root_leave(l " + root_frame_ + ")");+    if (has_value)+      emit("ret " + v.s);+    else+      emit("ret");+    blocks_[cur_].terminated = true;+  }++  void emit_ret_void() {+    if (word_return_)+      emit_ret(Value{t_i32(), "0", true}, true);+    else+      emit_ret(Value{}, false);+  }++  bool expr_has_managed(const Expr &e) {+    if (e.kind == Expr::Kind::If) {+      if (e.then_e && e.then_e->kind == Expr::Kind::Block && e.then_e->block &&+          block_has_managed(*e.then_e->block))+        return true;+      if (e.else_e && e.else_e->kind == Expr::Kind::Block && e.else_e->block &&+          block_has_managed(*e.else_e->block))+        return true;+      if (e.else_e && e.else_e->kind == Expr::Kind::If &&+          expr_has_managed(*e.else_e))+        return true;+    }+    if (e.kind == Expr::Kind::Block && e.block &&+        block_has_managed(*e.block))+      return true;+    return false;+  }++  bool block_has_managed(const Block &b) {+    for (auto &s : b.stmts) {+      if (s->kind == Stmt::Kind::Let || s->kind == Stmt::Kind::Var) {+        TypePtr t = s->decl_type ? s->decl_type : s->expr->ty;+        if (is_managed(t))+          return true;+      }+      if ((s->kind == Stmt::Kind::ForRange ||+           s->kind == Stmt::Kind::ForCond || s->kind == Stmt::Kind::Block) &&+          s->block && block_has_managed(*s->block))+        return true;+      if (s->kind == Stmt::Kind::Expr && s->expr &&+          expr_has_managed(*s->expr))+        return true;+      if (s->kind == Stmt::Kind::Assign && s->expr &&+          expr_has_managed(*s->expr))+        return true;+    }+    return false;+  }++  bool function_has_managed(const Function &fn) {+    for (auto &p : fn.params)+      if (is_managed(p.type))+        return true;+    if (fn.body && block_has_managed(*fn.body))+      return true;+    return false;+  }++  void emit_root_frame_init() {+    root_frame_ = new_temp();+    root_slots_ = new_temp();+    rootmap_sym_ = "xyz_rootmap_" + std::to_string(rootmap_counter_++);+    rootoffs_sym_ = "xyz_rootoffs_" + std::to_string(rootmap_counter_ - 1);++    allocs_.push_back(root_frame_ + " =l alloc16 24");+    allocs_.push_back(root_slots_ + " =l alloc16 512");++    for (int i = 0; i < 64; i++) {+      std::string a = new_temp();+      emit_entry(a + " =l add " + root_slots_ + ", " ++                 std::to_string(i * 8));+      emit_entry("storel 0, " + a);+    }++    std::string a = new_temp();+    emit_entry(a + " =l add " + root_frame_ + ", 0");+    emit_entry("storel 0, " + a);++    a = new_temp();+    emit_entry(a + " =l add " + root_frame_ + ", 8");+    emit_entry("storel $" + rootmap_sym_ + ", " + a);++    a = new_temp();+    emit_entry(a + " =l add " + root_frame_ + ", 16");+    emit_entry("storel " + root_slots_ + ", " + a);++    emit_entry("call $xyz_root_enter(l " + root_frame_ + ")");+  }++  void emit_root_map() {+    data_ << "data $" << rootmap_sym_ << " = { w " << root_count_+          << ", w 24, l $" << rootoffs_sym_ << " }\n";+    data_ << "data $" << rootoffs_sym_ << " = { w";+    if (root_count_ == 0)+      data_ << " 0";+    else+      for (int i = 0; i < root_count_; i++)+        data_ << " " << (i * 8);+    data_ << " }\n\n";+  }++  void gen_function(Function &fn) {+    fn_ = &fn;+    blocks_.clear();+    cur_ = -1;+    next_temp_ = 0;+    next_slot_ = 0;+    next_block_ = 1;+    allocs_.clear();+    entry_.clear();+    scopes_.clear();+    loops_.clear();+    root_count_ = 0;+    has_post_ = false;+    checking_post_ = false;+    post_slots_.clear();+    has_root_frame_ = function_has_managed(fn);+    word_return_ = (fn.name == "main") ||+                   (fn.ret && fn.ret->kind != Type::Kind::Void);++    if (fn.name == "main" && !fn.params.empty())+      throw Error(fn.pos, "main cannot take arguments in this milestone");+    if (fn.body == nullptr && fn.arrow == nullptr)+      throw Error(fn.pos, "function has no body");++    push_scope();+    start_block("@start");++    if (has_root_frame_)+      emit_root_frame_init();++    for (size_t i = 0; i < fn.params.size(); i++) {+      const Param &p = fn.params[i];+      Local l;+      l.ty = p.type;+      l.slot = alloc_slot(p.type);+      if (is_managed(p.type)) {+        if (root_count_ >= 64)+          throw Error(fn.pos, "too many managed parameters");+        l.root_index = root_count_++;+      }+      scopes_.back()[p.name] = l;+      std::string pv = "%p" + std::to_string(i);+      entry_.push_back("store" + store_suffix(p.type) + " " + pv + ", " ++                       l.slot);+      if (l.root_index >= 0) {+        std::string a = new_temp();+        entry_.push_back(a + " =l add " + root_slots_ + ", " ++                         std::to_string(l.root_index * 8));+        entry_.push_back("storel " + pv + ", " + a);+      }+    }++    for (auto &c : fn.contracts) {+      if (c.kind != Contract::Kind::Post)+        continue;+      has_post_ = true;+      if (!c.result_name.empty() && !post_slots_.count(c.result_name)) {+        std::string slot = alloc_slot(fn.ret);+        Local l;+        l.ty = fn.ret;+        l.slot = slot;+        if (is_managed(fn.ret)) {+          if (!has_root_frame_)+            throw Error(fn.pos, "managed contract result needs a root frame");+          if (root_count_ >= 64)+            throw Error(fn.pos, "too many managed locals");+          l.root_index = root_count_++;+        }+        scopes_.back()[c.result_name] = l;+        post_slots_[c.result_name] = slot;+      }+    }++    gen_pre_checks();++    if (fn.arrow) {+      Value v = gen_expr(*fn.arrow);+      v = coerce(v, fn.ret);+      emit_ret(v, true);+    } else {+      if (fn.ret->kind == Type::Kind::Void) {+        gen_block_stmt(*fn.body);+        if (!terminated())+          emit_ret_void();+      } else {+        Value v = gen_block_value(*fn.body);+        if (!terminated()) {+          if (v.valid) {+            v = coerce(v, fn.ret);+            emit_ret(v, true);+          } else {+            emit_ret(Value{fn.ret, "0", true}, true);+          }+        }+      }+    }++    pop_scope();++    if (has_root_frame_)+      emit_root_map();++    std::ostringstream f;+    if (fn.name == "main")+      f << "export function w $main(";+    else {+      f << "function";+      if (fn.ret && fn.ret->kind != Type::Kind::Void)+        f << " " << qbe_type(fn.ret);+      f << " $xyz_" << fn.name << "(";+    }+    for (size_t i = 0; i < fn.params.size(); i++) {+      if (i)+        f << ", ";+      f << qbe_type(fn.params[i].type) << " %p" << i;+    }+    f << ") {\n";++    auto write_block = [&](const BlockOut &b, bool first) {+      f << b.label << "\n";+      if (first) {+        for (auto &a : allocs_)+          f << "\t" << a << "\n";+        for (auto &a : entry_)+          f << "\t" << a << "\n";+      }+      for (auto &line : b.lines)+        f << "\t" << line << "\n";+    };++    if (blocks_.empty()) {+      /* Unreachable: every function has @start. */+      f << "@start\n\tret\n";+    } else {+      write_block(blocks_[0], true);+      for (size_t i = 1; i < blocks_.size(); i++)+        write_block(blocks_[i], false);+    }+    f << "}\n\n";+    funcs_ << f.str();+  }++  Value gen_block_value(Block &b) {+    push_scope();+    Value result;+    for (size_t i = 0; i < b.stmts.size(); i++) {+      if (terminated())+        break;+      if (i + 1 == b.stmts.size() && b.stmts[i]->kind == Stmt::Kind::Expr) {+        result = gen_expr(*b.stmts[i]->expr);+      } else {+        gen_stmt(*b.stmts[i]);+      }+    }+    pop_scope();+    return result;+  }++  void gen_block_stmt(Block &b) {+    push_scope();+    for (auto &s : b.stmts) {+      if (terminated())+        break;+      gen_stmt(*s);+    }+    pop_scope();+  }++  Value gen_expr(Expr &e) {+    switch (e.kind) {+    case Expr::Kind::Int:+      return Value{e.ty, std::to_string(e.ival), true};+    case Expr::Kind::Bool:+      return Value{e.ty, e.bval ? "1" : "0", true};+    case Expr::Kind::String: {+      std::string sym = intern_string(e.text);+      return Value{e.ty, "$" + sym, true};+    }+    case Expr::Kind::Var: {+      Local *l = lookup_local(e.text);+      if (!l)+        throw Error(e.pos, "undefined variable '" + e.text + "'");+      return load_slot(l->slot, l->ty);+    }+    case Expr::Kind::Unary:+      return gen_unary(e);+    case Expr::Kind::Binary:+      return gen_binary(e);+    case Expr::Kind::Call:+      return gen_call(e);+    case Expr::Kind::If:+      return gen_if(e);+    case Expr::Kind::Block:+      return gen_block_value(*e.block);+    default:+      throw Error(e.pos, "unsupported expression");+    }+  }++  Value gen_unary(Expr &e) {+    Value v = gen_expr(*e.lhs);+    if (e.op == "-") {+      v = coerce(v, e.ty);+      std::string t = new_temp();+      emit(t + " =" + qbe_type(e.ty) + " sub 0, " + v.s);+      return Value{e.ty, t, true};+    }+    std::string t = new_temp();+    emit(t + " =w ceqw " + v.s + ", 0");+    return Value{t_bool(), t, true};+  }++  Value gen_binary(Expr &e) {+    if (e.op == "&&" || e.op == "||")+      return gen_logic(e);++    Value a = gen_expr(*e.lhs);+    Value b = gen_expr(*e.rhs);++    if (e.op == "+" || e.op == "-" || e.op == "*" || e.op == "/" ||+        e.op == "%") {+      TypePtr ty = e.ty;+      a = coerce(a, ty);+      b = coerce(b, ty);+      std::string ins = e.op == "+"   ? "add"+                        : e.op == "-" ? "sub"+                        : e.op == "*" ? "mul"+                        : e.op == "/" ? "div"+                                      : "rem";+      std::string t = new_temp();+      emit(t + " =" + qbe_type(ty) + " " + ins + " " + a.s + ", " + b.s);+      return Value{ty, t, true};+    }++    if (e.op == "==" || e.op == "!=") {+      TypePtr ty = a.ty;+      if (ty && ty->kind != Type::Kind::Str) {+        if (a.ty->kind == Type::Kind::I64 || b.ty->kind == Type::Kind::I64) {+          a = coerce(a, t_i64());+          b = coerce(b, t_i64());+          ty = t_i64();+        }+      }+      if (ty && ty->kind == Type::Kind::Str) {+        std::string t = new_temp();+        emit(t + " =w call $strcmp(l " + a.s + ", l " + b.s + ")");+        std::string q = new_temp();+        emit(q + " =w " + (e.op == "==" ? "ceqw " : "cnew ") + t + ", 0");+        return Value{t_bool(), q, true};+      }+      std::string base = qbe_type(ty);+      std::string ins = e.op == "==" ? "ceq" : "cne";+      std::string t = new_temp();+      emit(t + " =w " + ins + base + " " + a.s + ", " + b.s);+      return Value{t_bool(), t, true};+    }++    std::string ins;+    if (e.op == "<")+      ins = "cslt";+    else if (e.op == "<=")+      ins = "csle";+    else if (e.op == ">")+      ins = "csgt";+    else+      ins = "csge";+    TypePtr ty = a.ty;+    if (a.ty->kind == Type::Kind::I64 || b.ty->kind == Type::Kind::I64) {+      a = coerce(a, t_i64());+      b = coerce(b, t_i64());+      ty = t_i64();+    }+    std::string t = new_temp();+    emit(t + " =w " + ins + qbe_type(ty) + " " + a.s + ", " + b.s);+    return Value{t_bool(), t, true};+  }++  Value gen_logic(Expr &e) {+    bool is_and = e.op == "&&";+    std::string slot = alloc_slot(t_bool());+    std::string rhs = new_label("rhs");+    std::string other = new_label("other");+    std::string end = new_label("end");++    Value a = gen_expr(*e.lhs);+    if (is_and)+      branch(a, rhs, other);+    else+      branch(a, other, rhs);++    if (is_and) {+      start_block(rhs);+      Value b = gen_expr(*e.rhs);+      store_local(Local{t_bool(), slot, -1}, b);+      jump(end);++      start_block(other);+      store_local(Local{t_bool(), slot, -1}, Value{t_bool(), "0", true});+      jump(end);+    } else {+      start_block(other);+      store_local(Local{t_bool(), slot, -1}, Value{t_bool(), "1", true});+      jump(end);++      start_block(rhs);+      Value b = gen_expr(*e.rhs);+      store_local(Local{t_bool(), slot, -1}, b);+      jump(end);+    }++    start_block(end);+    return load_slot(slot, t_bool());+  }++  Value gen_if(Expr &e) {+    Value cond = gen_expr(*e.cond);+    TypePtr rt = e.ty;+    bool want = rt && rt->kind != Type::Kind::Void;+    std::string slot;+    if (want)+      slot = alloc_slot(rt);++    std::string then_l = new_label("then");+    std::string else_l = new_label("else");+    std::string end_l = new_label("endif");++    branch(cond, then_l, else_l);++    start_block(then_l);+    Value a = gen_branch_value(*e.then_e);+    if (!terminated()) {+      if (want) {+        a = coerce(a, rt);+        store_local(Local{rt, slot, -1}, a);+      }+      jump(end_l);+    }++    start_block(else_l);+    if (e.else_e) {+      Value b = gen_branch_value(*e.else_e);+      if (!terminated()) {+        if (want) {+          b = coerce(b, rt);+          store_local(Local{rt, slot, -1}, b);+        }+        jump(end_l);+      }+    } else {+      jump(end_l);+    }++    start_block(end_l);+    if (want)+      return load_slot(slot, rt);+    return Value{};+  }++  Value gen_branch_value(Expr &e) {+    if (e.kind == Expr::Kind::Block)+      return gen_block_value(*e.block);+    return gen_expr(e);+  }++  Value gen_call(Expr &e) {+    if (e.lhs->kind != Expr::Kind::Var)+      throw Error(e.pos, "only named functions can be called");+    const std::string &name = e.lhs->text;++    std::vector<Value> args;+    for (auto &a : e.args)+      args.push_back(gen_expr(*a));++    auto call = [&](const std::string &sym, const std::vector<TypePtr> &types,+                    TypePtr ret) -> Value {+      std::ostringstream s;+      if (ret && ret->kind != Type::Kind::Void)+        s << new_temp() << " =" << qbe_type(ret) << " ";+      s << "call $" << sym << "(";+      for (size_t i = 0; i < args.size(); i++) {+        if (i)+          s << ", ";+        Value v = coerce(args[i], types[i]);+        s << qbe_type(types[i]) << " " << v.s;+      }+      s << ")";+      emit(s.str());+      if (ret && ret->kind != Type::Kind::Void) {+        std::string t = s.str();+        auto pos = t.find(" =");+        return Value{ret, t.substr(0, pos), true};+      }+      return Value{};+    };++    if (name == "print") {+      TypePtr t = args[0].ty;+      if (t->kind == Type::Kind::I32)+        return call("xyz_print_i32", {t_i32()}, t_void());+      if (t->kind == Type::Kind::I64)+        return call("xyz_print_i64", {t_i64()}, t_void());+      if (t->kind == Type::Kind::Bool)+        return call("xyz_print_bool", {t_bool()}, t_void());+      return call("xyz_print_str", {t_str()}, t_void());+    }++    if (name == "__gc_alloc") {+      args.push_back(Value{t_i32(), "0", true});+      return call("xyz_alloc_slow", {t_i32(), t_i32()}, t_ptr());+    }++    if (name == "__gc_store") {+      Value p = coerce(args[0], t_ptr());+      Value off = coerce(args[1], t_i64());+      Value val = coerce(args[2], t_ptr());+      std::string addr = new_temp();+      emit(addr + " =l add " + p.s + ", " + off.s);+      emit("storel " + val.s + ", " + addr);+      return Value{};+    }++    if (name == "__gc_load") {+      Value p = coerce(args[0], t_ptr());+      Value off = coerce(args[1], t_i64());+      std::string addr = new_temp();+      emit(addr + " =l add " + p.s + ", " + off.s);+      std::string v = new_temp();+      emit(v + " =l loadl " + addr);+      return Value{t_ptr(), v, true};+    }++    if (name == "__gc_alive")+      return call("xyz_gc_object_alive", {t_ptr()}, t_bool());++    if (name == "__gc_collect")+      return call("xyz_gc_collect", {}, t_void());++    if (name == "__gc_verify")+      return call("xyz_gc_verify", {}, t_void());++    if (name == "__gc_pin")+      return call("xyz_pin", {t_ptr()}, t_void());++    if (name == "__gc_unpin")+      return call("xyz_unpin", {t_ptr()}, t_void());++    auto it = sigs_.find(name);+    if (it == sigs_.end())+      throw Error(e.pos, "unknown function '" + name + "'");+    const FuncSig &sig = it->second;+    std::ostringstream s;+    if (sig.ret->kind != Type::Kind::Void)+      s << new_temp() << " =" << qbe_type(sig.ret) << " ";+    s << "call $" << (name == "main" ? "main" : ("xyz_" + name)) << "(";+    for (size_t i = 0; i < args.size(); i++) {+      if (i)+        s << ", ";+      Value v = coerce(args[i], sig.params[i]);+      s << qbe_type(sig.params[i]) << " " << v.s;+    }+    s << ")";+    emit(s.str());+    if (sig.ret->kind != Type::Kind::Void) {+      std::string full = s.str();+      auto pos = full.find(" =");+      return Value{sig.ret, full.substr(0, pos), true};+    }+    return Value{};+  }++  void gen_stmt(Stmt &s) {+    switch (s.kind) {+    case Stmt::Kind::Let:+    case Stmt::Kind::Var: {+      Value v = gen_expr(*s.expr);+      TypePtr ty = s.decl_type ? s.decl_type : s.expr->ty;+      v = coerce(v, ty);+      declare_local(s.name, ty, v);+      break;+    }+    case Stmt::Kind::Assign: {+      if (s.expr->kind != Expr::Kind::Var)+        throw Error(s.pos, "assignment target must be a variable");+      Local *l = lookup_local(s.expr->text);+      if (!l)+        throw Error(s.pos, "undefined variable '" + s.expr->text + "'");+      if (s.op == "=") {+        Value v = gen_expr(*s.rhs);+        store_local(*l, coerce(v, l->ty));+      } else {+        Value old = load_slot(l->slot, l->ty);+        Value rhs = gen_expr(*s.rhs);+        rhs = coerce(rhs, l->ty);+        std::string ins = s.op == "+="   ? "add"+                          : s.op == "-=" ? "sub"+                          : s.op == "*=" ? "mul"+                          : s.op == "/=" ? "div"+                                         : "rem";+        std::string t = new_temp();+        emit(t + " =" + qbe_type(l->ty) + " " + ins + " " + old.s + ", " ++             rhs.s);+        store_local(*l, Value{l->ty, t, true});+      }+      break;+    }+    case Stmt::Kind::Return: {+      if (s.expr) {+        Value v = gen_expr(*s.expr);+        v = coerce(v, fn_->ret);+        emit_ret(v, true);+      } else {+        emit_ret_void();+      }+      break;+    }+    case Stmt::Kind::ForRange:+      gen_for_range(s);+      break;+    case Stmt::Kind::ForCond:+      gen_for_cond(s);+      break;+    case Stmt::Kind::Break:+      jump(loops_.back().break_label);+      break;+    case Stmt::Kind::Continue:+      jump(loops_.back().continue_label);+      break;+    case Stmt::Kind::Expr:+      gen_expr(*s.expr);+      break;+    case Stmt::Kind::Block:+      gen_block_stmt(*s.block);+      break;+    }+  }++  void gen_for_range(Stmt &s) {+    Value lo = gen_expr(*s.lo);+    Value hi = gen_expr(*s.hi);+    TypePtr it = lo.ty->kind == Type::Kind::I64 ||+                         (hi.ty && hi.ty->kind == Type::Kind::I64)+                     ? t_i64()+                     : t_i32();+    lo = coerce(lo, it);+    hi = coerce(hi, it);++    std::string i_slot = alloc_slot(it);+    std::string hi_slot = alloc_slot(it);+    emit("store" + store_suffix(it) + " " + lo.s + ", " + i_slot);+    emit("store" + store_suffix(it) + " " + hi.s + ", " + hi_slot);++    std::string cond = new_label("for.cond");+    std::string body = new_label("for.body");+    std::string incr = new_label("for.incr");+    std::string end = new_label("for.end");++    push_scope();+    Local loopvar;+    loopvar.ty = it;+    loopvar.slot = i_slot;+    scopes_.back()[s.name] = loopvar;++    start_block(cond);+    Value iv = load_slot(i_slot, it);+    Value hv = load_slot(hi_slot, it);+    std::string c = new_temp();+    emit(c + " =w " + (it->kind == Type::Kind::I64 ? "csltl " : "csltw ") ++         iv.s + ", " + hv.s);+    branch(Value{t_bool(), c, true}, body, end);++    start_block(body);+    loops_.push_back(LoopCtx{end, incr});+    gen_block_stmt(*s.block);+    loops_.pop_back();+    if (!terminated())+      jump(incr);++    start_block(incr);+    iv = load_slot(i_slot, it);+    std::string one = it->kind == Type::Kind::I64 ? "1" : "1";+    std::string n = new_temp();+    emit(n + " =" + qbe_type(it) + " add " + iv.s + ", " + one);+    emit("store" + store_suffix(it) + " " + n + ", " + i_slot);+    jump(cond);++    start_block(end);+    pop_scope();+  }++  void gen_for_cond(Stmt &s) {+    std::string cond = new_label("while.cond");+    std::string body = new_label("while.body");+    std::string end = new_label("while.end");++    start_block(cond);+    Value c = gen_expr(*s.cond);+    branch(c, body, end);++    start_block(body);+    loops_.push_back(LoopCtx{end, cond});+    gen_block_stmt(*s.block);+    loops_.pop_back();+    if (!terminated())+      jump(cond);++    start_block(end);+  }+};++} // namespace++std::string generate_qbe(Program &program, const std::string &source_name) {+  Gen g(program, source_name);+  return g.run();+}++} // namespace xyz--- /dev/null+++ b/src/driver.cpp@@ -0,0 +1,517 @@+#include "xyz.h"+#include "libqbe.h"++#include <cctype>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iostream>+#include <sstream>+#include <string>+#include <vector>++#if defined(_WIN32)+#include <process.h>+#else+#include <sys/wait.h>+#include <unistd.h>+#endif++namespace fs = std::filesystem;++namespace {++struct Options {+  std::string input;+  std::string output;+  std::string target;+  std::string cc;+  std::string runtime;+  bool emit_il = false;+  bool emit_asm = false;+  bool emit_obj = false;+  bool run = false;+  bool keep = false;+  bool verbose = false;+};++void usage(FILE *f) {+  std::fprintf(f,+               "usage: xyz [options] file.xyz\n"+               "\n"+               "  -o file       output path\n"+               "  -target name  UQBE target (amd64_sysv, amd64_apple, amd64_win,\n"+               "                arm64, arm64_apple, arm64_win, rv64)\n"+               "  -S            stop after assembly\n"+               "  -c            stop after object file\n"+               "  -qbe          stop after QBE IL\n"+               "  -run          run the produced executable\n"+               "  -keep         keep temporary files\n"+               "  -cc path      C compiler used for assembly/linking\n"+               "  -runtime path path to libxyzrt.a\n"+               "  -v            print version\n"+               "  -h            print this help\n");+}++std::string lower(std::string s) {+  for (char &c : s)+    c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));+  return s;+}++std::string canonical_target(std::string name) {+  name = lower(std::move(name));+  if (name == "amd64_sysv" || name == "amd64_apple" || name == "amd64_win" ||+      name == "arm64" || name == "arm64_apple" || name == "arm64_win" ||+      name == "rv64")+    return name;+  if (name == "linux/amd64" || name == "freebsd/amd64" ||+      name == "openbsd/amd64" || name == "netbsd/amd64" ||+      name == "dragonfly/amd64")+    return "amd64_sysv";+  if (name == "linux/arm64" || name == "freebsd/arm64" ||+      name == "openbsd/arm64" || name == "netbsd/arm64")+    return "arm64";+  if (name == "linux/riscv64")+    return "rv64";+  if (name == "darwin/amd64" || name == "macos/amd64" ||+      name == "macosx/amd64")+    return "amd64_apple";+  if (name == "darwin/arm64" || name == "macos/arm64" ||+      name == "macosx/arm64")+    return "arm64_apple";+  if (name == "windows/amd64" || name == "win/amd64")+    return "amd64_win";+  if (name == "windows/arm64" || name == "win/arm64")+    return "arm64_win";+  return name;+}++std::string read_file(const fs::path &p) {+  std::ifstream in(p, std::ios::binary);+  if (!in)+    throw std::runtime_error("cannot read '" + p.string() + "'");+  std::ostringstream ss;+  ss << in.rdbuf();+  return ss.str();+}++void write_file(const fs::path &p, const std::string &s) {+  std::ofstream out(p, std::ios::binary);+  if (!out)+    throw std::runtime_error("cannot write '" + p.string() + "'");+  out << s;+}++std::string shell_quote(const std::string &s) {+#if defined(_WIN32)+  std::string out = "\"";+  for (char c : s) {+    if (c == '"')+      out += "\\\"";+    else+      out.push_back(c);+  }+  out += "\"";+  return out;+#else+  std::string out = "'";+  for (char c : s) {+    if (c == '\'')+      out += "'\\''";+    else+      out.push_back(c);+  }+  out += "'";+  return out;+#endif+}++int run_tool(const std::vector<std::string> &argv, bool verbose) {+  std::ostringstream cmd;+  for (size_t i = 0; i < argv.size(); i++) {+    if (i)+      cmd << ' ';+    cmd << shell_quote(argv[i]);+  }+  if (verbose)+    std::fprintf(stderr, "+ %s\n", cmd.str().c_str());+  int rc = std::system(cmd.str().c_str());+#if defined(_WIN32)+  return rc;+#else+  if (rc == -1)+    return 1;+  if (WIFEXITED(rc))+    return WEXITSTATUS(rc);+  return 1;+#endif+}++bool is_executable_file(const fs::path &p) {+  std::error_code ec;+  return fs::is_regular_file(p, ec);+}++std::string find_in_path(const std::string &name) {+  fs::path direct(name);+  if (direct.has_parent_path()) {+    std::error_code ec;+    if (fs::is_regular_file(direct, ec))+      return fs::absolute(direct).string();+    return {};+  }+  const char *path = std::getenv("PATH");+  if (!path)+    return {};+#if defined(_WIN32)+  char sep = ';';+#else+  char sep = ':';+#endif+  std::string all(path);+  size_t start = 0;+  while (start <= all.size()) {+    size_t end = all.find(sep, start);+    if (end == std::string::npos)+      end = all.size();+    fs::path dir = all.substr(start, end - start);+    if (!dir.empty()) {+      fs::path cand = dir / name;+      if (is_executable_file(cand))+        return cand.string();+#if defined(_WIN32)+      cand = dir / (name + ".exe");+      if (is_executable_file(cand))+        return cand.string();+#endif+    }+    if (end == all.size())+      break;+    start = end + 1;+  }+  return {};+}++fs::path executable_dir(const char *argv0) {+  std::error_code ec;+  fs::path p = argv0 && *argv0 ? fs::path(argv0) : fs::path("xyz");+  if (!p.has_parent_path()) {+    std::string found = find_in_path(p.string());+    if (!found.empty())+      p = found;+  }+  p = fs::absolute(p, ec);+  if (ec)+    p = fs::path(argv0 ? argv0 : "xyz");+  p = fs::weakly_canonical(p, ec);+  return p.parent_path();+}++std::string find_runtime(const Options &o, const fs::path &exe_dir) {+  if (!o.runtime.empty()) {+    if (!is_executable_file(o.runtime))+      throw std::runtime_error("runtime archive not found: " + o.runtime);+    return fs::absolute(o.runtime).string();+  }+  if (const char *env = std::getenv("XYZ_RUNTIME")) {+    if (*env && is_executable_file(env))+      return fs::absolute(env).string();+  }+  std::vector<fs::path> dirs = {exe_dir, exe_dir / ".." / "lib",+                                exe_dir / ".." / "lib" / "xyz",+                                fs::current_path()};+  const char *names[] = {"libxyzrt.a", "xyzrt.lib", "libxyzrt.lib",+                         "xyzrt.o"};+  for (auto &d : dirs) {+    for (const char *n : names) {+      fs::path p = d / n;+      std::error_code ec;+      if (fs::is_regular_file(p, ec))+        return fs::weakly_canonical(p, ec).string();+    }+  }+  throw std::runtime_error(+      "cannot find libxyzrt.a; build it with xmake or pass -runtime path");+}++std::string find_cc(const Options &o) {+  if (!o.cc.empty()) {+    std::string p = find_in_path(o.cc);+    if (p.empty())+      throw std::runtime_error("C compiler not found: " + o.cc);+    return p;+  }+  if (const char *env = std::getenv("XYZ_CC")) {+    if (*env) {+      std::string p = find_in_path(env);+      if (!p.empty())+        return p;+    }+  }+  if (const char *env = std::getenv("CC")) {+    if (*env) {+      std::string p = find_in_path(env);+      if (!p.empty())+        return p;+    }+  }+  const char *tries[] = {+#if defined(_WIN32)+      "clang", "gcc", "cc", "cl"+#else+      "cc", "clang", "gcc"+#endif+  };+  for (const char *t : tries) {+    std::string p = find_in_path(t);+    if (!p.empty())+      return p;+  }+  throw std::runtime_error("no C compiler found; pass -cc path");+}++std::string default_output(const std::string &input, const char *ext) {+  fs::path p(input);+  p.replace_extension(ext);+  return p.string();+}++#if defined(_WIN32)+unsigned long process_id() { return static_cast<unsigned long>(_getpid()); }+#else+unsigned long process_id() { return static_cast<unsigned long>(getpid()); }+#endif++fs::path make_temp_dir() {+  std::error_code ec;+  fs::path base = fs::temp_directory_path(ec);+  if (ec)+    base = fs::current_path();+  base /= "xyz";+  fs::create_directories(base, ec);+  for (int i = 0; i < 1000; i++) {+    fs::path p = base / ("work-" + std::to_string(process_id()) + "-" ++                         std::to_string(i));+    if (fs::create_directory(p, ec))+      return p;+  }+  throw std::runtime_error("cannot create temporary directory");+}++std::string format_error(const std::string &file, const xyz::Error &e) {+  std::ostringstream ss;+  ss << file << ':' << e.pos.line << ':' << e.pos.col << ": error: "+     << e.what();+  return ss.str();+}++} // namespace++int main(int argc, char **argv) {+  Options opt;+  std::vector<std::string> positional;++  for (int i = 1; i < argc; i++) {+    std::string a = argv[i];+    if (a == "-h") {+      usage(stdout);+      return 0;+    }+    if (a == "-v") {+      std::printf("xyz 0.1 (UQBE target %s)\n", qbe_default_target());+      return 0;+    }+    if (a == "-S") {+      opt.emit_asm = true;+      continue;+    }+    if (a == "-c") {+      opt.emit_obj = true;+      continue;+    }+    if (a == "-qbe") {+      opt.emit_il = true;+      continue;+    }+    if (a == "-run") {+      opt.run = true;+      continue;+    }+    if (a == "-keep") {+      opt.keep = true;+      continue;+    }+    if (a == "-verbose") {+      opt.verbose = true;+      continue;+    }+    if (a == "-o" || a == "-target" || a == "-cc" || a == "-runtime") {+      if (i + 1 >= argc) {+        std::fprintf(stderr, "xyz: missing value after %s\n", a.c_str());+        return 1;+      }+      std::string v = argv[++i];+      if (a == "-o")+        opt.output = v;+      else if (a == "-target")+        opt.target = v;+      else if (a == "-cc")+        opt.cc = v;+      else+        opt.runtime = v;+      continue;+    }+    if (a.size() > 2 && a[0] == '-' && a[1] == 'o')+      opt.output = a.substr(2);+    else if (a.size() > 7 && a.substr(0, 7) == "-target")+      opt.target = a.substr(7);+    else if (a.size() > 3 && a.substr(0, 3) == "-cc")+      opt.cc = a.substr(3);+    else if (a.size() > 8 && a.substr(0, 8) == "-runtime")+      opt.runtime = a.substr(8);+    else if (!a.empty() && a[0] == '-') {+      if (a.size() > 1 && a[1] == '-') {+        std::fprintf(stderr,+                     "xyz: GNU-style flag '%s' rejected; use single-dash "+                     "Plan 9 flags such as -target\n",+                     a.c_str());+        return 1;+      }+      std::fprintf(stderr, "xyz: unknown flag '%s' (try -h)\n", a.c_str());+      return 1;+    } else {+      positional.push_back(a);+    }+  }++  if (!positional.empty()) {+    const std::string &first = positional.front();+    if (first == "build" || first == "check" || first == "run" ||+        first == "qbe" || first == "asm" || first == "compile") {+      if (first == "run")+        opt.run = true;+      if (first == "qbe")+        opt.emit_il = true;+      if (first == "asm")+        opt.emit_asm = true;+      positional.erase(positional.begin());+    }+  }++  if (positional.size() != 1) {+    usage(stderr);+    return 2;+  }+  opt.input = positional[0];++  try {+    fs::path input(opt.input);+    if (!fs::is_regular_file(input))+      throw std::runtime_error("input file not found: " + opt.input);+    if (lower(input.extension().string()) != ".xyz")+      throw std::runtime_error("xyz expects a .xyz source file");++    std::string target = opt.target.empty() ? qbe_default_target()+                                            : canonical_target(opt.target);+    if (!qbe_target_supported(target.c_str()))+      throw std::runtime_error("unknown target '" + target ++                               "'; supported: " + qbe_target_list());++    std::string source = read_file(input);+    xyz::Program program = xyz::parse_program(source);+    xyz::check_program(program);+    std::string il = xyz::generate_qbe(program, input.filename().string());++    if (opt.emit_il) {+      std::string out = opt.output.empty() ? default_output(opt.input, ".ssa")+                                           : opt.output;+      if (out == "-")+        std::fwrite(il.data(), 1, il.size(), stdout);+      else {+        write_file(out, il);+        if (opt.verbose)+          std::fprintf(stderr, "xyz: wrote %s\n", out.c_str());+      }+      return 0;+    }++    fs::path tmp = make_temp_dir();+    fs::path ilpath = tmp / "unit.ssa";+    fs::path asmpath = tmp / "unit.s";+    write_file(ilpath, il);++    if (qbe_compile_file(ilpath.string().c_str(), asmpath.string().c_str(),+                         target.c_str()) != 0)+      throw std::runtime_error("UQBE failed to compile the generated IL");++    if (opt.emit_asm) {+      std::string out = opt.output.empty() ? default_output(opt.input, ".s")+                                           : opt.output;+      if (out == "-")+        std::fputs(read_file(asmpath).c_str(), stdout);+      else+        fs::copy_file(asmpath, out, fs::copy_options::overwrite_existing);+      if (opt.keep)+        std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+      else+        fs::remove_all(tmp);+      return 0;+    }++    std::string cc = find_cc(opt);+    fs::path exe_dir = executable_dir(argv[0]);+    std::string runtime = find_runtime(opt, exe_dir);++    if (opt.emit_obj) {+      std::string out = opt.output.empty() ? default_output(opt.input, ".o")+                                           : opt.output;+      std::vector<std::string> cmd = {cc, "-c", asmpath.string(), "-o", out};+      int rc = run_tool(cmd, opt.verbose);+      if (rc != 0)+        throw std::runtime_error("assembler failed");+      if (opt.keep)+        std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+      else+        fs::remove_all(tmp);+      return 0;+    }++    std::string out = opt.output;+    if (out.empty()) {+      out = default_output(opt.input, "");+#if defined(_WIN32)+      if (fs::path(out).extension().empty())+        out += ".exe";+#endif+    }++    std::vector<std::string> cmd = {cc, asmpath.string(), runtime, "-o", out};+    int rc = run_tool(cmd, opt.verbose);+    if (rc != 0)+      throw std::runtime_error("linker failed");++    if (opt.keep)+      std::fprintf(stderr, "xyz: kept %s\n", tmp.string().c_str());+    else+      fs::remove_all(tmp);++    if (opt.run) {+      std::string runpath = out;+#if !defined(_WIN32)+      if (runpath.find('/') == std::string::npos)+        runpath = "./" + runpath;+#endif+      return run_tool({runpath}, opt.verbose);+    }+    return 0;+  } catch (const xyz::Error &e) {+    std::fprintf(stderr, "%s\n", format_error(opt.input, e).c_str());+    return 1;+  } catch (const std::exception &e) {+    std::fprintf(stderr, "xyz: %s\n", e.what());+    return 1;+  }+}--- /dev/null+++ b/src/lexer.cpp@@ -0,0 +1,276 @@+#include "xyz.h"++#include <cctype>+#include <cerrno>+#include <cstdlib>++namespace xyz {++namespace {+class Lexer {+public:+  explicit Lexer(const std::string &src) : src_(src) {}++  std::vector<Token> run() {+    std::vector<Token> out;+    for (;;) {+      Token t = next();+      out.push_back(t);+      if (t.kind == Tok::End)+        break;+    }+    return out;+  }++private:+  const std::string &src_;+  size_t i_ = 0;+  int line_ = 1;+  int col_ = 1;++  char peek(size_t n = 0) const {+    return i_ + n < src_.size() ? src_[i_ + n] : '\0';+  }+  char take() {+    char c = peek();+    if (i_ < src_.size()) {+      i_++;+      if (c == '\n') {+        line_++;+        col_ = 1;+      } else {+        col_++;+      }+    }+    return c;+  }+  bool match(const char *s) {+    size_t n = std::char_traits<char>::length(s);+    if (src_.compare(i_, n, s) != 0)+      return false;+    for (size_t k = 0; k < n; k++)+      take();+    return true;+  }++  Token tok(Tok k, Pos p) {+    Token t;+    t.kind = k;+    t.pos = p;+    return t;+  }++  void skip_space() {+    for (;;) {+      char c = peek();+      if (c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' ||+          c == '\f') {+        take();+        continue;+      }+      if (c == '/' && peek(1) == '/') {+        while (peek() && peek() != '\n')+          take();+        continue;+      }+      if (c == '/' && peek(1) == '*') {+        take();+        take();+        while (peek() && !(peek() == '*' && peek(1) == '/'))+          take();+        if (peek()) {+          take();+          take();+        }+        continue;+      }+      break;+    }+  }++  Token next() {+    skip_space();+    Pos p{line_, col_};+    char c = peek();+    if (!c)+      return tok(Tok::End, p);++    if (std::isalpha(static_cast<unsigned char>(c)) || c == '_') {+      std::string s;+      while (std::isalnum(static_cast<unsigned char>(peek())) || peek() == '_')+        s.push_back(take());+      Token t = tok(Tok::Ident, p);+      t.text = std::move(s);+      return t;+    }++    if (std::isdigit(static_cast<unsigned char>(c))) {+      std::string s;+      int base = 10;+      if (c == '0' && (peek(1) == 'x' || peek(1) == 'X')) {+        s.push_back(take());+        s.push_back(take());+        base = 16;+        while (std::isxdigit(static_cast<unsigned char>(peek())) ||+               peek() == '_')+          s.push_back(take());+      } else {+        while (std::isdigit(static_cast<unsigned char>(peek())) || peek() == '_')+          s.push_back(take());+      }+      std::string clean;+      for (char ch : s)+        if (ch != '_')+          clean.push_back(ch);+      errno = 0;+      char *end = nullptr;+      unsigned long long v = std::strtoull(clean.c_str(), &end, base);+      if (errno || !end || *end)+        throw Error(p, "invalid integer literal");+      Token t = tok(Tok::Int, p);+      t.ival = static_cast<long long>(v);+      return t;+    }++    if (c == '"') {+      take();+      std::string s;+      while (peek() && peek() != '"') {+        char ch = take();+        if (ch != '\\') {+          s.push_back(ch);+          continue;+        }+        char e = take();+        switch (e) {+        case 'n':+          s.push_back('\n');+          break;+        case 't':+          s.push_back('\t');+          break;+        case 'r':+          s.push_back('\r');+          break;+        case '0':+          s.push_back('\0');+          break;+        case '\\':+          s.push_back('\\');+          break;+        case '"':+          s.push_back('"');+          break;+        case 'x': {+          int v = 0;+          for (int k = 0; k < 2; k++) {+            char h = peek();+            if (!std::isxdigit(static_cast<unsigned char>(h)))+              throw Error(p, "invalid \\x escape");+            take();+            v = v * 16 + (std::isdigit(static_cast<unsigned char>(h))+                              ? h - '0'+                              : std::tolower(static_cast<unsigned char>(h)) -+                                    'a' + 10);+          }+          s.push_back(static_cast<char>(v));+          break;+        }+        case '\n':+          break;+        default:+          s.push_back(e);+          break;+        }+      }+      if (peek() != '"')+        throw Error(p, "unterminated string literal");+      take();+      Token t = tok(Tok::Str, p);+      t.text = std::move(s);+      return t;+    }++    if (match("=>"))+      return tok(Tok::Arrow, p);+    if (match("=="))+      return tok(Tok::EqEq, p);+    if (match("!="))+      return tok(Tok::NotEq, p);+    if (match("<="))+      return tok(Tok::Le, p);+    if (match(">="))+      return tok(Tok::Ge, p);+    if (match("&&"))+      return tok(Tok::AndAnd, p);+    if (match("||"))+      return tok(Tok::OrOr, p);+    if (match("+="))+      return tok(Tok::PlusEq, p);+    if (match("-="))+      return tok(Tok::MinusEq, p);+    if (match("*="))+      return tok(Tok::StarEq, p);+    if (match("/="))+      return tok(Tok::SlashEq, p);+    if (match("%="))+      return tok(Tok::PercentEq, p);+    if (match("++"))+      return tok(Tok::PlusPlus, p);+    if (match("--"))+      return tok(Tok::MinusMinus, p);+    if (match(".."))+      return tok(Tok::DotDot, p);+    if (match("::"))+      return tok(Tok::ColonColon, p);++    take();+    switch (c) {+    case '+':+      return tok(Tok::Plus, p);+    case '-':+      return tok(Tok::Minus, p);+    case '*':+      return tok(Tok::Star, p);+    case '/':+      return tok(Tok::Slash, p);+    case '%':+      return tok(Tok::Percent, p);+    case '=':+      return tok(Tok::Assign, p);+    case '.':+      return tok(Tok::Dot, p);+    case ',':+      return tok(Tok::Comma, p);+    case '(':+      return tok(Tok::LParen, p);+    case ')':+      return tok(Tok::RParen, p);+    case '{':+      return tok(Tok::LBrace, p);+    case '}':+      return tok(Tok::RBrace, p);+    case '[':+      return tok(Tok::LBracket, p);+    case ']':+      return tok(Tok::RBracket, p);+    case ':':+      return tok(Tok::Colon, p);+    case '|':+      return tok(Tok::Pipe, p);+    case '!':+      return tok(Tok::Bang, p);+    case '<':+      return tok(Tok::Lt, p);+    case '>':+      return tok(Tok::Gt, p);+    default:+      throw Error(p, std::string("unexpected character '") + c + "'");+    }+  }+};+} // namespace++std::vector<Token> lex(const std::string &src) { return Lexer(src).run(); }++} // namespace xyz--- /dev/null+++ b/src/parser.cpp@@ -0,0 +1,573 @@+#include "xyz.h"++#include <utility>++namespace xyz {++namespace {++class Parser {+public:+  explicit Parser(std::vector<Token> tokens) : tokens_(std::move(tokens)) {}++  Program program() {+    Program p;+    while (!at(Tok::End)) {+      bool pure = false;+      bool pub = false;+      for (;;) {+        if (is_ident("pure")) {+          pure = true;+          advance();+        } else if (is_ident("pub")) {+          pub = true;+          advance();+        } else {+          break;+        }+      }+      if (is_ident("fn")) {+        p.functions.push_back(parse_fn(pure, pub));+        continue;+      }+      if (is_ident("type") || is_ident("contract") || is_ident("interface") ||+          is_ident("trait") || is_ident("impl") || is_ident("use") ||+          is_ident("import"))+        throw Error(cur().pos,+                    "'" + cur().text ++                        "' declarations are not supported by this milestone");+      throw Error(cur().pos, "expected 'fn' at top level");+    }+    return p;+  }++private:+  std::vector<Token> tokens_;+  size_t i_ = 0;++  const Token &cur() const { return tokens_[i_]; }+  const Token &at(size_t n) const {+    size_t k = i_ + n;+    return k < tokens_.size() ? tokens_[k] : tokens_.back();+  }+  void advance() {+    if (i_ + 1 < tokens_.size())+      i_++;+  }+  bool at(Tok k) const { return cur().kind == k; }+  bool is_ident(const std::string &s) const {+    return cur().kind == Tok::Ident && cur().text == s;+  }+  bool match(Tok k) {+    if (!at(k))+      return false;+    advance();+    return true;+  }+  bool match_ident(const std::string &s) {+    if (!is_ident(s))+      return false;+    advance();+    return true;+  }+  Token expect(Tok k, const std::string &what) {+    if (!at(k))+      throw Error(cur().pos, "expected " + what);+    Token t = cur();+    advance();+    return t;+  }+  std::string expect_ident(const std::string &what = "identifier") {+    if (cur().kind != Tok::Ident)+      throw Error(cur().pos, "expected " + what);+    std::string s = cur().text;+    advance();+    return s;+  }++  TypePtr parse_type() {+    if (cur().kind != Tok::Ident)+      throw Error(cur().pos, "expected a type");+    std::string name = cur().text;+    Pos p = cur().pos;+    advance();+    if (name == "i32")+      return t_i32();+    if (name == "i64")+      return t_i64();+    if (name == "bool")+      return t_bool();+    if (name == "str")+      return t_str();+    if (name == "ptr")+      return t_ptr();+    if (name == "void")+      return t_void();+    if (name == "list") {+      expect(Tok::LBracket, "'[' after list");+      TypePtr elem = parse_type();+      expect(Tok::RBracket, "']' after list element type");+      return t_list(std::move(elem));+    }+    if (name == "fn") {+      (void)p;+      throw Error(p, "function types are not supported by this milestone");+    }+    return t_unknown(name);+  }++  ExprPtr make_block_expr(BlockPtr b, Pos p) {+    auto e = std::make_unique<Expr>();+    e->kind = Expr::Kind::Block;+    e->pos = p;+    e->block = std::move(b);+    return e;+  }++  BlockPtr parse_block() {+    Pos p = cur().pos;+    expect(Tok::LBrace, "'{'");+    auto b = std::make_unique<Block>();+    b->pos = p;+    while (!at(Tok::RBrace)) {+      if (at(Tok::End))+        throw Error(cur().pos, "unterminated block");+      b->stmts.push_back(parse_stmt());+    }+    expect(Tok::RBrace, "'}'");+    return b;+  }++  StmtPtr parse_stmt() {+    Pos p = cur().pos;++    if (match_ident("const") || match_ident("var")) {+      bool is_const = tokens_[i_ - 1].text == "const";+      auto s = std::make_unique<Stmt>();+      s->kind = is_const ? Stmt::Kind::Let : Stmt::Kind::Var;+      s->pos = p;+      s->name = expect_ident("variable name");+      if (match(Tok::Colon))+        s->decl_type = parse_type();+      expect(Tok::Assign, "'=' in variable declaration");+      s->expr = parse_expr();+      return s;+    }++    if (match_ident("return")) {+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Return;+      s->pos = p;+      if (!at(Tok::RBrace) && !at(Tok::End))+        s->expr = parse_expr();+      return s;+    }++    if (match_ident("for")) {+      auto s = std::make_unique<Stmt>();+      s->pos = p;+      if (cur().kind == Tok::Ident && at(1).kind == Tok::Ident &&+          at(1).text == "in") {+        s->kind = Stmt::Kind::ForRange;+        s->name = cur().text;+        advance();+        advance();+        s->lo = parse_expr();+        expect(Tok::DotDot, "'..' in for range");+        s->hi = parse_expr();+        s->block = parse_block();+        return s;+      }+      s->kind = Stmt::Kind::ForCond;+      s->cond = parse_expr();+      s->block = parse_block();+      return s;+    }++    if (match_ident("break")) {+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Break;+      s->pos = p;+      return s;+    }+    if (match_ident("continue")) {+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Continue;+      s->pos = p;+      return s;+    }++    if (at(Tok::LBrace)) {+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Block;+      s->pos = p;+      s->block = parse_block();+      return s;+    }++    ExprPtr lhs = parse_expr();+    if (at(Tok::Assign) || at(Tok::PlusEq) || at(Tok::MinusEq) ||+        at(Tok::StarEq) || at(Tok::SlashEq) || at(Tok::PercentEq)) {+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Assign;+      s->pos = p;+      switch (cur().kind) {+      case Tok::Assign:+        s->op = "=";+        break;+      case Tok::PlusEq:+        s->op = "+=";+        break;+      case Tok::MinusEq:+        s->op = "-=";+        break;+      case Tok::StarEq:+        s->op = "*=";+        break;+      case Tok::SlashEq:+        s->op = "/=";+        break;+      default:+        s->op = "%=";+        break;+      }+      advance();+      s->expr = std::move(lhs);+      s->rhs = parse_expr();+      return s;+    }+    if (at(Tok::PlusPlus) || at(Tok::MinusMinus)) {+      bool inc = at(Tok::PlusPlus);+      advance();+      auto one = std::make_unique<Expr>();+      one->kind = Expr::Kind::Int;+      one->pos = p;+      one->ival = 1;+      one->ty = t_i32();+      auto s = std::make_unique<Stmt>();+      s->kind = Stmt::Kind::Assign;+      s->pos = p;+      s->op = inc ? "+=" : "-=";+      s->expr = std::move(lhs);+      s->rhs = std::move(one);+      return s;+    }++    auto s = std::make_unique<Stmt>();+    s->kind = Stmt::Kind::Expr;+    s->pos = p;+    s->expr = std::move(lhs);+    return s;+  }++  std::unique_ptr<Function> parse_fn(bool pure, bool pub) {+    Pos p = cur().pos;+    expect_ident("fn");+    auto fn = std::make_unique<Function>();+    fn->pos = p;+    fn->pure = pure;+    fn->pub = pub;+    fn->name = expect_ident("function name");++    if (match(Tok::LBracket)) {+      int depth = 1;+      while (depth > 0) {+        if (at(Tok::End))+          throw Error(cur().pos, "unterminated generic parameter list");+        if (at(Tok::LBracket))+          depth++;+        else if (at(Tok::RBracket))+          depth--;+        advance();+      }+    }++    expect(Tok::LParen, "'(' after function name");+    while (!at(Tok::RParen)) {+      Param param;+      param.pos = cur().pos;+      param.name = expect_ident("parameter name");+      param.type = parse_type();+      fn->params.push_back(std::move(param));+      if (!match(Tok::Comma))+        break;+    }+    expect(Tok::RParen, "')' after parameters");++    if (!at(Tok::Arrow) && !at(Tok::LBrace) && !at(Tok::Colon))+      fn->ret = parse_type();+    else+      fn->ret = t_void();++    while (match(Tok::Colon)) {+      if (match_ident("pre")) {+        Contract c;+        c.kind = Contract::Kind::Pre;+        c.pos = p;+        c.expr = parse_expr();+        fn->contracts.push_back(std::move(c));+      } else if (match_ident("post")) {+        Contract c;+        c.kind = Contract::Kind::Post;+        c.pos = p;+        if (cur().kind == Tok::Ident)+          c.result_name = cur().text;+        if (c.result_name.size() && at(1).kind == Tok::Arrow) {+          advance();+          advance();+        }+        c.expr = parse_expr();+        fn->contracts.push_back(std::move(c));+      } else {+        throw Error(cur().pos,+                    "named contracts are not supported by this milestone");+      }+    }++    if (match(Tok::Arrow)) {+      fn->arrow = parse_expr();+    } else {+      fn->body = parse_block();+    }+    return fn;+  }++  std::vector<ExprPtr> parse_args() {+    std::vector<ExprPtr> args;+    expect(Tok::LParen, "'('");+    while (!at(Tok::RParen)) {+      args.push_back(parse_expr());+      if (!match(Tok::Comma))+        break;+    }+    expect(Tok::RParen, "')' after arguments");+    return args;+  }++  ExprPtr parse_if_expr() {+    Pos p = cur().pos;+    expect_ident("if");+    auto e = std::make_unique<Expr>();+    e->kind = Expr::Kind::If;+    e->pos = p;+    e->cond = parse_expr();+    e->then_e = make_block_expr(parse_block(), p);+    if (match_ident("else")) {+      if (is_ident("if")) {+        e->else_e = parse_if_expr();+      } else {+        e->else_e = make_block_expr(parse_block(), p);+      }+    }+    return e;+  }++  ExprPtr parse_primary() {+    Pos p = cur().pos;+    if (at(Tok::Int)) {+      auto e = std::make_unique<Expr>();+      e->kind = Expr::Kind::Int;+      e->pos = p;+      e->ival = cur().ival;+      advance();+      return e;+    }+    if (at(Tok::Str)) {+      auto e = std::make_unique<Expr>();+      e->kind = Expr::Kind::String;+      e->pos = p;+      e->text = cur().text;+      advance();+      return e;+    }+    if (at(Tok::Ident)) {+      if (is_ident("true") || is_ident("false")) {+        auto e = std::make_unique<Expr>();+        e->kind = Expr::Kind::Bool;+        e->pos = p;+        e->bval = is_ident("true");+        advance();+        return e;+      }+      if (is_ident("if"))+        return parse_if_expr();+      auto e = std::make_unique<Expr>();+      e->kind = Expr::Kind::Var;+      e->pos = p;+      e->text = cur().text;+      advance();+      return e;+    }+    if (match(Tok::LParen)) {+      ExprPtr e = parse_expr();+      expect(Tok::RParen, "')'");+      return e;+    }+    if (at(Tok::LBrace)) {+      return make_block_expr(parse_block(), p);+    }+    if (match(Tok::LBracket)) {+      auto e = std::make_unique<Expr>();+      e->kind = Expr::Kind::List;+      e->pos = p;+      while (!at(Tok::RBracket)) {+        e->args.push_back(parse_expr());+        if (!match(Tok::Comma))+          break;+      }+      expect(Tok::RBracket, "']' after list literal");+      return e;+    }+    throw Error(cur().pos, "expected an expression");+  }++  ExprPtr parse_postfix() {+    ExprPtr e = parse_primary();+    for (;;) {+      if (at(Tok::LParen)) {+        auto call = std::make_unique<Expr>();+        call->kind = Expr::Kind::Call;+        call->pos = e->pos;+        call->lhs = std::move(e);+        call->args = parse_args();+        e = std::move(call);+        continue;+      }+      if (match(Tok::Dot)) {+        auto field = std::make_unique<Expr>();+        field->kind = Expr::Kind::Field;+        field->pos = e->pos;+        field->text = expect_ident("field name");+        field->lhs = std::move(e);+        e = std::move(field);+        continue;+      }+      if (match(Tok::LBracket)) {+        auto index = std::make_unique<Expr>();+        index->kind = Expr::Kind::Index;+        index->pos = e->pos;+        index->lhs = std::move(e);+        index->rhs = parse_expr();+        expect(Tok::RBracket, "']' after index");+        e = std::move(index);+        continue;+      }+      break;+    }+    return e;+  }++  ExprPtr parse_unary() {+    if (at(Tok::Minus) || at(Tok::Bang)) {+      Pos p = cur().pos;+      std::string op = at(Tok::Minus) ? "-" : "!";+      advance();+      auto e = std::make_unique<Expr>();+      e->kind = Expr::Kind::Unary;+      e->pos = p;+      e->op = op;+      e->lhs = parse_unary();+      return e;+    }+    return parse_postfix();+  }++  ExprPtr make_binary(std::string op, ExprPtr l, ExprPtr r, Pos p) {+    auto e = std::make_unique<Expr>();+    e->kind = Expr::Kind::Binary;+    e->pos = p;+    e->op = std::move(op);+    e->lhs = std::move(l);+    e->rhs = std::move(r);+    return e;+  }++  ExprPtr parse_multiplicative() {+    ExprPtr l = parse_unary();+    while (at(Tok::Star) || at(Tok::Slash) || at(Tok::Percent)) {+      Pos p = cur().pos;+      std::string op = at(Tok::Star) ? "*" : (at(Tok::Slash) ? "/" : "%");+      advance();+      l = make_binary(op, std::move(l), parse_unary(), p);+    }+    return l;+  }++  ExprPtr parse_additive() {+    ExprPtr l = parse_multiplicative();+    while (at(Tok::Plus) || at(Tok::Minus)) {+      Pos p = cur().pos;+      std::string op = at(Tok::Plus) ? "+" : "-";+      advance();+      l = make_binary(op, std::move(l), parse_multiplicative(), p);+    }+    return l;+  }++  ExprPtr parse_comparison() {+    ExprPtr l = parse_additive();+    while (at(Tok::Lt) || at(Tok::Le) || at(Tok::Gt) || at(Tok::Ge)) {+      Pos p = cur().pos;+      std::string op;+      switch (cur().kind) {+      case Tok::Lt:+        op = "<";+        break;+      case Tok::Le:+        op = "<=";+        break;+      case Tok::Gt:+        op = ">";+        break;+      default:+        op = ">=";+        break;+      }+      advance();+      l = make_binary(op, std::move(l), parse_additive(), p);+    }+    return l;+  }++  ExprPtr parse_equality() {+    ExprPtr l = parse_comparison();+    while (at(Tok::EqEq) || at(Tok::NotEq)) {+      Pos p = cur().pos;+      std::string op = at(Tok::EqEq) ? "==" : "!=";+      advance();+      l = make_binary(op, std::move(l), parse_comparison(), p);+    }+    return l;+  }++  ExprPtr parse_and() {+    ExprPtr l = parse_equality();+    while (at(Tok::AndAnd)) {+      Pos p = cur().pos;+      advance();+      l = make_binary("&&", std::move(l), parse_equality(), p);+    }+    return l;+  }++  ExprPtr parse_or() {+    ExprPtr l = parse_and();+    while (at(Tok::OrOr)) {+      Pos p = cur().pos;+      advance();+      l = make_binary("||", std::move(l), parse_and(), p);+    }+    return l;+  }++  ExprPtr parse_expr() { return parse_or(); }+};++} // namespace++Program parse_program(const std::string &src) {+  Parser p(lex(src));+  return p.program();+}++} // namespace xyz--- /dev/null+++ b/src/sema.cpp@@ -0,0 +1,447 @@+#include "xyz.h"++#include <algorithm>+#include <climits>++namespace xyz {++namespace {++struct VarInfo {+  TypePtr type;+  bool is_const = false;+};++class Scope {+public:+  Scope() { push(); }++  void push() { scopes_.emplace_back(); }+  void pop() { scopes_.pop_back(); }++  bool declare(const std::string &name, TypePtr type, bool is_const, Pos p) {+    auto &m = scopes_.back();+    if (m.count(name))+      throw Error(p, "duplicate declaration of '" + name + "'");+    m.emplace(name, VarInfo{std::move(type), is_const});+    return true;+  }++  const VarInfo *lookup(const std::string &name) const {+    for (auto it = scopes_.rbegin(); it != scopes_.rend(); ++it) {+      auto f = it->find(name);+      if (f != it->end())+        return &f->second;+    }+    return nullptr;+  }++private:+  std::vector<std::unordered_map<std::string, VarInfo>> scopes_;+};++class Checker {+public:+  explicit Checker(Program &p) : program_(p) {}++  void run() {+    if (program_.functions.empty())+      throw Error(Pos{}, "program contains no functions");++    for (auto &fn : program_.functions) {+      if (sigs_.count(fn->name))+        throw Error(fn->pos, "duplicate function '" + fn->name + "'");+      FuncSig sig;+      sig.ret = fn->ret;+      for (auto &p : fn->params)+        sig.params.push_back(p.type);+      sigs_.emplace(fn->name, std::move(sig));+    }++    if (!sigs_.count("main"))+      throw Error(Pos{}, "program does not define main");++    for (auto &fn : program_.functions)+      check_function(*fn);+  }++private:+  Program &program_;+  SigMap sigs_;+  Scope *scope_ = nullptr;+  TypePtr current_ret_;+  int loop_depth_ = 0;+  std::string current_fn_;++  static bool printable(const TypePtr &t) {+    return t && (t->kind == Type::Kind::I32 || t->kind == Type::Kind::I64 ||+                 t->kind == Type::Kind::Bool || t->kind == Type::Kind::Str);+  }++  TypePtr unify_int(const TypePtr &a, const TypePtr &b, Pos p) {+    if (!is_int(a) || !is_int(b))+      throw Error(p, "integer operands required");+    return (a->kind == Type::Kind::I64 || b->kind == Type::Kind::I64) ? t_i64()+                                                                     : t_i32();+  }++  void check_function(Function &fn) {+    scope_ = new Scope();+    current_ret_ = fn.ret;+    current_fn_ = fn.name;+    loop_depth_ = 0;++    for (auto &p : fn.params) {+      if (p.type->kind == Type::Kind::Unknown)+        throw Error(p.pos, "unknown type '" + p.type->name + "'");+      if (p.type->kind == Type::Kind::Void)+        throw Error(p.pos, "parameter cannot have type void");+      scope_->declare(p.name, p.type, true, p.pos);+    }++    for (auto &c : fn.contracts) {+      if (c.kind == Contract::Kind::Post && !c.result_name.empty())+        scope_->declare(c.result_name, fn.ret, true, c.pos);+      TypePtr t = check_expr(*c.expr);+      if (t->kind != Type::Kind::Bool)+        throw Error(c.pos, "contract expression must be bool");+    }++    if (fn.arrow) {+      if (fn.ret->kind == Type::Kind::Void)+        throw Error(fn.pos, "expression-bodied function must return a value");+      TypePtr t = check_expr(*fn.arrow);+      if (!assignable(fn.ret, t))+        throw Error(fn.arrow->pos, "function returns " + type_name(t) ++                                       ", expected " + type_name(fn.ret));+    } else if (fn.body) {+      TypePtr last = check_block(*fn.body);+      if (fn.ret->kind != Type::Kind::Void) {+        if (last && last->kind != Type::Kind::Void &&+            assignable(fn.ret, last)) {+          /* The final expression is the implicit return value. */+        } else if (!contains_return(*fn.body)) {+          throw Error(fn.body->pos, "function '" + fn.name + "' can finish "+                                                      "without returning a value");+        }+      }+    } else {+      throw Error(fn.pos, "function has no body");+    }++    delete scope_;+    scope_ = nullptr;+  }++  static bool contains_return(const Block &b) {+    for (auto &s : b.stmts) {+      if (s->kind == Stmt::Kind::Return)+        return true;+      if (s->kind == Stmt::Kind::Expr && s->expr &&+          s->expr->kind == Expr::Kind::If) {+        if (expr_contains_return(*s->expr))+          return true;+      }+      if (s->kind == Stmt::Kind::ForRange || s->kind == Stmt::Kind::ForCond) {+        if (s->block && contains_return(*s->block))+          return true;+      }+      if (s->kind == Stmt::Kind::Block && s->block && contains_return(*s->block))+        return true;+    }+    return false;+  }++  static bool expr_contains_return(const Expr &e) {+    if (e.kind == Expr::Kind::If) {+      if (e.then_e && e.then_e->kind == Expr::Kind::Block && e.then_e->block &&+          contains_return(*e.then_e->block))+        return true;+      if (e.else_e && e.else_e->kind == Expr::Kind::Block && e.else_e->block &&+          contains_return(*e.else_e->block))+        return true;+      if (e.else_e && e.else_e->kind == Expr::Kind::If &&+          expr_contains_return(*e.else_e))+        return true;+    }+    if (e.kind == Expr::Kind::Block && e.block && contains_return(*e.block))+      return true;+    return false;+  }++  TypePtr check_block(Block &b) {+    scope_->push();+    TypePtr last;+    for (auto &s : b.stmts) {+      last = check_stmt(*s);+    }+    scope_->pop();+    return last;+  }++  TypePtr check_stmt(Stmt &s) {+    switch (s.kind) {+    case Stmt::Kind::Let:+    case Stmt::Kind::Var: {+      TypePtr init = check_expr(*s.expr);+      TypePtr t = s.decl_type ? s.decl_type : init;+      if (t->kind == Type::Kind::Unknown)+        throw Error(s.pos, "unknown type '" + t->name + "'");+      if (t->kind == Type::Kind::Void)+        throw Error(s.pos, "variable cannot have type void");+      if (s.decl_type && !assignable(t, init))+        throw Error(s.pos, "cannot initialise " + type_name(t) + " with " ++                               type_name(init));+      scope_->declare(s.name, t, s.kind == Stmt::Kind::Let, s.pos);+      return t_void();+    }+    case Stmt::Kind::Assign: {+      if (s.expr->kind != Expr::Kind::Var)+        throw Error(s.pos, "assignment target must be a variable");+      const VarInfo *v = scope_->lookup(s.expr->text);+      if (!v)+        throw Error(s.pos, "undefined variable '" + s.expr->text + "'");+      if (v->is_const)+        throw Error(s.pos, "cannot assign to '" + s.expr->text + "'");+      s.expr->ty = v->type;+      TypePtr rhs = check_expr(*s.rhs);+      if (s.op == "=") {+        if (!assignable(v->type, rhs))+          throw Error(s.pos, "cannot assign " + type_name(rhs) + " to " ++                                 type_name(v->type));+      } else {+        if (!is_int(v->type) || !is_int(rhs))+          throw Error(s.pos, "compound assignment requires integers");+        if (v->type->kind == Type::Kind::I32 &&+            rhs->kind == Type::Kind::I64)+          throw Error(s.pos, "cannot narrow i64 to i32");+      }+      return t_void();+    }+    case Stmt::Kind::Return: {+      if (s.expr) {+        TypePtr t = check_expr(*s.expr);+        if (current_ret_->kind == Type::Kind::Void)+          throw Error(s.pos, "void function cannot return a value");+        if (!assignable(current_ret_, t))+          throw Error(s.pos, "returning " + type_name(t) + " from function "+                             "returning " + type_name(current_ret_));+      } else if (current_ret_->kind != Type::Kind::Void) {+        throw Error(s.pos, "return value required");+      }+      return t_void();+    }+    case Stmt::Kind::ForRange: {+      TypePtr lo = check_expr(*s.lo);+      TypePtr hi = check_expr(*s.hi);+      TypePtr it = unify_int(lo, hi, s.pos);+      scope_->push();+      scope_->declare(s.name, it, false, s.pos);+      loop_depth_++;+      check_block(*s.block);+      loop_depth_--;+      scope_->pop();+      return t_void();+    }+    case Stmt::Kind::ForCond: {+      TypePtr c = check_expr(*s.cond);+      if (c->kind != Type::Kind::Bool)+        throw Error(s.pos, "for condition must be bool");+      loop_depth_++;+      check_block(*s.block);+      loop_depth_--;+      return t_void();+    }+    case Stmt::Kind::Break:+      if (!loop_depth_)+        throw Error(s.pos, "break outside a loop");+      return t_void();+    case Stmt::Kind::Continue:+      if (!loop_depth_)+        throw Error(s.pos, "continue outside a loop");+      return t_void();+    case Stmt::Kind::Expr:+      check_expr(*s.expr);+      return (s.expr->ty && s.expr->ty->kind != Type::Kind::Void)+                 ? s.expr->ty+                 : t_void();+    case Stmt::Kind::Block:+      return check_block(*s.block);+    }+    return t_void();+  }++  TypePtr check_expr(Expr &e) {+    TypePtr t;+    switch (e.kind) {+    case Expr::Kind::Int:+      if (e.ival >= INT32_MIN && e.ival <= INT32_MAX)+        t = t_i32();+      else+        t = t_i64();+      break;+    case Expr::Kind::Bool:+      t = t_bool();+      break;+    case Expr::Kind::String:+      t = t_str();+      break;+    case Expr::Kind::Var: {+      const VarInfo *v = scope_->lookup(e.text);+      if (!v)+        throw Error(e.pos, "undefined variable '" + e.text + "'");+      t = v->type;+      break;+    }+    case Expr::Kind::Unary: {+      TypePtr a = check_expr(*e.lhs);+      if (e.op == "-") {+        if (!is_int(a))+          throw Error(e.pos, "unary '-' requires an integer");+        t = a;+      } else {+        if (a->kind != Type::Kind::Bool)+          throw Error(e.pos, "unary '!' requires bool");+        t = t_bool();+      }+      break;+    }+    case Expr::Kind::Binary: {+      TypePtr a = check_expr(*e.lhs);+      TypePtr b = check_expr(*e.rhs);+      if (e.op == "+" || e.op == "-" || e.op == "*" || e.op == "/" ||+          e.op == "%") {+        t = unify_int(a, b, e.pos);+      } else if (e.op == "<" || e.op == "<=" || e.op == ">" || e.op == ">=") {+        unify_int(a, b, e.pos);+        t = t_bool();+      } else if (e.op == "==" || e.op == "!=") {+        if (!(is_int(a) && is_int(b)) && !(a->kind == Type::Kind::Bool &&+                                          b->kind == Type::Kind::Bool) &&+            !(a->kind == Type::Kind::Str && b->kind == Type::Kind::Str))+          throw Error(e.pos, "operands are not comparable");+        t = t_bool();+      } else if (e.op == "&&" || e.op == "||") {+        if (a->kind != Type::Kind::Bool || b->kind != Type::Kind::Bool)+          throw Error(e.pos, "logical operands must be bool");+        t = t_bool();+      } else {+        throw Error(e.pos, "unknown operator '" + e.op + "'");+      }+      break;+    }+    case Expr::Kind::Call: {+      if (e.lhs->kind != Expr::Kind::Var)+        throw Error(e.pos, "only named functions can be called");+      const std::string &name = e.lhs->text;+      for (auto &a : e.args)+        check_expr(*a);+      if (name == "print") {+        if (e.args.size() != 1)+          throw Error(e.pos, "print takes exactly one argument");+        if (!printable(e.args[0]->ty))+          throw Error(e.pos, "cannot print " + type_name(e.args[0]->ty));+        t = t_void();+      } else if (name == "__gc_alloc") {+        if (e.args.size() != 1 || !is_int(e.args[0]->ty))+          throw Error(e.pos, "__gc_alloc takes one integer");+        t = t_ptr();+      } else if (name == "__gc_store") {+        if (e.args.size() != 3 || e.args[0]->ty->kind != Type::Kind::Ptr ||+            !is_int(e.args[1]->ty) ||+            e.args[2]->ty->kind != Type::Kind::Ptr)+          throw Error(e.pos, "__gc_store takes (ptr, i32, ptr)");+        t = t_void();+      } else if (name == "__gc_load") {+        if (e.args.size() != 2 || e.args[0]->ty->kind != Type::Kind::Ptr ||+            !is_int(e.args[1]->ty))+          throw Error(e.pos, "__gc_load takes (ptr, i32)");+        t = t_ptr();+      } else if (name == "__gc_alive") {+        if (e.args.size() != 1 || e.args[0]->ty->kind != Type::Kind::Ptr)+          throw Error(e.pos, "__gc_alive takes a ptr");+        t = t_bool();+      } else if (name == "__gc_collect" || name == "__gc_verify") {+        if (!e.args.empty())+          throw Error(e.pos, name + " takes no arguments");+        t = t_void();+      } else if (name == "__gc_pin" || name == "__gc_unpin") {+        if (e.args.size() != 1 || e.args[0]->ty->kind != Type::Kind::Ptr)+          throw Error(e.pos, name + " takes a ptr");+        t = t_void();+      } else {+        auto it = sigs_.find(name);+        if (it == sigs_.end())+          throw Error(e.pos, "unknown function '" + name + "'");+        const FuncSig &sig = it->second;+        if (e.args.size() != sig.params.size())+          throw Error(e.pos, "function '" + name + "' expects " ++                                 std::to_string(sig.params.size()) ++                                 " arguments");+        for (size_t i = 0; i < e.args.size(); i++) {+          if (!assignable(sig.params[i], e.args[i]->ty))+            throw Error(e.args[i]->pos,+                        "argument " + std::to_string(i + 1) + " has type " ++                            type_name(e.args[i]->ty) + ", expected " ++                            type_name(sig.params[i]));+        }+        t = sig.ret;+      }+      break;+    }+    case Expr::Kind::If: {+      TypePtr c = check_expr(*e.cond);+      if (c->kind != Type::Kind::Bool)+        throw Error(e.pos, "if condition must be bool");+      TypePtr a = e.then_e->kind == Expr::Kind::Block+                      ? check_block(*e.then_e->block)+                      : check_expr(*e.then_e);+      TypePtr b = t_void();+      if (e.else_e) {+        b = e.else_e->kind == Expr::Kind::Block ? check_block(*e.else_e->block)+                                                : check_expr(*e.else_e);+      }+      if (!e.else_e) {+        t = t_void();+      } else if (a->kind == Type::Kind::Void && b->kind == Type::Kind::Void) {+        t = t_void();+      } else if (a->kind == Type::Kind::Void || b->kind == Type::Kind::Void) {+        throw Error(e.pos, "both branches of an if expression must produce "+                           "a value");+      } else if (assignable(a, b)) {+        t = a;+      } else if (assignable(b, a)) {+        t = b;+      } else {+        throw Error(e.pos, "if branches have incompatible types " ++                               type_name(a) + " and " + type_name(b));+      }+      break;+    }+    case Expr::Kind::Block:+      t = check_block(*e.block);+      break;+    case Expr::Kind::List:+      throw Error(e.pos,+                  "list expressions are not supported by this milestone");+    case Expr::Kind::Field:+      throw Error(e.pos,+                  "field access is not supported by this milestone");+    case Expr::Kind::Index:+      throw Error(e.pos, "indexing is not supported by this milestone");+    case Expr::Kind::Assign:+      throw Error(e.pos, "assignment is only valid as a statement");+    }+    e.ty = t;+    return t;+  }+};++} // namespace++void check_program(Program &program) {+  Checker c(program);+  c.run();+}++} // namespace xyz--- /dev/null+++ b/src/types.cpp@@ -0,0 +1,102 @@+#include "xyz.h"++namespace xyz {++namespace {+TypePtr make(Type::Kind k) {+  auto t = std::make_shared<Type>();+  t->kind = k;+  return t;+}+} // namespace++TypePtr t_void() { return make(Type::Kind::Void); }+TypePtr t_i32() { return make(Type::Kind::I32); }+TypePtr t_i64() { return make(Type::Kind::I64); }+TypePtr t_bool() { return make(Type::Kind::Bool); }+TypePtr t_str() { return make(Type::Kind::Str); }+TypePtr t_ptr() { return make(Type::Kind::Ptr); }++TypePtr t_list(TypePtr elem) {+  auto t = make(Type::Kind::List);+  t->elem = std::move(elem);+  return t;+}++TypePtr t_unknown(const std::string &name) {+  auto t = make(Type::Kind::Unknown);+  t->name = name;+  return t;+}++bool same_type(const TypePtr &a, const TypePtr &b) {+  if (!a || !b)+    return false;+  if (a->kind != b->kind)+    return false;+  if (a->kind == Type::Kind::List)+    return same_type(a->elem, b->elem);+  if (a->kind == Type::Kind::Unknown)+    return a->name == b->name;+  return true;+}++bool is_int(const TypePtr &t) {+  return t && (t->kind == Type::Kind::I32 || t->kind == Type::Kind::I64);+}++bool is_managed(const TypePtr &t) {+  return t && (t->kind == Type::Kind::Ptr || t->kind == Type::Kind::List);+}++std::string type_name(const TypePtr &t) {+  if (!t)+    return "?";+  switch (t->kind) {+  case Type::Kind::Void:+    return "void";+  case Type::Kind::I32:+    return "i32";+  case Type::Kind::I64:+    return "i64";+  case Type::Kind::Bool:+    return "bool";+  case Type::Kind::Str:+    return "str";+  case Type::Kind::Ptr:+    return "ptr";+  case Type::Kind::List:+    return "list[" + type_name(t->elem) + "]";+  case Type::Kind::Unknown:+    return t->name.empty() ? "?" : t->name;+  }+  return "?";+}++std::string qbe_type(const TypePtr &t) {+  if (!t)+    return "w";+  switch (t->kind) {+  case Type::Kind::I64:+  case Type::Kind::Str:+  case Type::Kind::Ptr:+  case Type::Kind::List:+    return "l";+  default:+    return "w";+  }+}++bool assignable(const TypePtr &to, const TypePtr &from) {+  if (!to || !from)+    return false;+  if (same_type(to, from))+    return true;+  if (to->kind == Type::Kind::I64 && from->kind == Type::Kind::I32)+    return true;+  if (to->kind == Type::Kind::Unknown || from->kind == Type::Kind::Unknown)+    return true;+  return false;+}++} // namespace xyz--- /dev/null+++ b/src/xyz.h@@ -0,0 +1,215 @@+#ifndef XYZ_H+#define XYZ_H++#include <cstdint>+#include <memory>+#include <stdexcept>+#include <string>+#include <unordered_map>+#include <unordered_set>+#include <vector>++namespace xyz {++struct Pos {+  int line = 1;+  int col = 1;+};++struct Error : std::runtime_error {+  Pos pos;+  Error(Pos p, const std::string &msg) : std::runtime_error(msg), pos(p) {}+};++struct Type;+using TypePtr = std::shared_ptr<Type>;++struct Type {+  enum class Kind { Void, I32, I64, Bool, Str, Ptr, List, Unknown };+  Kind kind = Kind::Unknown;+  TypePtr elem;+  std::string name;+};++TypePtr t_void();+TypePtr t_i32();+TypePtr t_i64();+TypePtr t_bool();+TypePtr t_str();+TypePtr t_ptr();+TypePtr t_list(TypePtr elem);+TypePtr t_unknown(const std::string &name);+bool same_type(const TypePtr &a, const TypePtr &b);+bool is_int(const TypePtr &t);+bool is_managed(const TypePtr &t);+std::string type_name(const TypePtr &t);+std::string qbe_type(const TypePtr &t);+bool assignable(const TypePtr &to, const TypePtr &from);++enum class Tok {+  End,+  Ident,+  Int,+  Str,+  Arrow,+  EqEq,+  NotEq,+  Le,+  Ge,+  AndAnd,+  OrOr,+  Plus,+  Minus,+  Star,+  Slash,+  Percent,+  Assign,+  PlusEq,+  MinusEq,+  StarEq,+  SlashEq,+  PercentEq,+  PlusPlus,+  MinusMinus,+  Dot,+  DotDot,+  Comma,+  LParen,+  RParen,+  LBrace,+  RBrace,+  LBracket,+  RBracket,+  Colon,+  ColonColon,+  Pipe,+  Bang,+  Lt,+  Gt,+};++struct Token {+  Tok kind = Tok::End;+  std::string text;+  long long ival = 0;+  Pos pos;+};++std::vector<Token> lex(const std::string &src);++struct Expr;+using ExprPtr = std::unique_ptr<Expr>;++struct Block;+using BlockPtr = std::unique_ptr<Block>;++struct Expr {+  enum class Kind {+    Int,+    Bool,+    String,+    Var,+    Unary,+    Binary,+    Call,+    If,+    Block,+    List,+    Field,+    Index,+    Assign,+  };+  Kind kind = Kind::Int;+  Pos pos;+  TypePtr ty;+  long long ival = 0;+  bool bval = false;+  std::string text;+  std::string op;+  ExprPtr lhs;+  ExprPtr rhs;+  ExprPtr cond;+  ExprPtr then_e;+  ExprPtr else_e;+  std::vector<ExprPtr> args;+  BlockPtr block;+};++struct Stmt;+using StmtPtr = std::unique_ptr<Stmt>;++struct Stmt {+  enum class Kind {+    Let,+    Var,+    Assign,+    Return,+    ForRange,+    ForCond,+    Break,+    Continue,+    Expr,+    Block,+  };+  Kind kind = Kind::Expr;+  Pos pos;+  std::string name;+  std::string op;+  TypePtr decl_type;+  ExprPtr expr;+  ExprPtr rhs;+  ExprPtr cond;+  ExprPtr lo;+  ExprPtr hi;+  BlockPtr block;+};++struct Block {+  Pos pos;+  std::vector<StmtPtr> stmts;+};++struct Param {+  std::string name;+  TypePtr type;+  Pos pos;+};++struct Contract {+  enum class Kind { Pre, Post };+  Kind kind = Kind::Pre;+  std::string result_name;+  ExprPtr expr;+  Pos pos;+};++struct Function {+  std::string name;+  std::vector<Param> params;+  TypePtr ret;+  BlockPtr body;+  ExprPtr arrow;+  std::vector<Contract> contracts;+  bool pure = false;+  bool pub = false;+  Pos pos;+};++struct Program {+  std::vector<std::unique_ptr<Function>> functions;+};++Program parse_program(const std::string &src);+void check_program(Program &program);+std::string generate_qbe(Program &program, const std::string &source_name);++struct FuncSig {+  TypePtr ret;+  std::vector<TypePtr> params;+};++using SigMap = std::unordered_map<std::string, FuncSig>;++} // namespace xyz++#endif--- /dev/null+++ b/tests/m0_gc.xyz@@ -0,0 +1,32 @@+// Internal M0 smoke test: ordinary, medium, and large allocation, with+// collections interleaved and the heap verifier enabled.++fn churn(count i32) {+    var i = 0+    for i < count {+        const p = __gc_alloc(64)+        __gc_store(p, 8, p)+        i+++    }+}++fn hold_big() ptr {+    const p = __gc_alloc(10000)+    return p+}++fn main() {+    const keep = hold_big()+    churn(2000)+    __gc_collect()+    __gc_verify()+    if __gc_alive(keep) {+        print("big alive")+    } else {+        print("big dead")+    }+    churn(1000)+    __gc_collect()+    __gc_verify()+    print("churn ok")+}--- /dev/null+++ b/tests/m1_roots.xyz@@ -0,0 +1,21 @@+// Internal M1 smoke test: a managed reference must survive a collection+// across nested calls, and the shadow-stack frame must keep it alive.++fn allocate_and_collect() {+    const p = __gc_alloc(64)+    __gc_store(p, 8, p)+    __gc_collect()+    __gc_verify()+}++fn main() {+    const q = __gc_alloc(48)+    allocate_and_collect()+    __gc_collect()+    __gc_verify()+    if __gc_alive(q) {+        print("alive")+    } else {+        print("dead")+    }+}--- /dev/null+++ b/tests/runtime_test.cpp@@ -0,0 +1,99 @@+#include "xyzrt.h"++#include <cstdio>+#include <cstdlib>++namespace {++int failures = 0;++void check(bool ok, const char *what) {+  if (!ok) {+    std::fprintf(stderr, "FAIL: %s\n", what);+    failures++;+  }+}++} // namespace++int main() {+  xyz_runtime_init();++  /* A descriptor with two managed pointer fields. */+  static const uint32_t offsets[] = {8, 16};+  uint32_t parent_type = xyz_register_type(32, 2, offsets);++  void *child = xyz_alloc_slow(16, 0);+  void *parent = xyz_alloc_slow(16, parent_type);+  check(child && parent, "allocation");+  *reinterpret_cast<void **>(static_cast<unsigned char *>(parent) + 8) = child;++  void *root = parent;+  xyz_root_add(&root);+  xyz_gc_collect();+  xyz_gc_verify();+  check(xyz_gc_object_alive(parent), "parent kept by global root");+  check(xyz_gc_object_alive(child), "child traced through descriptor");++  xyz_root_remove(&root);+  parent = nullptr;+  child = nullptr;+  xyz_gc_collect();+  xyz_gc_verify();++  /* Medium object. */+  void *medium = xyz_alloc_slow(4000, 0);+  check(medium != nullptr, "medium allocation");+  root = medium;+  xyz_root_add(&root);+  xyz_gc_collect();+  check(xyz_gc_object_alive(medium), "medium object survives");+  xyz_root_remove(&root);++  /* Large object space. */+  void *large = xyz_alloc_large(10000, 0);+  check(large != nullptr, "large allocation");+  root = large;+  xyz_root_add(&root);+  xyz_gc_collect();+  check(xyz_gc_object_alive(large), "large object survives");+  xyz_root_remove(&root);+  xyz_gc_collect();+  check(!xyz_gc_object_alive(large), "large object reclaimed");++  /* Shadow-stack frame. */+  void *slot[1] = {nullptr};+  static const uint32_t root_offsets[] = {0};+  XyzRootMap map = {1, 24, root_offsets};+  XyzRootFrame frame = {nullptr, &map, slot};+  slot[0] = xyz_alloc_slow(64, 0);+  xyz_root_enter(&frame);+  xyz_gc_collect();+  xyz_gc_verify();+  check(xyz_gc_object_alive(slot[0]), "object kept by root frame");+  xyz_root_leave(&frame);+  xyz_gc_collect();+  check(!xyz_gc_object_alive(slot[0]), "object collected after root leave");++  /* Epoch wraparound smoke test. */+  void *stable = xyz_alloc_slow(32, 0);+  root = stable;+  xyz_root_add(&root);+  for (int i = 0; i < 300; i++) {+    xyz_gc_collect();+    if (!xyz_gc_object_alive(stable)) {+      check(false, "stable object survived epoch wrap");+      break;+    }+  }+  xyz_root_remove(&root);+  xyz_gc_collect();+  check(!xyz_gc_object_alive(stable), "stable object reclaimed");++  if (failures) {+    std::fprintf(stderr, "%d runtime test(s) failed\n", failures);+    return 1;+  }+  std::puts("runtime tests passed");+  return 0;+}--- /dev/null+++ b/xmake.lua@@ -0,0 +1,63 @@+add_rules("mode.debug", "mode.release")+set_languages("c99", "c++23")++-- The xyz runtime: static archive linked into every produced executable.+target("xyzrt")+    set_kind("static")+    set_default(true)+    add_files("runtime/*.cpp")+    add_includedirs("runtime")+    if is_plat("windows") and is_toolchain("msvc") then+        add_cxxflags("/EHs-c-", "/GR-")+    else+        add_cxxflags("-fno-exceptions", "-fno-rtti")+    end+target("xyzrt_test")+    set_kind("binary")+    set_default(false)+    add_files("tests/runtime_test.cpp")+    add_includedirs("runtime")+    add_deps("xyzrt")++-- The xyz compiler.  UQBE is compiled in as a library; main.c is replaced by+-- ../qbe/libqbe.c.+target("xyz")+    set_kind("binary")+    set_default(true)+    add_files("src/*.cpp")+    add_files(+        "../qbe/libqbe.c",+        "../qbe/abi.c",+        "../qbe/alias.c",+        "../qbe/cfg.c",+        "../qbe/copy.c",+        "../qbe/emit.c",+        "../qbe/fold.c",+        "../qbe/gcm.c",+        "../qbe/getopt.c",+        "../qbe/gvn.c",+        "../qbe/ifopt.c",+        "../qbe/live.c",+        "../qbe/load.c",+        "../qbe/mem.c",+        "../qbe/parse.c",+        "../qbe/rega.c",+        "../qbe/simpl.c",+        "../qbe/spill.c",+        "../qbe/ssa.c",+        "../qbe/util.c",+        "../qbe/amd64/targ.c",+        "../qbe/amd64/sysv.c",+        "../qbe/amd64/isel.c",+        "../qbe/amd64/emit.c",+        "../qbe/amd64/winabi.c",+        "../qbe/arm64/targ.c",+        "../qbe/arm64/abi.c",+        "../qbe/arm64/isel.c",+        "../qbe/arm64/emit.c",+        "../qbe/rv64/targ.c",+        "../qbe/rv64/abi.c",+        "../qbe/rv64/isel.c",+        "../qbe/rv64/emit.c"+    )+    add_includedirs("src", "../qbe", "../qbe/amd64", "../qbe/arm64", "../qbe/rv64")