Skip to content

Port GC heap to std/rt + typeck extern dedupe (Wave 1 unit 5) - #9

Merged
CierCier merged 4 commits into
mainfrom
std/rt-gc-heap
Jul 20, 2026
Merged

CierCier merged 4 commits into
mainfrom
std/rt-gc-heap

Conversation

@CierCier

@CierCier CierCier commented Jul 20, 2026 •

Copy link
Copy Markdown
Owner

Summary

Wave 1 unit 5 of docs/runtime-migration.md.

  • std/rt/heap.ag — generational Handle, slot vector, free list, RtValue/Object tagged structs (type ids as bare u32 for now; unified with TypeId in unit 10), alloc/get/get_mut/free, mark-sweep collect_garbage(roots)
  • agc/src/semantic/typeck.rs — identical extern redeclarations no longer register the same symbol id twice (fixes phantom abort() ambiguity when modules redeclare the same prototype)
  • tests/rt_heap_test.ag — 39 cases: generational safety, GC reachability, get_mut, slot reuse

Test plan

Greptile Summary

This PR introduces a generational mark-sweep GC heap (std/rt/heap.ag) as a Silver port of silver_runtime/src/runtime/heap.rs, and fixes a type-checker bug where identical extern "C" redeclarations from multiple imported modules caused phantom overload-resolution ambiguities.

  • std/rt/heap.ag: Adds Handle, RtValue, Object, and Heap with alloc/get/get_mut/free/collect_garbage. The implementation uses five parallel slot vectors (objects, occupied, marked, generations, free_list) instead of Rust's Vec<Option<Entry>>, with explicit ownership managed through Silver's mandatory-drop pattern.
  • agc/src/semantic/typeck.rs: Changes function_symbols.insert to entry().or_insert_with() and guards overloads.push with a contains check, preventing duplicate symbol_id entries that caused a function to appear as a phantom self-ambiguous overload.
  • tests/rt_heap_test.ag: 39 test cases covering generational stale-handle rejection, GC reachability tracing through composite objects, get_mut mutation visibility, slot reuse, and allocated_count bookkeeping.

Confidence Score: 4/5

Safe to merge for integration; the one open concern is that generation counters in both free() and the GC sweep use plain addition rather than a guaranteed-wrapping operation, leaving the slot-reuse safety guarantee dependent on build-mode overflow behaviour.

The GC algorithm and ownership model are correct, the typeck dedupe fix is sound, and the 39-case test suite gives solid coverage. The generation counter arithmetic (noted in a prior thread) is the remaining unresolved point: if overflow checks fire in any build configuration, a slot freed exactly 2^32 times would trap rather than wrap as the comment promises, and if they are silently truncated the ABA window reappears at that boundary.

std/rt/heap.ag — specifically the generation bump expressions in free() (line 433) and the GC sweep (line 453).

Important Files Changed

