cljrs-value 0.2.33

Runtime Value type and persistent collections for clojurust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Heap promotion of region-allocated values at publish boundaries
//! (Phase 10.5 — the safety net that lets bump regions coexist with the
//! tracing GC).
//!
//! Escape analysis decides which allocations may live in a scratch region;
//! correctness must not depend on that analysis being perfect.  This module
//! is the runtime fallback: every store into a program-lifetime cell
//! (`Var::bind`, `Atom`, `Volatile`) and every cross-thread handoff runs the
//! value through [`publish_value`]:
//!
//! * **Clean** — the value visibly contains no region-allocated `GcPtr`s
//!   (the overwhelmingly common case; one pointer-tag scan).  Stored as-is.
//! * **Dirty** — a region-tagged box was found.  The value is deep-copied to
//!   the GC heap via the structured-clone machinery (`crate::clone`) and the
//!   copy is stored instead; the region originals die with their region.
//! * **Opaque** — the value (or a part of it) cannot be scanned or copied
//!   (closures, unrealized lazy seqs, native objects, region-allocated
//!   mutable cells whose identity a copy would break).  The publisher then
//!   *poisons* the thread's active regions
//!   ([`cljrs_gc::region::poison_active_regions`]): each is retired (kept
//!   alive forever and traced as a GC root) instead of reset when its scope
//!   closes — a deliberate bounded leak that can never dangle.
//!
//! The whole protocol short-circuits to a single thread-local depth check
//! when no region is active, which is the case for virtually every top-level
//! `def`.
//!
//! No-gc publication retains backing scopes without copying values. Replaceable
//! destinations release their ownership edges when the payload changes. Raw
//! program-lifetime publications retain their actual backing scopes.

use crate::Value;
#[cfg(not(feature = "no-gc"))]
use crate::clone::{deserialize, serialize};
#[cfg(not(feature = "no-gc"))]
use crate::types::{DelayState, LazySeqState};
#[cfg(not(feature = "no-gc"))]
use crate::value::{MapValue, SetValue};
#[cfg(not(feature = "no-gc"))]
use cljrs_gc::{GcPtr, Trace};

/// Scan verdict for one value graph.
#[cfg(not(feature = "no-gc"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Scan {
    /// No region-allocated box reachable.
    Clean,
    /// At least one region-allocated box found; all of it is copyable.
    Dirty,
    /// Contains something we can neither scan through nor deep-copy.
    Opaque,
}

#[cfg(not(feature = "no-gc"))]
impl Scan {
    fn join(self, other: Scan) -> Scan {
        use Scan::*;
        match (self, other) {
            (Opaque, _) | (_, Opaque) => Opaque,
            (Dirty, _) | (_, Dirty) => Dirty,
            _ => Clean,
        }
    }
}

/// Tag check for one box.
#[cfg(not(feature = "no-gc"))]
fn tag<T: Trace + 'static>(p: &GcPtr<T>) -> Scan {
    let dirty = p.is_region_alloc();
    if dirty { Scan::Dirty } else { Scan::Clean }
}

/// Like [`tag`] but for boxes whose pointee cannot be deep-copied (mutable
/// identity, closures, native state): a region-tagged box is unrecoverable.
#[cfg(not(feature = "no-gc"))]
fn tag_opaque<T: Trace + 'static>(p: &GcPtr<T>) -> Scan {
    if p.is_region_alloc() {
        Scan::Opaque
    } else {
        Scan::Clean
    }
}

#[cfg(not(feature = "no-gc"))]
fn scan_map(m: &MapValue) -> Scan {
    let mut acc = match m {
        MapValue::Array(p) => tag(p),
        MapValue::Hash(p) => tag(p),
        MapValue::Sorted(p) => tag(p),
    };
    m.for_each(|k, v| {
        acc = acc.join(scan(k)).join(scan(v));
    });
    acc
}

/// Scan a value graph for region-allocated boxes.
///
/// The conservative defaults matter more than the precise ones: anything we
/// cannot see through is `Opaque` *if* it could conceivably reference region
/// memory.  Heap-allocated mutable cells (`Atom`, `Volatile`, `Var`) are
/// `Clean` because their contents pass through this same barrier on every
/// store; heap closures and pending thunks are `Opaque` because their
/// captured environments are invisible here.
#[cfg(not(feature = "no-gc"))]
fn scan(v: &Value) -> Scan {
    use Scan::*;
    match v {
        // Immediates and Arc-backed values: nothing region-allocated.
        Value::Nil
        | Value::Bool(_)
        | Value::Long(_)
        | Value::Double(_)
        | Value::Char(_)
        | Value::ByteBlob(_)
        | Value::SharedAtom(_)
        | Value::Resource(_) => Clean,

        // Leaf boxes: copyable, no Value children.
        Value::BigInt(p) => tag(p),
        Value::BigDecimal(p) => tag(p),
        Value::Ratio(p) => tag(p),
        Value::Uuid(p) => tag(p),
        Value::Str(p) => tag(p),
        Value::Pattern(p) => tag(p),
        Value::Symbol(p) => tag(p),
        Value::Keyword(p) => tag(p),

        // Collections: box tag plus children.
        Value::List(p) => p.get().iter().fold(tag(p), |acc, e| acc.join(scan(e))),
        Value::Vector(p) => p.get().iter().fold(tag(p), |acc, e| acc.join(scan(e))),
        Value::Queue(p) => p.get().iter().fold(tag(p), |acc, e| acc.join(scan(e))),
        Value::Map(m) => scan_map(m),
        Value::Set(s) => {
            let t = match s {
                SetValue::Hash(p) => tag(p),
                SetValue::Sorted(p) => tag(p),
            };
            s.iter().fold(t, |acc, e| acc.join(scan(e)))
        }
        Value::Cons(p) => {
            let c = p.get();
            tag(p).join(scan(&c.head)).join(scan(&c.tail))
        }

        // Primitive arrays: contents are scalars; only the box matters.
        Value::IntArray(p) => tag(p),
        Value::LongArray(p) => tag(p),
        Value::ShortArray(p) => tag(p),
        Value::ByteArray(p) => tag(p),
        Value::FloatArray(p) => tag(p),
        Value::DoubleArray(p) => tag(p),
        Value::BooleanArray(p) => tag(p),
        Value::CharArray(p) => tag(p),
        Value::ObjectArray(p) => {
            let guard = p.get().0.lock().unwrap();
            guard.iter().fold(tag(p), |acc, e| acc.join(scan(e)))
        }

        // Wrappers.
        Value::WithMeta(inner, meta) => scan(inner).join(scan(meta)),
        Value::Reduced(inner) => scan(inner),

        // Records.
        Value::TypeInstance(p) => {
            if p.get().mutable.is_some() {
                Opaque
            } else {
                tag(p).join(scan_map(&p.get().fields))
            }
        }

        // Errors: box tag plus the data map / cause chain / thrown value.
        Value::Error(p) => {
            let mut acc = tag(p);
            let e = p.get();
            if let Some(data) = &e.data {
                acc = acc.join(scan_map(data));
            }
            if let crate::error::ValueError::Thrown(t) = &e.error {
                acc = acc.join(scan(t));
            }
            let mut cause = e.cause.clone();
            while let Some(c) = cause {
                acc = acc.join(tag(&c));
                if let Some(data) = &c.get().data {
                    acc = acc.join(scan_map(data));
                }
                cause = c.get().cause.clone();
            }
            acc
        }

        // Lazy cells: a realized cache is scannable; a pending thunk's
        // captured environment is not.
        Value::LazySeq(p) => {
            let t = tag_opaque(p);
            if t == Opaque {
                return Opaque;
            }
            match &*p.get().state.lock().unwrap() {
                LazySeqState::Forced(v) => t.join(scan(v)),
                LazySeqState::Error(_) => t,
                LazySeqState::Pending(_) | LazySeqState::Realizing { .. } => Opaque,
            }
        }
        Value::Delay(p) => {
            let t = tag_opaque(p);
            if t == Opaque {
                return Opaque;
            }
            match &*p.get().state.lock().unwrap() {
                DelayState::Forced(v) => t.join(scan(v)),
                DelayState::Pending(_) | DelayState::Realizing { .. } => Opaque,
                DelayState::Error(_) => t,
            }
        }

        // Mutable cells: identity-bearing, so a region-tagged box cannot be
        // promoted by copying.  Heap-allocated ones are Clean — every store
        // into them runs through this barrier itself.
        Value::Atom(p) => tag_opaque(p),
        Value::Volatile(p) => tag_opaque(p),
        Value::Var(p) => tag_opaque(p),
        Value::Promise(p) => tag_opaque(p),
        Value::Future(p) => tag_opaque(p),
        Value::Agent(p) => tag_opaque(p),
        Value::Namespace(p) => tag_opaque(p),
        Value::Protocol(p) => tag_opaque(p),

        // Closures and other callables: captured environments are invisible
        // here.  Under analysis-driven scopes captures are classified as
        // escaping (so they are never region-allocated), but we cannot verify
        // that locally — be conservative when one is published while a region
        // is open.
        Value::Fn(_)
        | Value::Macro(_)
        | Value::BoundFn(_)
        | Value::NativeFunction(_)
        | Value::ProtocolFn(_)
        | Value::MultiFn(_) => Opaque,

        // Mutable / native containers we cannot see through.
        Value::TransientMap(_)
        | Value::TransientSet(_)
        | Value::TransientVector(_)
        | Value::Matcher(_)
        | Value::NativeObject(_) => Opaque,
    }
}

/// Prepare `v` for publication into a program-lifetime cell (or another
/// thread): promote region-allocated parts to the GC heap, or poison the
/// active regions when the value is opaque to the scan.
///
/// Returns the value to store (the original, or its heap-promoted copy).
#[cfg(not(feature = "no-gc"))]
pub fn publish_value(v: Value) -> Value {
    // Fast path: no region open on this thread ⇒ nothing reachable from `v`
    // can be region-allocated (region values never outlive their region
    // except through exactly the publishes this barrier intercepts).
    if cljrs_gc::region::region_stack_depth() == 0
        || cljrs_gc::region::active_regions_are_poisoned()
    {
        return v;
    }
    // An opaque lazy tail poisons a scope once. Later cells need no graph
    // scan: every active region is already guaranteed to outlive its values.
    match scan(&v) {
        Scan::Clean => v,
        Scan::Dirty => match serialize(&v) {
            Ok(wire) => deserialize(wire),
            Err(_) => {
                cljrs_gc::region::poison_active_regions();
                v
            }
        },
        Scan::Opaque => {
            // Only poison when the opaque value could actually be holding
            // region memory; a fully-Clean graph with an opaque *leaf* is
            // still unverifiable, so this branch is reached for both.
            cljrs_gc::region::poison_active_regions();
            v
        }
    }
}

/// GC publication uses the same promotion barrier for every destination.
#[cfg(not(feature = "no-gc"))]
pub fn publish_for_owner(value: Value, _address: usize) -> Value {
    publish_value(value)
}

/// Retain actual backing scopes for an explicit program-lifetime result.
/// Values preserve their identity and laziness.
#[cfg(feature = "no-gc")]
pub fn publish_value(value: Value) -> Value {
    if !cljrs_gc::alloc_ctx::invocation_is_active() {
        cljrs_gc::retain_regions_for(&value);
    }
    value
}

#[cfg(feature = "no-gc")]
pub fn publish_for_owner(value: Value, address: usize) -> Value {
    publish_for_slot(value, address, 0)
}

/// Publish one independently replaceable mutable field or array index.
#[cfg(feature = "no-gc")]
pub fn publish_for_slot(value: Value, address: usize, slot: usize) -> Value {
    if cljrs_gc::alloc_ctx::invocation_is_active() {
        return value;
    }
    let (value, _compact) = compact_scalar(value);
    let lease = cljrs_gc::region::RegionLease::for_value(&value);
    cljrs_gc::region::AllocationOwner::for_address(address).set_slot(address, slot, &lease);
    value
}
#[cfg(not(feature = "no-gc"))]
pub fn publish_for_slot(value: Value, _address: usize, _slot: usize) -> Value {
    publish_value(value)
}
/// Publish a field identified by a stable application key.
pub fn publish_for_named_slot(value: Value, address: usize, slot: String) -> Value {
    #[cfg(feature = "no-gc")]
    {
        if cljrs_gc::alloc_ctx::invocation_is_active() {
            return value;
        }
        let (value, _compact) = compact_scalar(value);
        let lease = cljrs_gc::region::RegionLease::for_value(&value);
        cljrs_gc::region::AllocationOwner::for_address(address).set_slot(address, slot, &lease);
        value
    }
    #[cfg(not(feature = "no-gc"))]
    {
        let _ = (address, slot);
        publish_value(value)
    }
}
/// Protect a previously published slot while its caller uses the returned value.
pub fn read_slot(address: usize, slot: usize) {
    #[cfg(feature = "no-gc")]
    cljrs_gc::region::AllocationOwner::for_address(address).read_slot(address, slot);
    #[cfg(not(feature = "no-gc"))]
    let _ = (address, slot);
}

/// Borrow a named field while its returned value is in use.
pub fn read_named_slot(address: usize, slot: String) {
    #[cfg(feature = "no-gc")]
    cljrs_gc::region::AllocationOwner::for_address(address).read_slot(address, slot);
    #[cfg(not(feature = "no-gc"))]
    let _ = (address, slot);
}

/// Release cached slots before their containing object is destroyed.
pub fn clear_slots(address: usize) {
    #[cfg(feature = "no-gc")]
    cljrs_gc::region::AllocationOwner::for_address(address).clear_slots(address);
    #[cfg(not(feature = "no-gc"))]
    let _ = address;
}

/// A payload snapshot held across a callback or replacement.
pub struct ValueSnapshot {
    pub value: Value,
    #[cfg(feature = "no-gc")]
    pub(crate) lease: cljrs_gc::region::RegionLease,
}
impl ValueSnapshot {
    pub fn protect_current(&self) {
        #[cfg(feature = "no-gc")]
        self.lease.protect_read();
    }
}

/// Cached backing scopes for a replaceable payload. Regional containers use
/// replaceable weak edges, while permanent containers own their current payload.
#[cfg(feature = "no-gc")]
#[derive(Debug, Default)]
pub struct ValueLease {
    owned: Option<cljrs_gc::region::RegionLease>,
    scoped: cljrs_gc::region::RegionDependency,
}
#[cfg(feature = "no-gc")]
impl ValueLease {
    pub(crate) fn for_trace(
        value: &impl cljrs_gc::Trace,
        owner: &cljrs_gc::region::AllocationOwner,
    ) -> Self {
        if cljrs_gc::alloc_ctx::invocation_is_active() {
            return Self::default();
        }
        Self::from_lease(cljrs_gc::region::RegionLease::for_value(value), owner)
    }
    pub fn for_values(values: &[Value], owner: &cljrs_gc::region::AllocationOwner) -> Self {
        if cljrs_gc::alloc_ctx::invocation_is_active() {
            return Self::default();
        }
        Self::from_lease(cljrs_gc::region::RegionLease::for_values(values), owner)
    }
    fn from_lease(
        lease: cljrs_gc::region::RegionLease,
        owner: &cljrs_gc::region::AllocationOwner,
    ) -> Self {
        if owner.is_permanent() {
            Self {
                owned: Some(lease),
                scoped: Default::default(),
            }
        } else {
            Self {
                scoped: owner.replaceable(&lease),
                owned: None,
            }
        }
    }
    pub fn snapshot(&self) -> cljrs_gc::region::RegionLease {
        self.owned
            .as_ref()
            .cloned()
            .unwrap_or_else(|| self.scoped.snapshot())
    }
    pub(crate) fn reparent(&self, owner: &cljrs_gc::region::AllocationOwner) -> Self {
        Self::from_lease(self.snapshot(), owner)
    }
    pub fn protect_read(&self) {
        if let Some(lease) = &self.owned {
            lease.protect_read();
        } else {
            self.scoped.protect_read();
        }
    }
    pub fn publish_return(&self) {
        if let Some(lease) = &self.owned {
            lease.publish_return();
        } else {
            self.scoped.snapshot().publish_return();
        }
    }
    pub fn protect_current(&self) {
        if let Some(lease) = &self.owned {
            lease.protect_current();
        } else {
            self.scoped.snapshot().protect_current();
        }
    }
}

// Immutable leaf copies retain their logical identity. Collections and mutable
// values keep their allocation identity and structural sharing unchanged.
#[cfg(feature = "no-gc")]
fn compact_scalar(value: Value) -> (Value, Option<cljrs_gc::alloc_ctx::ScratchGuard>) {
    macro_rules! copy_leaf {
        ($pointer:expr, $variant:path) => {{
            let pointer = $pointer;
            if pointer.is_static_alloc() || pointer.is_relocated_immutable() {
                return ($variant(pointer), None);
            }
            let arena = cljrs_gc::alloc_ctx::ScratchGuard::with_capacity(
                std::mem::size_of_val(pointer.get()) + 32,
            );
            // SAFETY: each matched type is an immutable scalar with a value-preserving Clone.
            let copy = unsafe { pointer.clone_immutable() };
            return ($variant(copy), Some(arena));
        }};
    }
    match value {
        Value::Str(p) if p.get().len() <= 4096 => copy_leaf!(p, Value::Str),
        Value::Uuid(p) => copy_leaf!(p, Value::Uuid),
        Value::BigInt(p) if p.get().bits() <= 32768 => copy_leaf!(p, Value::BigInt),
        Value::Ratio(p)
            if p.get()
                .numer()
                .bits()
                .saturating_add(p.get().denom().bits())
                <= 32768 =>
        {
            copy_leaf!(p, Value::Ratio)
        }
        other => (other, None),
    }
}

#[cfg(feature = "no-gc")]
pub(crate) fn prepare_definition(
    value: Value,
    owner: &cljrs_gc::region::AllocationOwner,
) -> (Value, ValueLease) {
    if cljrs_gc::alloc_ctx::invocation_is_active() {
        return prepare_for_owner(value, owner);
    }
    // Bound compaction by both work and depth. Large/shared payloads keep
    // their persistent representation and acquire ownership without rebuilding it.
    fn worth_copying(value: &Value) -> bool {
        let mut pending = vec![(value.clone(), 0usize)];
        let mut remaining = 128usize;
        let mut needs_copy = false;
        while let Some((value, depth)) = pending.pop() {
            if remaining == 0 || depth > 32 {
                return false;
            }
            remaining -= 1;
            macro_rules! leaf {
                ($p:expr, $bounded:expr) => {{
                    let p = $p;
                    if !p.is_static_alloc() && !p.is_relocated_immutable() {
                        if !$bounded {
                            return false;
                        }
                        needs_copy = true;
                    }
                }};
            }
            macro_rules! children {
                ($p:expr, $iter:expr) => {{
                    let p = $p;
                    if !p.is_static_alloc() && !p.is_relocated_immutable() {
                        needs_copy = true;
                        for child in $iter(&p) {
                            if pending.len() >= remaining {
                                return false;
                            }
                            pending.push((child, depth + 1));
                        }
                    }
                }};
            }
            match value {
                Value::Str(p) => {
                    let bounded = p.get().len() <= 4096;
                    leaf!(p, bounded);
                }
                Value::BigInt(p) => {
                    let bounded = p.get().bits() <= 32768;
                    leaf!(p, bounded);
                }
                Value::Ratio(p) => {
                    let bounded = p
                        .get()
                        .numer()
                        .bits()
                        .saturating_add(p.get().denom().bits())
                        <= 32768;
                    leaf!(p, bounded);
                }
                Value::BigDecimal(p) => {
                    let bounded = p.get().digits() <= 9865;
                    leaf!(p, bounded);
                }
                Value::Uuid(p) => leaf!(p, true),
                Value::Symbol(p) => leaf!(p, true),
                Value::Keyword(p) => leaf!(p, true),
                Value::Cons(p) => children!(p, |p: &cljrs_gc::GcPtr<crate::CljxCons>| [
                    p.get().head.clone(),
                    p.get().tail.clone()
                ]),
                Value::Vector(p) => children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentVector>| p
                    .get()
                    .iter()
                    .take(129)
                    .cloned()
                    .collect::<Vec<_>>()),
                Value::List(p) => children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentList>| p
                    .get()
                    .iter()
                    .take(129)
                    .cloned()
                    .collect::<Vec<_>>()),
                Value::Queue(p) => children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentQueue>| p
                    .get()
                    .iter()
                    .take(129)
                    .cloned()
                    .collect::<Vec<_>>()),
                Value::Map(crate::MapValue::Array(p)) => {
                    children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentArrayMap>| p
                        .get()
                        .iter()
                        .take(65)
                        .flat_map(|(k, v)| [k.clone(), v.clone()])
                        .collect::<Vec<_>>())
                }
                Value::Map(crate::MapValue::Hash(p)) => {
                    children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentHashMap>| p
                        .get()
                        .iter()
                        .take(65)
                        .flat_map(|(k, v)| [k.clone(), v.clone()])
                        .collect::<Vec<_>>())
                }
                Value::Set(crate::SetValue::Hash(p)) => {
                    children!(p, |p: &cljrs_gc::GcPtr<crate::PersistentHashSet>| p
                        .get()
                        .iter()
                        .take(129)
                        .cloned()
                        .collect::<Vec<_>>())
                }
                _ => {}
            }
        }
        needs_copy
    }
    if !worth_copying(&value) {
        return prepare_for_owner(value, owner);
    }
    let _compact = cljrs_gc::alloc_ctx::ScratchGuard::with_capacity(256);
    fn copy(value: Value, memo: &mut std::collections::HashMap<usize, Value>) -> Value {
        macro_rules! leaf {
            ($pointer:expr, $variant:path) => {{
                let p = $pointer;
                if p.is_static_alloc() || p.is_relocated_immutable() {
                    return $variant(p);
                }
                let address = p.get() as *const _ as usize;
                if let Some(value) = memo.get(&address) {
                    return value.clone();
                }
                // SAFETY: this is an immutable leaf; cloning preserves its value.
                let value = $variant(unsafe { p.clone_immutable() });
                memo.insert(address, value.clone());
                value
            }};
        }
        macro_rules! collection {
            ($pointer:expr, $variant:expr, $data:expr) => {{
                let p = $pointer;
                let address = p.get() as *const _ as usize;
                if p.is_static_alloc() || p.is_relocated_immutable() {
                    ($variant)(p)
                } else if let Some(value) = memo.get(&address) {
                    value.clone()
                } else {
                    let data = $data(&p, memo);
                    // SAFETY: only immutable collections are rebuilt; every child's identity is preserved.
                    let value = ($variant)(unsafe { p.relocate_immutable(data) });
                    memo.insert(address, value.clone());
                    value
                }
            }};
        }
        match value {
            Value::Str(p) => leaf!(p, Value::Str),
            Value::Uuid(p) => leaf!(p, Value::Uuid),
            Value::BigInt(p) => leaf!(p, Value::BigInt),
            Value::BigDecimal(p) => leaf!(p, Value::BigDecimal),
            Value::Ratio(p) => leaf!(p, Value::Ratio),
            Value::Symbol(p) => leaf!(p, Value::Symbol),
            Value::Keyword(p) => leaf!(p, Value::Keyword),
            Value::Queue(p) => collection!(
                p,
                Value::Queue,
                |p: &cljrs_gc::GcPtr<crate::PersistentQueue>, memo: &mut _| {
                    p.get()
                        .iter()
                        .cloned()
                        .fold(crate::PersistentQueue::empty(), |queue, value| {
                            queue.conj(copy(value, memo))
                        })
                }
            ),
            Value::Cons(p) => collection!(
                p,
                Value::Cons,
                |p: &cljrs_gc::GcPtr<crate::CljxCons>, memo: &mut _| crate::CljxCons {
                    head: copy(p.get().head.clone(), memo),
                    tail: copy(p.get().tail.clone(), memo)
                }
            ),
            Value::List(p) => collection!(
                p,
                Value::List,
                |p: &cljrs_gc::GcPtr<crate::PersistentList>, memo: &mut _| {
                    crate::PersistentList::from_iter(p.get().iter().cloned().map(|v| copy(v, memo)))
                }
            ),
            Value::Vector(p) => collection!(
                p,
                Value::Vector,
                |p: &cljrs_gc::GcPtr<crate::PersistentVector>, memo: &mut _| {
                    let values: Vec<_> = p.get().iter().cloned().map(|v| copy(v, memo)).collect();
                    if p.get().is_map_entry() {
                        crate::PersistentVector::map_entry(values[0].clone(), values[1].clone())
                    } else {
                        crate::PersistentVector::from_iter(values)
                    }
                }
            ),
            Value::Map(crate::MapValue::Array(p)) => collection!(
                p,
                |p| Value::Map(crate::MapValue::Array(p)),
                |p: &cljrs_gc::GcPtr<crate::PersistentArrayMap>, memo: &mut _| {
                    let crate::collections::array_map::AssocResult::Array(map) =
                        crate::PersistentArrayMap::from_pairs(
                            p.get()
                                .iter()
                                .map(|(k, v)| (copy(k.clone(), memo), copy(v.clone(), memo))),
                        )
                    else {
                        unreachable!("compaction preserves map keys")
                    };
                    map
                }
            ),
            Value::Map(crate::MapValue::Hash(p)) => collection!(
                p,
                |p| Value::Map(crate::MapValue::Hash(p)),
                |p: &cljrs_gc::GcPtr<crate::PersistentHashMap>, memo: &mut _| {
                    crate::PersistentHashMap::from_pairs(
                        p.get()
                            .iter()
                            .map(|(k, v)| (copy(k.clone(), memo), copy(v.clone(), memo))),
                    )
                }
            ),
            Value::Set(crate::SetValue::Hash(p)) => collection!(
                p,
                |p| Value::Set(crate::SetValue::Hash(p)),
                |p: &cljrs_gc::GcPtr<crate::PersistentHashSet>, memo: &mut _| {
                    crate::PersistentHashSet::from_iter(
                        p.get().iter().cloned().map(|v| copy(v, memo)),
                    )
                }
            ),
            other => other,
        }
    }
    let value = copy(value, &mut Default::default());
    prepare_for_owner(value, owner)
}

/// Prepare a replaceable payload without copying identity-bearing values.
#[cfg(feature = "no-gc")]
pub fn prepare_for_owner(
    value: Value,
    owner: &cljrs_gc::region::AllocationOwner,
) -> (Value, ValueLease) {
    use cljrs_gc::region::RegionLease;
    if cljrs_gc::alloc_ctx::invocation_is_active() {
        return (value, Default::default());
    }
    let (value, _compact) = compact_scalar(value);
    let lease = RegionLease::for_value(&value);
    let cached = ValueLease::from_lease(lease, owner);
    (value, cached)
}

/// Transfer a result into its caller without retaining unrelated scratch data.
#[cfg(feature = "no-gc")]
pub fn publish_return(value: Value) -> Value {
    if cljrs_gc::alloc_ctx::is_static_context() && !cljrs_gc::region::ReadScope::is_active() {
        publish_value(value)
    } else {
        cljrs_gc::region::RegionLease::for_value(&value).protect_current();
        value
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(all(test, not(feature = "no-gc")))]
mod tests {
    use super::*;
    use crate::PersistentVector;
    use cljrs_gc::region::{Region, RegionGuard};

    /// Allocate a vector value whose box lives in `region`.
    fn region_vec(region: &mut Region, items: Vec<Value>) -> Value {
        Value::Vector(region.alloc(PersistentVector::from_iter(items)))
    }

    #[test]
    fn clean_value_passes_through_untouched() {
        let mut region = Region::new();
        let _guard = unsafe { RegionGuard::new(&mut region) };
        let v = Value::Vector(GcPtr::new(PersistentVector::from_iter([Value::Long(1)])));
        let Value::Vector(before) = &v else { panic!() };
        let before = before.clone();
        let out = publish_value(v);
        let Value::Vector(after) = &out else { panic!() };
        assert!(
            GcPtr::ptr_eq(&before, after),
            "heap value must not be copied"
        );
    }

    #[test]
    fn region_value_is_promoted_to_heap() {
        let mut region = Region::new();
        let inner = region_vec(&mut region, vec![Value::Long(1), Value::Long(2)]);
        // A heap map containing a region-allocated vector: the barrier must
        // deep-copy the whole graph so nothing region-tagged is stored.
        let map = Value::Map(crate::MapValue::from_pairs(vec![(Value::Long(0), inner)]));
        let _guard = unsafe { RegionGuard::new(&mut region) };
        let out = publish_value(map);
        assert_eq!(scan(&out), Scan::Clean, "promoted copy must be heap-only");
        // Structure preserved.
        let Value::Map(m) = &out else { panic!() };
        let got = {
            let mut got = None;
            m.for_each(|_, v| got = Some(v.clone()));
            got.unwrap()
        };
        assert_eq!(
            got,
            Value::Vector(GcPtr::new(PersistentVector::from_iter([
                Value::Long(1),
                Value::Long(2)
            ])))
        );
    }

    #[test]
    fn no_active_region_short_circuits() {
        // Even a region-tagged value passes through when no region is active
        // on this thread (the barrier cannot help at that point; the fast
        // path must stay one thread-local read).
        let mut region = Region::new();
        let v = region_vec(&mut region, vec![Value::Long(5)]);
        let out = publish_value(v.clone());
        assert_eq!(out, v);
    }

    #[test]
    fn retained_regions_skip_repeated_publication_and_keep_values_alive() {
        let mut region = Box::new(Region::new());
        let child = region_vec(&mut region, vec![Value::Long(42)]);
        let value = Value::Vector(GcPtr::new(PersistentVector::from_iter([child])));
        unsafe { cljrs_gc::region::push_region_raw(region.as_mut() as *mut Region) };
        cljrs_gc::region::poison_active_regions();
        let out = publish_value(value.clone());
        let (Value::Vector(before), Value::Vector(after)) = (&value, &out) else {
            panic!()
        };
        assert!(
            GcPtr::ptr_eq(before, after),
            "retained graphs need no scan or copy"
        );
        cljrs_gc::region::close_region(region);
        assert_eq!(format!("{out}"), "[[42]]");
    }

    #[test]
    fn opaque_value_poisons_active_regions() {
        use std::sync::{Arc, Mutex};
        #[derive(Debug)]
        struct Tracked(Arc<Mutex<bool>>);
        impl Drop for Tracked {
            fn drop(&mut self) {
                *self.0.lock().unwrap() = true;
            }
        }
        impl Trace for Tracked {
            fn trace(&self, _: &mut cljrs_gc::MarkVisitor) {}
        }

        let dropped = Arc::new(Mutex::new(false));
        let mut region = Box::new(Region::new());
        region.alloc(Tracked(dropped.clone()));
        // An unrealized lazy seq is opaque to the scan.
        let lazy = {
            struct T;
            impl std::fmt::Debug for T {
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                    write!(f, "T")
                }
            }
            impl Trace for T {
                fn trace(&self, _: &mut cljrs_gc::MarkVisitor) {}
            }
            impl crate::types::Thunk for T {
                fn force(&self) -> Result<Value, String> {
                    Ok(Value::Nil)
                }
            }
            Value::LazySeq(GcPtr::new(crate::types::LazySeq::new(Box::new(T))))
        };

        unsafe { cljrs_gc::region::push_region_raw(region.as_mut() as *mut Region) };
        let _ = publish_value(lazy);
        cljrs_gc::region::close_region(region);
        assert!(
            !*dropped.lock().unwrap(),
            "publishing an opaque value must retire the active region"
        );
    }
}