incular-core 0.1.1

Platform-independent foundation types for Incular
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
//! Build contexts, inherited values, and dependency-aware signals.
//!
//! The context is deliberately scheduler agnostic. A runtime can associate a
//! [`ConsumerId`] with an element and use [`BuildContext::take_dirty`] to
//! enqueue it; core only records dependencies and reports invalidation.

use std::{
    any::{Any, TypeId},
    cell::{Cell, RefCell},
    collections::{HashMap, HashSet},
    fmt,
    rc::{Rc, Weak},
    sync::atomic::{AtomicU64, Ordering},
};

static NEXT_CONSUMER: AtomicU64 = AtomicU64::new(1);
static NEXT_ENVIRONMENT: AtomicU64 = AtomicU64::new(1);
use crate::reactivity::{DependencySource, Subscription, TrackingGuard};

fn next_identity(counter: &AtomicU64, label: &'static str) -> u64 {
    counter
        .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
        .unwrap_or_else(|_| panic!("{label} identity space exhausted"))
}

fn next_revision(revision: u64) -> u64 {
    revision
        .checked_add(1)
        .expect("context dependency revision exhausted")
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum DependencyKey {
    Environment { environment: u64, type_id: TypeId },
}

#[derive(Default)]
struct TrackerInner {
    dependencies: RefCell<HashMap<ConsumerId, HashMap<u64, Subscription>>>,
    sources: RefCell<HashMap<DependencyKey, DependencySource>>,
    /// Environment source keys by source id, so clearing a consumer prunes
    /// only the sources it observed instead of scanning all of them.
    source_keys: RefCell<HashMap<u64, DependencyKey>>,
    dirty: RefCell<HashSet<ConsumerId>>,
    owners: RefCell<HashMap<ConsumerId, Weak<ConsumerOwner>>>,
}
impl TrackerInner {
    fn owner(self: &Rc<Self>, consumer: ConsumerId) -> Rc<ConsumerOwner> {
        let mut owners = self.owners.borrow_mut();
        if let Some(owner) = owners.get(&consumer).and_then(Weak::upgrade) {
            return owner;
        }
        let owner = Rc::new(ConsumerOwner {
            tracker: Rc::downgrade(self),
            consumer,
        });
        owners.insert(consumer, Rc::downgrade(&owner));
        owner
    }

    fn record(self: &Rc<Self>, consumer: ConsumerId, dependency: DependencyKey) {
        let source = self
            .sources
            .borrow_mut()
            .entry(dependency)
            .or_insert_with(|| {
                let source = DependencySource::default();
                self.source_keys
                    .borrow_mut()
                    .insert(source.id(), dependency);
                source
            })
            .clone();
        self.record_source(consumer, source);
    }
    fn record_source(self: &Rc<Self>, consumer: ConsumerId, source: DependencySource) {
        let mut dependencies = self.dependencies.borrow_mut();
        dependencies
            .entry(consumer)
            .or_default()
            .entry(source.id())
            .or_insert_with(|| {
                let weak = Rc::downgrade(self);
                source.subscribe(consumer, move || {
                    if let Some(tracker) = weak.upgrade() {
                        tracker.dirty.borrow_mut().insert(consumer);
                    }
                })
            });
    }
    fn clear(&self, consumer: ConsumerId) {
        self.dirty.borrow_mut().remove(&consumer);
        let Some(subscriptions) = self.dependencies.borrow_mut().remove(&consumer) else {
            return;
        };
        let ids: Vec<u64> = subscriptions.keys().copied().collect();
        // Dropping the subscriptions unsubscribes them; an environment
        // source nobody observes any more is then released.
        drop(subscriptions);
        let mut sources = self.sources.borrow_mut();
        let mut keys = self.source_keys.borrow_mut();
        for id in ids {
            if let Some(key) = keys.get(&id).copied()
                && sources
                    .get(&key)
                    .is_some_and(|source| source.subscriber_count() == 0)
            {
                sources.remove(&key);
                keys.remove(&id);
            }
        }
    }
    fn invalidate(&self, dependency: DependencyKey) {
        let source = self.sources.borrow().get(&dependency).cloned();
        if let Some(source) = source {
            source.notify();
        }
    }
    fn dependency_count(&self, consumer: ConsumerId) -> usize {
        self.dependencies
            .borrow()
            .get(&consumer)
            .map_or(0, HashMap::len)
    }
    fn is_dirty(&self, consumer: ConsumerId) -> bool {
        self.dirty.borrow().contains(&consumer)
    }
    fn take_dirty(&self, consumer: ConsumerId) -> bool {
        self.dirty.borrow_mut().remove(&consumer)
    }
    fn take_all_dirty(&self) -> Vec<ConsumerId> {
        self.dirty.borrow_mut().drain().collect()
    }
}

struct ConsumerOwner {
    tracker: Weak<TrackerInner>,
    consumer: ConsumerId,
}
impl Drop for ConsumerOwner {
    fn drop(&mut self) {
        if let Some(tracker) = self.tracker.upgrade() {
            tracker.clear(self.consumer);
            tracker.owners.borrow_mut().remove(&self.consumer);
        }
    }
}

struct Environment {
    id: u64,
    parent: Option<Rc<Environment>>,
    values: RefCell<HashMap<TypeId, Rc<dyn Any>>>,
    revision: Cell<u64>,
}

impl Environment {
    fn root() -> Rc<Self> {
        Rc::new(Self {
            id: next_identity(&NEXT_ENVIRONMENT, "environment"),
            parent: None,
            values: RefCell::new(HashMap::new()),
            revision: Cell::new(0),
        })
    }

    fn child(parent: &Rc<Self>) -> Rc<Self> {
        Rc::new(Self {
            id: next_identity(&NEXT_ENVIRONMENT, "environment"),
            parent: Some(parent.clone()),
            values: RefCell::new(HashMap::new()),
            revision: Cell::new(0),
        })
    }

    fn lookup(&self, type_id: TypeId) -> Option<(u64, Rc<dyn Any>)> {
        if let Some(value) = self.values.borrow().get(&type_id) {
            return Some((self.id, value.clone()));
        }
        self.parent.as_deref()?.lookup(type_id)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ConsumerId(u64);

impl ConsumerId {
    #[must_use]
    pub fn new() -> Self {
        Self(next_identity(&NEXT_CONSUMER, "context consumer"))
    }

    #[must_use]
    pub const fn from_raw(value: u64) -> Self {
        Self(value)
    }

    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }
}

impl Default for ConsumerId {
    fn default() -> Self {
        Self::new()
    }
}

/// A read-only summary of the dependencies currently collected for a context.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct DependencySnapshot {
    count: usize,
    dirty: bool,
}

impl DependencySnapshot {
    #[must_use]
    pub const fn count(self) -> usize {
        self.count
    }

    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.count == 0
    }

    #[must_use]
    pub const fn is_dirty(self) -> bool {
        self.dirty
    }
}

struct ActiveScope {
    tracker: Rc<TrackerInner>,
    consumer: ConsumerId,
}

thread_local! {
    static ACTIVE_SCOPES: RefCell<Vec<ActiveScope>> = const { RefCell::new(Vec::new()) };
}

/// A scoped build context. Cloning a context keeps the same consumer identity;
/// [`BuildContext::for_consumer`] creates a distinct dependency owner.
#[derive(Clone)]
pub struct BuildContext {
    _owner: Rc<ConsumerOwner>,
    environment: Rc<Environment>,
    tracker: Rc<TrackerInner>,
    consumer: ConsumerId,
}

impl fmt::Debug for BuildContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BuildContext")
            .field("consumer", &self.consumer)
            .field("dependency_count", &self.dependency_count())
            .field("dirty", &self.is_dirty())
            .finish()
    }
}

impl Default for BuildContext {
    fn default() -> Self {
        Self::new()
    }
}

impl BuildContext {
    /// Creates an empty root context with a fresh dependency consumer.
    #[must_use]
    pub fn new() -> Self {
        Self::for_consumer(ConsumerId::new())
    }

    /// Creates an empty root context for a caller-owned consumer identity.
    #[must_use]
    pub fn for_consumer(consumer: ConsumerId) -> Self {
        let tracker = Rc::new(TrackerInner::default());
        Self {
            _owner: tracker.owner(consumer),
            environment: Environment::root(),
            tracker,
            consumer,
        }
    }

    /// Creates another dependency owner that observes the same retained
    /// inherited environment and shares this context's dependency tracker.
    #[must_use]
    pub fn for_related_consumer(&self, consumer: ConsumerId) -> Self {
        Self {
            _owner: self.tracker.owner(consumer),
            environment: self.environment.clone(),
            tracker: self.tracker.clone(),
            consumer,
        }
    }

    /// Creates an explicit inherited lookup boundary for another consumer.
    /// Values above this point are not visible, while dependency invalidation
    /// remains in the same retained-tree tracker.
    #[must_use]
    pub fn boundary_for_consumer(&self, consumer: ConsumerId) -> Self {
        Self {
            _owner: self.tracker.owner(consumer),
            environment: Environment::root(),
            tracker: self.tracker.clone(),
            consumer,
        }
    }

    /// Returns the identity used for dependency invalidation.
    #[must_use]
    pub const fn consumer_id(&self) -> ConsumerId {
        self.consumer
    }

    /// Creates a child environment. Values in the child shadow values in its
    /// parent while keeping the same dependency tracker and consumer.
    #[must_use]
    pub fn child(&self) -> Self {
        Self {
            _owner: self._owner.clone(),
            environment: Environment::child(&self.environment),
            tracker: self.tracker.clone(),
            consumer: self.consumer,
        }
    }

    /// Creates a child context with one inherited value.
    #[must_use]
    pub fn provide<T: Any>(&self, value: T) -> Self {
        let child = self.child();
        child.insert(value);
        child
    }

    /// Creates a child environment from a type-erased framework value. This is
    /// the retained-tree integration point; application-facing APIs should use
    /// typed `provide`/lookup methods instead.
    #[doc(hidden)]
    #[must_use]
    pub fn provide_erased(&self, type_id: TypeId, value: Rc<dyn Any>) -> Self {
        let child = self.child();
        child.environment.values.borrow_mut().insert(type_id, value);
        child
    }

    /// Replaces a local type-erased value and invalidates only consumers that
    /// subscribed to this exact retained environment/type key.
    #[doc(hidden)]
    pub fn set_erased(&self, type_id: TypeId, value: Rc<dyn Any>) {
        self.environment.values.borrow_mut().insert(type_id, value);
        self.environment
            .revision
            .set(next_revision(self.environment.revision.get()));
        self.tracker.invalidate(DependencyKey::Environment {
            environment: self.environment.id,
            type_id,
        });
    }

    /// Inserts or replaces a value in this environment. Existing consumers
    /// that watched this type are marked dirty when the value changes.
    pub fn insert<T: Any>(&self, value: T) -> bool {
        let type_id = TypeId::of::<T>();
        self.environment
            .values
            .borrow_mut()
            .insert(type_id, Rc::new(value));
        self.environment
            .revision
            .set(next_revision(self.environment.revision.get()));
        self.tracker.invalidate(DependencyKey::Environment {
            environment: self.environment.id,
            type_id,
        });
        true
    }

    /// Replaces a value only when its `PartialEq` value changed.
    pub fn set<T: Any + PartialEq>(&self, value: T) -> bool {
        let type_id = TypeId::of::<T>();
        let changed = self
            .environment
            .values
            .borrow()
            .get(&type_id)
            .and_then(|old| old.downcast_ref::<T>())
            .is_none_or(|old| old != &value);
        if changed {
            self.insert(value);
        }
        changed
    }

    /// Removes a value from this environment.
    pub fn remove<T: Any>(&self) -> bool {
        let type_id = TypeId::of::<T>();
        let removed = self
            .environment
            .values
            .borrow_mut()
            .remove(&type_id)
            .is_some();
        if removed {
            self.environment
                .revision
                .set(next_revision(self.environment.revision.get()));
            self.tracker.invalidate(DependencyKey::Environment {
                environment: self.environment.id,
                type_id,
            });
        }
        removed
    }

    #[must_use]
    pub fn contains<T: Any>(&self) -> bool {
        self.lookup_value(TypeId::of::<T>()).is_some()
    }

    #[must_use]
    pub fn revision(&self) -> u64 {
        self.environment.revision.get()
    }

    fn lookup_value(&self, type_id: TypeId) -> Option<(u64, Rc<dyn Any>)> {
        self.environment.lookup(type_id)
    }

    /// Reads an inherited value without recording a dependency.
    #[must_use]
    pub fn read<T: Any + Clone>(&self) -> Option<T> {
        self.read_shared::<T>().map(|value| (*value).clone())
    }

    /// Alias for [`BuildContext::read`].
    #[must_use]
    pub fn get<T: Any + Clone>(&self) -> Option<T> {
        self.read()
    }

    /// Reads an inherited value as shared ownership without recording a
    /// dependency.
    #[must_use]
    pub fn read_shared<T: Any>(&self) -> Option<Rc<T>> {
        self.lookup_value(TypeId::of::<T>())
            .and_then(|(_, value)| value.downcast::<T>().ok())
    }

    fn record_environment(&self, type_id: TypeId) {
        let environment = self
            .lookup_value(type_id)
            .map_or(self.environment.id, |(environment, _)| environment);
        with_active_scope(|scope| {
            scope.tracker.record(
                scope.consumer,
                DependencyKey::Environment {
                    environment,
                    type_id,
                },
            );
        })
        .unwrap_or_else(|| {
            self.tracker.record(
                self.consumer,
                DependencyKey::Environment {
                    environment,
                    type_id,
                },
            )
        });
    }

    /// Reads a value and records the environment lookup as a dependency.
    #[must_use]
    pub fn depend<T: Any + Clone>(&self) -> Option<T> {
        self.record_environment(TypeId::of::<T>());
        self.read()
    }

    /// Reads a shared inherited value while recording the dependency without
    /// cloning the value itself.
    #[must_use]
    pub fn depend_shared<T: Any>(&self) -> Option<Rc<T>> {
        self.record_environment(TypeId::of::<T>());
        self.read_shared()
    }

    /// Alias for [`BuildContext::depend`], matching reactive UI terminology.
    #[must_use]
    pub fn watch<T: Any + Clone>(&self) -> Option<T> {
        self.depend()
    }

    /// Enters this context as the active build scope. Signal reads made while
    /// the guard is alive are associated with this context's consumer.
    #[must_use]
    pub fn enter(&self) -> ContextGuard {
        ACTIVE_SCOPES.with(|scopes| {
            scopes.borrow_mut().push(ActiveScope {
                tracker: self.tracker.clone(),
                consumer: self.consumer,
            });
        });
        let tracker = self.tracker.clone();
        let consumer = self.consumer;
        ContextGuard {
            active: true,
            _owner: self._owner.clone(),
            _read_only: crate::reactivity::ReadOnlyGuard::enter(),
            _tracking: TrackingGuard::enter(move |source| tracker.record_source(consumer, source)),
        }
    }

    /// Alias for [`BuildContext::enter`].
    #[must_use]
    pub fn scope(&self) -> ContextGuard {
        self.enter()
    }

    /// Clears old dependencies, enters the build scope, and invokes the
    /// callback. This is the normal runtime integration point.
    pub fn build<R>(&self, callback: impl FnOnce(&BuildContext) -> R) -> R {
        self.clear_dependencies();
        let _guard = self.enter();
        callback(self)
    }

    /// Runs a closure in a fresh dependency collection. Use [`BuildContext::build`]
    /// when the callback needs the context as an argument.
    pub fn run<R>(&self, callback: impl FnOnce() -> R) -> R {
        self.clear_dependencies();
        let _guard = self.enter();
        callback()
    }

    /// Alias for [`BuildContext::build`].
    pub fn with_context<R>(&self, callback: impl FnOnce(&BuildContext) -> R) -> R {
        self.build(callback)
    }

    pub fn clear_dependencies(&self) {
        self.tracker.clear(self.consumer);
    }

    #[must_use]
    pub fn dependency_count(&self) -> usize {
        self.tracker.dependency_count(self.consumer)
    }

    #[must_use]
    pub fn is_dirty(&self) -> bool {
        self.tracker.is_dirty(self.consumer)
    }

    /// Takes and clears this consumer's invalidation bit.
    pub fn take_dirty(&self) -> bool {
        self.tracker.take_dirty(self.consumer)
    }

    /// Drains all dirty consumers that share this retained dependency tracker.
    /// Schedulers use this to translate precise inherited-value invalidations
    /// into their own element work queues.
    #[doc(hidden)]
    pub fn take_dirty_consumers(&self) -> Vec<ConsumerId> {
        self.tracker.take_all_dirty()
    }

    /// Whether this retained dependency tracker currently has invalidated
    /// consumers. Framework schedulers use this to request a frame without
    /// consuming the identities that reconciliation still needs to drain.
    #[doc(hidden)]
    #[must_use]
    pub fn has_dirty_consumers(&self) -> bool {
        !self.tracker.dirty.borrow().is_empty()
    }

    #[must_use]
    pub fn dependencies(&self) -> DependencySnapshot {
        DependencySnapshot {
            count: self.dependency_count(),
            dirty: self.is_dirty(),
        }
    }
}

/// Restores the previous active build scope when dropped.
pub struct ContextGuard {
    active: bool,
    _owner: Rc<ConsumerOwner>,
    _tracking: TrackingGuard,
    _read_only: crate::reactivity::ReadOnlyGuard,
}

impl Drop for ContextGuard {
    fn drop(&mut self) {
        if self.active {
            ACTIVE_SCOPES.with(|scopes| {
                let _ = scopes.borrow_mut().pop();
            });
            self.active = false;
        }
    }
}

fn with_active_scope<R>(callback: impl FnOnce(&ActiveScope) -> R) -> Option<R> {
    ACTIVE_SCOPES.with(|scopes| scopes.borrow().last().map(callback))
}