Filename Overview
agc/src/semantic/typeck.rs Fixes phantom self-ambiguity for identical extern redeclarations: function_symbols now uses entry().or_insert_with() (idempotent, keeps first FunctionSig) and overloads guards with contains before push. Logic is correct for the documented use case.
std/rt/heap.ag New generational mark-sweep GC heap. Algorithm is correct: clear→mark from roots (DFS work-stack)→sweep. Ownership invariants are carefully managed with explicit drops. Two concerns from prior threads (generation counter wraps and span source) are the primary open items.
bootstrap/include/silver/std/rt/heap.ag Byte-for-byte copy of std/rt/heap.ag added to the bootstrap include tree. No independent logic to review.
tests/rt_heap_test.ag 39-case test suite covering generational safety, GC reachability (single and chained objects), get_mut mutation visibility, allocated_count bookkeeping, and slot reuse. All cleanup paths call explicit drop as expected.
bootstrap/lib/silver/std/rt/heap.agm New compiled module artifact for std/rt/heap; binary diff only, generated from the source.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["alloc(object)"] --> B{free_list empty?}
    B -- No --> C["pop index from free_list\nread bumped generation\nset objects[idx]\nset occupied[idx]=true\nset marked[idx]=false"]
    B -- Yes --> D["append object\nappend occupied=true\nappend marked=false\nappend generation=0"]
    C --> E["return Handle{index, generation}"]
    D --> E
    F["get / get_mut(handle)"] --> G{handle_is_valid?}
    G -- No --> H["ObjectRef { ok=false, ptr=null }"]
    G -- Yes --> I["ObjectRef { ok=true, ptr=&objects[idx] }"]
    J["free(handle)"] --> K{handle_is_valid?}
    K -- No --> L["FreeResult { ok=false, empty Object }"]
    K -- Yes --> M["objects.take(idx)\noccupied[idx]=false\ngenerations[idx]+=1\nfree_list.push(idx)"]
    M --> N["FreeResult { ok=true, object }"]
    O["collect_garbage(roots, len)"] --> P["clear marked[0..slot_count]"]
    P --> Q["push root handles onto work stack"]
    Q --> R{stack empty?}
    R -- No --> S["pop handle\nvalidate index+generation+occupied+!marked\nmark slot\npush children"]
    S --> R
    R -- Yes --> T["sweep: drop+free all occupied && !marked\nbump generation, push to free_list"]
    T --> U["return freed count"]
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A["alloc(object)"] --> B{free_list empty?}
    B -- No --> C["pop index from free_list\nread bumped generation\nset objects[idx]\nset occupied[idx]=true\nset marked[idx]=false"]
    B -- Yes --> D["append object\nappend occupied=true\nappend marked=false\nappend generation=0"]
    C --> E["return Handle{index, generation}"]
    D --> E
    F["get / get_mut(handle)"] --> G{handle_is_valid?}
    G -- No --> H["ObjectRef { ok=false, ptr=null }"]
    G -- Yes --> I["ObjectRef { ok=true, ptr=&objects[idx] }"]
    J["free(handle)"] --> K{handle_is_valid?}
    K -- No --> L["FreeResult { ok=false, empty Object }"]
    K -- Yes --> M["objects.take(idx)\noccupied[idx]=false\ngenerations[idx]+=1\nfree_list.push(idx)"]
    M --> N["FreeResult { ok=true, object }"]
    O["collect_garbage(roots, len)"] --> P["clear marked[0..slot_count]"]
    P --> Q["push root handles onto work stack"]
    Q --> R{stack empty?}
    R -- No --> S["pop handle\nvalidate index+generation+occupied+!marked\nmark slot\npush children"]
    S --> R
    R -- Yes --> T["sweep: drop+free all occupied && !marked\nbump generation, push to free_list"]
    T --> U["return freed count"]
Loading

Reviews (3): Last reviewed commit: "Merge origin/main into std/rt-gc-heap an..." | Re-trigger Greptile

Add std/rt/heap.ag with generational handles, free-list slot reuse,
and mark-sweep collect_garbage(roots). Type checker now skips
registering the same symbol id twice for identical extern redeclarations
inlined from multiple imports (avoids phantom ambiguous-overload errors).

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 20, 2026 16:07

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Comment thread agc/src/semantic/typeck.rs Resolved
Comment thread std/rt/heap.ag
Comment on lines +389 to +391
// Invalidate all outstanding handles for this index (wrapping add).
self.generations.set(idx, self.generations.get(idx) + (u32)1);
self.free_list.push(handle.index);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Generation bump comment promises wrapping, code does not

The inline comment says "wrapping add" but the expression self.generations.get(idx) + (u32)1 is ordinary u32 addition. If Silver applies overflow checks in debug builds (or panics on unsigned overflow in any build mode), a slot freed exactly 2^32 times would trap rather than wrap. The same pattern appears in the GC sweep at line 453. If the intent is a guaranteed modular wrap, an explicit wrapping primitive (or at minimum a % (u32::MAX + 1) note) would match the documented contract.

@CierCier
CierCier merged commit c7b29d9 into main Jul 20, 2026
1 check passed
@CierCier
CierCier deleted the std/rt-gc-heap branch July 21, 2026 10:16
CierCier added a commit that referenced this pull request Aug 1, 2026
Port GC heap to std/rt + typeck extern dedupe (Wave 1 unit 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants