@@ -0,0 +1,2288 @@
1+{-# LANGUAGE BangPatterns #-}
2+{-# LANGUAGE CPP #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE ExistentialQuantification #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
9+{-# LANGUAGE GADTs #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+{-# LANGUAGE LambdaCase #-}
12+{-# LANGUAGE MagicHash #-}
13+{-# LANGUAGE MultiParamTypeClasses #-}
14+{-# LANGUAGE MultiWayIf #-}
15+{-# LANGUAGE RankNTypes #-}
16+{-# LANGUAGE RecursiveDo #-}
17+{-# LANGUAGE RoleAnnotations #-}
18+{-# LANGUAGE ScopedTypeVariables #-}
19+{-# LANGUAGE TypeFamilies #-}
20+{-# LANGUAGE TypeOperators #-}
21+{-# LANGUAGE UnboxedTuples #-}
22+{-# LANGUAGE UndecidableInstances #-}
23+module Reflex.Spider.Internal (Spider, SpiderEnv (..), Global, SpiderHost, runSpiderHost, SpiderEventHandle (..), showSubscriberType, showEventType, ComputeM (..), MergeSubscribedParent (..), HasSpiderEnv (..), newSpiderEnv, SpiderPullM (..), SpiderPushM (..), ReadPhase (..)) where
24+
25+import Data.WeakBag (WeakBag, WeakBagTicket)
26+import qualified Data.WeakBag as WeakBag
27+import qualified Reflex.Class as R
28+import qualified Reflex.Host.Class as R
29+
30+import Control.Applicative
31+import Control.Concurrent
32+import Control.Exception
33+import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
34+import Control.Monad.Exception
35+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
36+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
37+import Control.Monad.Ref
38+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
39+import Data.Align
40+import Data.Dependent.Map (DMap, DSum (..))
41+import qualified Data.Dependent.Map as DMap
42+import Data.Foldable
43+import Data.Function
44+import Data.Functor.Compose
45+import Data.GADT.Compare
46+import Data.IntMap.Strict (IntMap)
47+import qualified Data.IntMap.Strict as IntMap
48+import Data.IORef
49+import Data.List
50+import Data.Maybe
51+import Data.Monoid ((<>))
52+import Data.Some (Some)
53+import qualified Data.Some as Some
54+import Data.These
55+import Data.Traversable
56+import System.Mem.Weak
57+
58+import GHC.Base (IO (..))
59+import GHC.IORef (IORef (..))
60+import GHC.Stack
61+
62+import Control.Monad.Primitive
63+import Data.Coerce
64+import System.IO.Unsafe
65+import Unsafe.Coerce
66+
67+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
68+import qualified Data.List.NonEmpty as NonEmpty
69+import Data.Tree (Forest, Tree (..), drawForest)
70+
71+-- Note: must come last to silence warnings due to AMP on GHC < 7.10
72+import Prelude hiding (any, concat, mapM, mapM_, sequence)
73+
74+type SubscriberList a = WeakBag (Subscriber a)
75+type SubscriberListTicket a = WeakBagTicket (Subscriber a)
76+
77+debugPropagate :: Bool
78+
79+debugInvalidateHeight :: Bool
80+
81+debugInvalidate :: Bool
82+
83+#ifdef DEBUG
84+
85+#define DEBUG_NODEIDS
86+
87+debugPropagate = True
88+
89+debugInvalidateHeight = False
90+
91+debugInvalidate = True
92+
93+class HasNodeId a where
94+ getNodeId :: a -> Int
95+
96+instance HasNodeId (Hold p a) where
97+ getNodeId = holdNodeId
98+
99+instance HasNodeId (PushSubscribed a b) where
100+ getNodeId = pushSubscribedNodeId
101+
102+instance HasNodeId (SwitchSubscribed a) where
103+ getNodeId = switchSubscribedNodeId
104+
105+instance HasNodeId (MergeSubscribed a) where
106+ getNodeId = mergeSubscribedNodeId
107+
108+instance HasNodeId (FanSubscribed a) where
109+ getNodeId = fanSubscribedNodeId
110+
111+instance HasNodeId (CoincidenceSubscribed a) where
112+ getNodeId = coincidenceSubscribedNodeId
113+
114+instance HasNodeId (RootSubscribed a) where
115+ getNodeId = rootSubscribedNodeId
116+
117+instance HasNodeId (Pull a) where
118+ getNodeId = pullNodeId
119+
120+{-# INLINE showNodeId #-}
121+showNodeId :: HasNodeId a => a -> String
122+showNodeId = ("#"<>) . show . getNodeId
123+
124+#else
125+
126+debugPropagate = False
127+
128+debugInvalidateHeight = False
129+
130+debugInvalidate = False
131+
132+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
133+{-# INLINE showNodeId #-}
134+showNodeId :: a -> String
135+showNodeId _ = ""
136+
137+#endif
138+
139+#ifdef DEBUG_NODEIDS
140+{-# NOINLINE nextNodeIdRef #-}
141+nextNodeIdRef :: IORef Int
142+nextNodeIdRef = unsafePerformIO $ newIORef 1
143+
144+newNodeId :: IO Int
145+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
146+
147+{-# NOINLINE unsafeNodeId #-}
148+unsafeNodeId :: a -> Int
149+unsafeNodeId a = unsafePerformIO $ do
150+ touch a
151+ newNodeId
152+#endif
153+
154+--TODO: Figure out why certain things are not 'representational', then make them representational so we can use coerce
155+--type role Hold representational
156+data Hold p a
157+ = Hold { holdValue :: !(IORef a)
158+ , holdInvalidators :: !(IORef [Weak Invalidator])
159+ , holdParent :: !(IORef (Either (Event (p a)) (EventSubscription (p a)))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
160+#ifdef DEBUG_NODEIDS
161+ , holdNodeId :: Int
162+#endif
163+ }
164+
165+data EventEnv x
166+ = EventEnv { eventEnvSpiderEnv :: !(SpiderEnv x)
167+ , eventEnvAssignments :: !(IORef [SomeAssignment]) -- Needed for Subscribe
168+ , eventEnvHoldInits :: !(IORef [SomeHoldInit]) -- Needed for Subscribe
169+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate])
170+ , eventEnvMergeInits :: !(IORef [SomeMergeInit]) -- Needed for Subscribe
171+ , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
172+ , eventEnvRootClears :: !(IORef [SomeRootClear])
173+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
174+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence]) -- Needed for Subscribe
175+ , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge]))
176+ }
177+
178+{-# INLINE runEventM #-}
179+runEventM :: EventM x a -> EventEnv x -> IO a
180+runEventM = runReaderT . unEventM
181+
182+class MonadIO m => Defer a m where
183+ getDeferralQueue :: m (IORef [a])
184+
185+{-# INLINE defer #-}
186+defer :: Defer a m => a -> m ()
187+defer a = do
188+ q <- getDeferralQueue
189+ liftIO $ modifyIORef' q (a:)
190+
191+instance Defer SomeAssignment (EventM x) where
192+ {-# INLINE getDeferralQueue #-}
193+ getDeferralQueue = EventM $ asks eventEnvAssignments
194+
195+instance Defer SomeHoldInit (EventM x) where
196+ {-# INLINE getDeferralQueue #-}
197+ getDeferralQueue = EventM $ asks eventEnvHoldInits
198+
199+instance Defer SomeHoldInit BehaviorM where
200+ {-# INLINE getDeferralQueue #-}
201+ getDeferralQueue = BehaviorM $ asks snd
202+
203+instance Defer SomeMergeUpdate (EventM x) where
204+ {-# INLINE getDeferralQueue #-}
205+ getDeferralQueue = EventM $ asks eventEnvMergeUpdates
206+
207+instance Defer SomeMergeInit (EventM x) where
208+ {-# INLINE getDeferralQueue #-}
209+ getDeferralQueue = EventM $ asks eventEnvMergeInits
210+
211+class HasCurrentHeight m where
212+ getCurrentHeight :: m Height
213+ scheduleMerge :: Height -> MergeSubscribed a -> m ()
214+
215+instance HasCurrentHeight (EventM x) where
216+ {-# INLINE getCurrentHeight #-}
217+ getCurrentHeight = EventM $ do
218+ heightRef <- asks eventEnvCurrentHeight
219+ liftIO $ readIORef heightRef
220+ {-# INLINE scheduleMerge #-}
221+ scheduleMerge height subscribed = EventM $ do
222+ delayedRef <- asks eventEnvDelayedMerges
223+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [DelayedMerge subscribed]
224+
225+class HasSpiderEnv x m | m -> x where
226+ askSpiderEnv :: m (SpiderEnv x)
227+
228+instance HasSpiderEnv x (EventM x) where
229+ {-# INLINE askSpiderEnv #-}
230+ askSpiderEnv = EventM $ asks eventEnvSpiderEnv
231+
232+instance HasSpiderEnv x (SpiderHost x) where
233+ {-# INLINE askSpiderEnv #-}
234+ askSpiderEnv = SpiderHost ask
235+
236+putCurrentHeight :: Height -> EventM x ()
237+putCurrentHeight h = EventM $ do
238+ heightRef <- asks eventEnvCurrentHeight
239+ liftIO $ writeIORef heightRef $! h
240+
241+instance Defer SomeClear (EventM x) where
242+ {-# INLINE getDeferralQueue #-}
243+ getDeferralQueue = EventM $ asks eventEnvClears
244+
245+{-# INLINE scheduleClear #-}
246+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
247+scheduleClear r = defer $ SomeClear r
248+
249+instance Defer SomeRootClear (EventM x) where
250+ {-# INLINE getDeferralQueue #-}
251+ getDeferralQueue = EventM $ asks eventEnvRootClears
252+
253+{-# INLINE scheduleRootClear #-}
254+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
255+scheduleRootClear r = defer $ SomeRootClear r
256+
257+instance Defer SomeResetCoincidence (EventM x) where
258+ {-# INLINE getDeferralQueue #-}
259+ getDeferralQueue = EventM $ asks eventEnvResetCoincidences
260+
261+-- Note: hold cannot examine its event until after the phase is over
262+{-# SPECIALIZE hold :: R.Patch p => a -> Event (p a) -> EventM x (Hold p a) #-}
263+{-# SPECIALIZE hold :: R.Patch p => a -> Event (p a) -> ComputeM (Hold p a) #-}
264+hold :: (R.Patch p, Defer SomeHoldInit m) => a -> Event (p a) -> m (Hold p a)
265+hold v0 e = do
266+ valRef <- liftIO $ newIORef v0
267+ invsRef <- liftIO $ newIORef []
268+ parentRef <- liftIO $ newIORef $ Left e
269+#ifdef DEBUG_NODEIDS
270+ nodeId <- liftIO newNodeId
271+#endif
272+ let h = Hold
273+ { holdValue = valRef
274+ , holdInvalidators = invsRef
275+ , holdParent = parentRef
276+#ifdef DEBUG_NODEIDS
277+ , holdNodeId = nodeId
278+#endif
279+ }
280+ defer $ SomeHoldInit h
281+ return h
282+
283+{-
284+mkWeakIORefKey :: IORef a -> b -> IO () -> IO (Weak b)
285+mkWeakIORefKey r@(IORef (STRef r#)) b (IO f) = IO $ \s ->
286+ case mkWeak# r# b f s of (# s1, w #) -> (# s1, Weak w #)
287+-}
288+
289+{-# INLINE getHoldEventSubscription #-}
290+getHoldEventSubscription :: forall m p a x. (Defer SomeAssignment m, Defer SomeHoldInit m, Defer SomeClear m, R.Patch p, HasCurrentHeight m, Defer SomeMergeInit m, Defer SomeResetCoincidence m, HasSpiderEnv x m) => Hold p a -> m (EventSubscription (p a))
291+getHoldEventSubscription h = do
292+ ep <- liftIO $ readIORef $ holdParent h
293+ case ep of
294+ Right subd -> return subd
295+ Left e -> do
296+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
297+ {-
298+ spiderEnv <- askSpiderEnv
299+ weakSubscriptionRef <- liftIO $ mkWeakIORef subscriptionRef $ return ()
300+ wh <- liftIO $ mkWeakIORefKey (holdValue h) h $ do
301+ msr <- deRefWeak weakSubscriptionRef
302+ forM_ msr $ \sr -> do
303+ subscription <- readIORef sr
304+ atomicModifyIORef (_spiderEnv_toUnsubscribe spiderEnv) $ \x -> (SomeEventSubscription subscription : x, ())
305+-- return ()
306+ {-
307+ -- What can we do? 1) Detect GCs at the SpiderEnv level, then go over the tree
308+ 2) Have a finalizer on every SubscriberListNode that only runs if its parent is still alive, and does a normal unsubscribe if so; this would seem to double the number of weakRefs we use, but perhaps not the weakDepth, so maybe it's OK; we will probably need to move the regular call to unsubscribe into the finalizer and then use finalize instead of that call; we can have a strong reference to the SubscriberListNode, which means we just need a single weak reference to each EventSubscribed, which we can reuse in all of the finalizers that need to (potentially) unsubscribe from it
309+-}
310+ -}
311+ subscription@(EventSubscription _ subd) <- subscribe e =<< liftIO (newSubscriberHold h)
312+ liftIO $ writeIORef subscriptionRef $! subscription
313+ occ <- liftIO $ readEventSubscribed subd
314+ case occ of
315+ Nothing -> return ()
316+ Just o -> do
317+ old <- liftIO $ readIORef $ holdValue h
318+ case R.apply o old of
319+ Nothing -> return ()
320+ Just new -> do
321+ -- Need to evaluate these so that we don't retain the Hold itself
322+ v <- liftIO $ evaluate $ holdValue h
323+ i <- liftIO $ evaluate $ holdInvalidators h
324+ defer $ SomeAssignment v i new
325+ liftIO $ writeIORef (holdParent h) $! Right subscription
326+ return subscription
327+
328+type BehaviorEnv = (Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]), IORef [SomeHoldInit])
329+
330+--type role BehaviorM representational
331+-- BehaviorM can sample behaviors
332+newtype BehaviorM a = BehaviorM { unBehaviorM :: ReaderT BehaviorEnv IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
333+
334+instance Monad BehaviorM where
335+ {-# INLINE (>>=) #-}
336+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
337+ {-# INLINE (>>) #-}
338+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
339+ {-# INLINE return #-}
340+ return x = BehaviorM $ return x
341+ {-# INLINE fail #-}
342+ fail s = BehaviorM $ fail s
343+
344+data BehaviorSubscribed a
345+ = forall p. BehaviorSubscribedHold (Hold p a)
346+ | BehaviorSubscribedPull (PullSubscribed a)
347+
348+data SomeBehaviorSubscribed = forall a. SomeBehaviorSubscribed (BehaviorSubscribed a)
349+
350+--type role PullSubscribed representational
351+data PullSubscribed a
352+ = PullSubscribed { pullSubscribedValue :: !a
353+ , pullSubscribedInvalidators :: !(IORef [Weak Invalidator])
354+ , pullSubscribedOwnInvalidator :: !Invalidator
355+ , pullSubscribedParents :: ![SomeBehaviorSubscribed] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
356+ }
357+
358+--type role Pull representational
359+data Pull a
360+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed a)))
361+ , pullCompute :: !(BehaviorM a)
362+#ifdef DEBUG_NODEIDS
363+ , pullNodeId :: Int
364+#endif
365+ }
366+
367+data Invalidator
368+ = forall a. InvalidatorPull (Pull a)
369+ | forall a. InvalidatorSwitch (SwitchSubscribed a)
370+
371+data RootSubscribed a = forall k. GCompare k => RootSubscribed
372+ { rootSubscribedKey :: !(k a)
373+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k RootSubscribed)) -- From the original Root
374+ , rootSubscribedSubscribers :: !(SubscriberList a)
375+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
376+ , rootSubscribedUninit :: IO ()
377+ , rootSubscribedWeakSelf :: !(IORef (Weak (RootSubscribed a))) --TODO: Can we make this a lazy non-IORef and then force it manually to avoid an indirection each time we use it?
378+#ifdef DEBUG_NODEIDS
379+ , rootSubscribedNodeId :: Int
380+#endif
381+ }
382+
383+data Root (k :: * -> *)
384+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
385+ , rootSubscribed :: !(IORef (DMap k RootSubscribed))
386+ , rootInit :: !(forall a. k a -> RootTrigger a -> IO (IO ()))
387+ }
388+
389+data SomeHoldInit = forall p a. R.Patch p => SomeHoldInit !(Hold p a)
390+
391+data SomeMergeUpdate = forall k. GCompare k => SomeMergeUpdate (R.PatchDMap (DMap k Event)) (MergeSubscribed k)
392+
393+data SomeMergeInit = forall k. GCompare k => SomeMergeInit !(MergeSubscribed k) !(Event (R.PatchDMap (DMap k Event)))
394+
395+data SomeEventSubscription = forall a. SomeEventSubscription (EventSubscription a)
396+
397+-- EventM can do everything BehaviorM can, plus create holds
398+newtype EventM x a = EventM { unEventM :: ReaderT (EventEnv x) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over
399+
400+data PushSubscribed a b
401+ = PushSubscribed { pushSubscribedCachedSubscribed :: !(IORef (Maybe (PushSubscribed a b)))
402+ , pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are)
403+ , pushSubscribedHeight :: !(IORef Height)
404+ , pushSubscribedSubscribers :: !(SubscriberList b)
405+ , pushSubscribedSelf :: !(Subscriber a) -- Hold this in memory to ensure our WeakReferences don't die --TODO: Probably unneeded now
406+ , pushSubscribedWeakSelf :: !(IORef (Weak (PushSubscribed a b)))
407+ , pushSubscribedParent :: !(EventSubscription a)
408+#ifdef DEBUG_NODEIDS
409+ , pushSubscribedNodeId :: Int
410+#endif
411+ }
412+
413+newtype ComputeM a = ComputeM { unComputeM :: ReaderT (IORef [SomeHoldInit]) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
414+
415+instance Defer SomeHoldInit ComputeM where
416+ getDeferralQueue = ComputeM ask
417+
418+{-# SPECIALIZE runComputeM :: ComputeM a -> EventM x a #-}
419+runComputeM :: Defer SomeHoldInit m => ComputeM a -> m a
420+runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
421+
422+data Push a b
423+ = Push { pushCompute :: !(a -> ComputeM (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed --TODO: This only uses Defer SomeHoldInit EventM; perhaps only the hold init queue should be passed in (also, perhaps those hold inits can be accelerated - can there be a loop we would need to worry about?)
424+ , pushParent :: !(Event a)
425+ , pushSubscribed :: !(IORef (Maybe (PushSubscribed a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
426+ }
427+
428+data MergeSubscribedParent k a
429+ = MergeSubscribedParent { mergeSubscribedParentSubscription :: !(EventSubscription a)
430+ , mergeSubscribedParentSubscriber :: !(Subscriber a)
431+ }
432+
433+data HeightBag = HeightBag
434+ { _heightBag_size :: {-# UNPACK #-} !Int
435+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
436+ }
437+ deriving (Show, Read, Eq, Ord)
438+
439+heightBagEmpty :: HeightBag
440+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
441+
442+heightBagSize :: HeightBag -> Int
443+heightBagSize = _heightBag_size
444+
445+heightBagFromList :: [Height] -> HeightBag
446+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
447+
448+heightBagAdd :: Height -> HeightBag -> HeightBag
449+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
450+
451+heightBagRemove :: Height -> HeightBag -> HeightBag
452+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
453+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
454+ Just old -> HeightBag (pred s) $ case old of
455+ 0 -> IntMap.delete h c
456+ _ -> IntMap.insert h (pred old) c
457+
458+heightBagMax :: HeightBag -> Height
459+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
460+ Just ((h, _), _) -> Height h
461+ Nothing -> zeroHeight
462+
463+heightBagVerify :: HeightBag -> HeightBag
464+#ifdef DEBUG
465+heightBagVerify b@(HeightBag s c) = if
466+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
467+ -> error $ "heightBagVerify: size doesn't match: " <> show b
468+ | unHeight invalidHeight `IntMap.member` c
469+ -> error $ "heightBagVerify: contains invalid height: " <> show b
470+ | otherwise -> b
471+#else
472+heightBagVerify = id
473+#endif
474+
475+data MergeSubscribed k
476+ = MergeSubscribed { mergeSubscribedCachedSubscribed :: !(IORef (Maybe (MergeSubscribed k))) -- From the original merge
477+ , mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
478+ , mergeSubscribedAccum :: !(IORef (DMap k Identity)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
479+ , mergeSubscribedHeight :: !(IORef Height)
480+ , mergeSubscribedHeightBag :: !(IORef HeightBag)
481+ , mergeSubscribedSubscribers :: !(SubscriberList (DMap k Identity))
482+ , mergeSubscribedChange :: !(IORef (Subscriber (R.PatchDMap (DMap k Event)), EventSubscribed (R.PatchDMap (DMap k Event))))
483+ , mergeSubscribedParents :: !(IORef (DMap k (MergeSubscribedParent k)))
484+ , mergeSubscribedWeakSelf :: !(IORef (Weak (MergeSubscribed k)))
485+#ifdef DEBUG_NODEIDS
486+ , mergeSubscribedNodeId :: Int
487+#endif
488+ }
489+
490+--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
491+data Merge k
492+ = Merge { mergeParents :: !(Dynamic R.PatchDMap (DMap k Event))
493+ , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed k)))
494+ }
495+
496+data FanSubscribedChildren k a = FanSubscribedChildren
497+ { _fanSubscribedChildren_list :: !(SubscriberList a)
498+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed k)
499+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed k)))
500+ }
501+
502+data FanSubscribed k
503+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed k)))
504+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren k))) -- This DMap should never be empty
505+ , fanSubscribedParent :: !(EventSubscription (DMap k Identity))
506+#ifdef DEBUG_NODEIDS
507+ , fanSubscribedNodeId :: Int
508+#endif
509+ }
510+
511+data Fan k
512+ = Fan { fanParent :: !(Event (DMap k Identity))
513+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed k)))
514+ }
515+
516+data SwitchSubscribed a
517+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed a)))
518+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
519+ , switchSubscribedHeight :: !(IORef Height)
520+ , switchSubscribedSubscribers :: !(SubscriberList a)
521+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !Invalidator
522+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak Invalidator))
523+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed])
524+ , switchSubscribedParent :: !(Behavior (Event a))
525+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription a))
526+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed a)))
527+#ifdef DEBUG_NODEIDS
528+ , switchSubscribedNodeId :: Int
529+#endif
530+ }
531+
532+data Switch a
533+ = Switch { switchParent :: !(Behavior (Event a))
534+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed a)))
535+ }
536+
537+data CoincidenceSubscribed a
538+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a)))
539+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
540+ , coincidenceSubscribedSubscribers :: !(SubscriberList a)
541+ , coincidenceSubscribedHeight :: !(IORef Height)
542+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber (Event a))
543+ , coincidenceSubscribedOuterParent :: !(EventSubscription (Event a))
544+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed a)))
545+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed a)))
546+#ifdef DEBUG_NODEIDS
547+ , coincidenceSubscribedNodeId :: Int
548+#endif
549+ }
550+
551+data Coincidence a
552+ = Coincidence { coincidenceParent :: !(Event (Event a))
553+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed a)))
554+ }
555+
556+data Subscriber a
557+ = forall b. SubscriberPush (a -> ComputeM (Maybe b)) (PushSubscribed a b) --TODO: Why does this have the pushCompute in it?
558+ | forall k. GCompare k => SubscriberMerge !(k a) (MergeSubscribed k) --TODO: Can we inline the GCompare?
559+ | forall k. (a ~ R.PatchDMap (DMap k Event), GCompare k) => SubscriberMergeChange (MergeSubscribed k)
560+ | forall k. (GCompare k, a ~ DMap k Identity) => SubscriberFan (FanSubscribed k)
561+ | forall p b. (a ~ p b, R.Patch p) => SubscriberHold !(Hold p b)
562+ | forall b. (a ~ Identity b) => SubscriberHoldIdentity !(Hold Identity b)
563+ | SubscriberSwitch (SwitchSubscribed a)
564+ | forall b. a ~ Event b => SubscriberCoincidenceOuter (CoincidenceSubscribed b)
565+ | SubscriberCoincidenceInner (CoincidenceSubscribed a)
566+ | SubscriberHandle
567+
568+showSubscriberType :: Subscriber a -> String
569+showSubscriberType = \case
570+ SubscriberPush _ _ -> "SubscriberPush"
571+ SubscriberMerge _ _ -> "SubscriberMerge"
572+ SubscriberFan _ -> "SubscriberFan"
573+ SubscriberMergeChange _ -> "SubscriberMergeChange"
574+ SubscriberHold _ -> "SubscriberHold"
575+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
576+ SubscriberSwitch _ -> "SubscriberSwitch"
577+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
578+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
579+ SubscriberHandle -> "SubscriberHandle"
580+
581+data Event a
582+ = forall k. GCompare k => EventRoot !(k a) !(Root k)
583+ | EventNever
584+ | forall b. EventPush !(Push b a)
585+ | forall k. (GCompare k, a ~ DMap k Identity) => EventMerge !(Merge k)
586+ | forall k. GCompare k => EventFan !(k a) !(Fan k)
587+ | EventSwitch !(Switch a)
588+ | EventCoincidence !(Coincidence a)
589+ | forall p b. (a ~ p b, R.Patch p) => EventHold !(Hold p b)
590+ | forall p b. (a ~ p b, R.Patch p) => EventDyn !(Dyn p b)
591+ | forall b. (a ~ Identity b) => EventHoldIdentity !(Hold Identity b)
592+ | forall b. (a ~ Identity b) => EventDynIdentity !(Dyn Identity b)
593+
594+showEventType :: Event a -> String
595+showEventType = \case
596+ EventRoot _ _ -> "EventRoot"
597+ EventNever -> "EventNever"
598+ EventPush _ -> "EventPush"
599+ EventMerge _ -> "EventMerge"
600+ EventFan _ _ -> "EventFan"
601+ EventSwitch _ -> "EventSwitch"
602+ EventCoincidence _ -> "EventCoincidence"
603+ EventHold _ -> "EventHold"
604+ EventDyn _ -> "EventDyn"
605+ EventHoldIdentity _ -> "EventHoldIdentity"
606+ EventDynIdentity _ -> "EventDynIdentity"
607+
608+data EventSubscription a = EventSubscription
609+ { _eventSubscription_ticket :: !(Maybe (SubscriberListTicket a))
610+ , _eventSubscription_subscribed :: !(EventSubscribed a)
611+ }
612+
613+data EventSubscribed a
614+ = EventSubscribedRoot {-# NOUNPACK #-} (RootSubscribed a)
615+ | EventSubscribedNever
616+ | forall b. EventSubscribedPush !(PushSubscribed b a)
617+ | forall k. (GCompare k, a ~ DMap k Identity) => EventSubscribedMerge !(MergeSubscribed k)
618+ | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed k)
619+ | EventSubscribedSwitch !(SwitchSubscribed a)
620+ | EventSubscribedCoincidence !(CoincidenceSubscribed a)
621+
622+unsubscribe :: EventSubscription a -> IO ()
623+unsubscribe (EventSubscription msln _) = forM_ msln $ \sln -> WeakBag.remove sln
624+
625+-- These function are constructor functions that are marked NOINLINE so they are
626+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
627+-- so any weak references that are attached to the constructors will have their
628+-- finalizer run. Using the opaque constructor, does not see the
629+-- constructor application, so it behaves like an IORef and cannot be fused away.
630+--
631+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
632+-- the weak pointer to it in some cases.
633+
634+--TODO: I think all of these noinlines are now unnecessary
635+{-# NOINLINE newSubscriberPush #-}
636+newSubscriberPush :: (a -> ComputeM (Maybe b)) -> PushSubscribed a b -> IO (Subscriber a)
637+newSubscriberPush compute subd = return $! SubscriberPush compute subd
638+
639+{-# RULES
640+ "newSubscriberHold/Identity" forall h. newSubscriberHold h = newSubscriberHoldIdentity h
641+ #-}
642+{-# NOINLINE newSubscriberHold #-}
643+newSubscriberHold :: R.Patch p => Hold p a -> IO (Subscriber (p a))
644+newSubscriberHold h = return $! SubscriberHold h
645+
646+{-# NOINLINE newSubscriberHoldIdentity #-}
647+newSubscriberHoldIdentity :: Hold Identity a -> IO (Subscriber (Identity a))
648+newSubscriberHoldIdentity h = return $! SubscriberHoldIdentity h
649+
650+{-# NOINLINE newSubscriberMerge #-}
651+newSubscriberMerge :: GCompare k => k a -> MergeSubscribed k -> IO (Subscriber a)
652+newSubscriberMerge k subd = return $! SubscriberMerge k subd
653+
654+{-# NOINLINE newSubscriberMergeChange #-}
655+newSubscriberMergeChange :: GCompare k => MergeSubscribed k -> IO (Subscriber (R.PatchDMap (DMap k Event)))
656+newSubscriberMergeChange subd = return $! SubscriberMergeChange subd
657+
658+{-# NOINLINE newSubscriberFan #-}
659+newSubscriberFan :: GCompare k => FanSubscribed k -> IO (Subscriber (DMap k Identity))
660+newSubscriberFan subd = return $! SubscriberFan subd
661+
662+{-# NOINLINE newSubscriberSwitch #-}
663+newSubscriberSwitch :: SwitchSubscribed a -> IO (Subscriber a)
664+newSubscriberSwitch subd = return $! SubscriberSwitch subd
665+
666+{-# NOINLINE newSubscriberCoincidenceOuter #-}
667+newSubscriberCoincidenceOuter :: CoincidenceSubscribed b -> IO (Subscriber (Event b))
668+newSubscriberCoincidenceOuter subd = return $! SubscriberCoincidenceOuter subd
669+
670+{-# NOINLINE newSubscriberCoincidenceInner #-}
671+newSubscriberCoincidenceInner :: CoincidenceSubscribed a -> IO (Subscriber a)
672+newSubscriberCoincidenceInner subd = return $! SubscriberCoincidenceInner subd
673+
674+{-# NOINLINE newInvalidatorSwitch #-}
675+newInvalidatorSwitch :: SwitchSubscribed a -> IO Invalidator
676+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
677+
678+{-# NOINLINE newInvalidatorPull #-}
679+newInvalidatorPull :: Pull a -> IO Invalidator
680+newInvalidatorPull p = return $! InvalidatorPull p
681+
682+data Dynamic p a
683+ = DynamicHold !(Hold p a)
684+ | p ~ Identity => DynamicHoldIdentity !(Hold Identity a)
685+ | DynamicConst !a
686+ | DynamicDyn !(Dyn p a)
687+ | p ~ Identity => DynamicDynIdentity !(Dyn Identity a)
688+
689+{-# INLINE current #-}
690+current :: R.Patch p => Dynamic p a -> Behavior a
691+current = \case
692+ DynamicHold h -> BehaviorHold h
693+ DynamicHoldIdentity h -> BehaviorHoldIdentity h
694+ DynamicConst a -> BehaviorConst a
695+ DynamicDyn d -> BehaviorDyn d
696+ DynamicDynIdentity d -> BehaviorDynIdentity d
697+
698+--TODO: If you only need updated, not current, can we avoid actually constructing the Hold?
699+{-# INLINE updated #-}
700+updated :: R.Patch p => Dynamic p a -> Event (p a)
701+updated = \case
702+ DynamicHold h -> EventHold h
703+ DynamicHoldIdentity h -> EventHoldIdentity h
704+ DynamicConst _ -> EventNever
705+ DynamicDyn d -> EventDyn d
706+ DynamicDynIdentity d -> EventDynIdentity d
707+
708+newMapDyn :: (a -> b) -> Dynamic Identity a -> Dynamic Identity b
709+newMapDyn f d = DynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ current d) (fmap (Identity . f . runIdentity) $ updated d)
710+
711+instance Functor (Dynamic Identity) where
712+ fmap f d = newMapDyn f d
713+
714+instance Applicative (Dynamic Identity) where
715+ pure = DynamicConst
716+ (<*>) = zipDynWith ($)
717+ _ *> b = b
718+ a <* _ = a
719+
720+instance R.FunctorMaybe Event where
721+ fmapMaybe f = push $ return . f
722+
723+instance Align Event where
724+ nil = EventNever
725+ align ea eb = R.fmapMaybe R.dmapToThese $ merge $ DynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
726+
727+--TODO: Avoid the duplication between this and R.zipDynWith
728+zipDynWith :: (a -> b -> c) -> Dynamic Identity a -> Dynamic Identity b -> Dynamic Identity c
729+zipDynWith f da db =
730+ let eab = align (updated da) (updated db)
731+ ec = flip push eab $ \o -> do
732+ (a, b) <- case o of
733+ This (Identity a) -> do
734+ b <- readBehaviorUntracked $ current db
735+ return (a, b)
736+ That (Identity b) -> do
737+ a <- readBehaviorUntracked $ current da
738+ return (a, b)
739+ These (Identity a) (Identity b) -> return (a, b)
740+ return $ Just $ Identity $ f a b
741+ in DynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (current da) <*> readBehaviorUntracked (current db)) ec
742+
743+instance Monad (Dynamic Identity) where
744+ {-# INLINE return #-}
745+ return = pure
746+ {-# INLINE (>>=) #-}
747+ x >>= f = DynamicDynIdentity $ newJoinDyn $ newMapDyn f x --TODO: (>>), fail
748+ {-# INLINE (>>) #-}
749+ _ >> y = y
750+ {-# INLINE fail #-}
751+ fail _ = error "Dynamic does not support 'fail'"
752+
753+newtype Dyn p a = Dyn { unDyn :: IORef (Either (BehaviorM a, Event (p a)) (Hold p a)) }
754+
755+unsafeDyn :: BehaviorM a -> Event (p a) -> Dyn p a
756+unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
757+ where x = (readV0, v')
758+
759+newJoinDyn :: Dynamic Identity (Dynamic Identity a) -> Dyn Identity a
760+newJoinDyn d =
761+ let readV0 = readBehaviorTracked . current =<< readBehaviorTracked (current d)
762+ eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . current . runIdentity) $ updated d
763+ eInner = switch $ fmap updated $ current d
764+ eBoth = coincidence $ fmap (updated . runIdentity) $ updated d
765+ v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
766+ in unsafeDyn readV0 v'
767+
768+--type role Behavior representational
769+data Behavior a
770+ = forall p. BehaviorHold !(Hold p a)
771+ | BehaviorHoldIdentity !(Hold Identity a)
772+ | BehaviorConst !a
773+ | BehaviorPull !(Pull a)
774+ | BehaviorDynIdentity !(Dyn Identity a)
775+ | forall p. R.Patch p => BehaviorDyn !(Dyn p a)
776+
777+-- ResultM can read behaviors and events
778+type ResultM = EventM
779+
780+{-# NOINLINE unsafeNewIORef #-}
781+unsafeNewIORef :: a -> b -> IORef b
782+unsafeNewIORef _ b = unsafePerformIO $ newIORef b
783+
784+instance Functor Event where
785+ fmap f = push $ return . Just . f
786+
787+instance Functor Behavior where
788+ fmap f = pull . liftM f . readBehaviorTracked
789+
790+{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
791+push :: forall a b. (a -> ComputeM (Maybe b)) -> Event a -> Event b
792+push f e = EventPush $ Push
793+ { pushCompute = f
794+ , pushParent = e
795+ , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
796+ }
797+-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
798+
799+{-# NOINLINE pull #-}
800+pull :: BehaviorM a -> Behavior a
801+pull a = BehaviorPull $ Pull
802+ { pullCompute = a
803+ , pullValue = unsafeNewIORef a Nothing
804+#ifdef DEBUG_NODEIDS
805+ , pullNodeId = unsafeNodeId a
806+#endif
807+ }
808+
809+{-# NOINLINE switch #-}
810+switch :: Behavior (Event a) -> Event a
811+switch a = EventSwitch $ Switch
812+ { switchParent = a
813+ , switchSubscribed = unsafeNewIORef a Nothing
814+ }
815+
816+coincidence :: Event (Event a) -> Event a
817+coincidence a = EventCoincidence $ Coincidence
818+ { coincidenceParent = a
819+ , coincidenceSubscribed = unsafeNewIORef a Nothing
820+ }
821+
822+propagateAndUpdateSubscribersRef :: SubscriberList a -> a -> EventM x ()
823+propagateAndUpdateSubscribersRef subscribersRef a = do
824+ propagate a subscribersRef
825+
826+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
827+run :: [DSum RootTrigger Identity] -> ResultM x b -> SpiderHost x b
828+run roots after = do
829+ tracePropagate $ "Running an event frame with " <> show (length roots) <> " events"
830+ spiderEnv <- SpiderHost ask
831+ result <- SpiderHost $ lift $ withMVar (_spiderEnv_lock spiderEnv) $ \_ -> flip runReaderT spiderEnv $ unSpiderHost $ runFrame $ do
832+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
833+ occBefore <- liftIO $ do
834+ occBefore <- readIORef occRef
835+ writeIORef occRef $! DMap.insert k a occBefore
836+ return occBefore
837+ if DMap.null occBefore
838+ then do scheduleRootClear occRef
839+ return $ Just r
840+ else return Nothing
841+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
842+ propagateAndUpdateSubscribersRef subscribersRef a
843+ delayedRef <- EventM $ asks eventEnvDelayedMerges
844+ let go = do
845+ delayed <- liftIO $ readIORef delayedRef
846+ case IntMap.minViewWithKey delayed of
847+ Nothing -> return ()
848+ Just ((currentHeight, cur), future) -> do
849+ tracePropagate $ "Running height " ++ show currentHeight
850+ putCurrentHeight $ Height currentHeight
851+ liftIO $ writeIORef delayedRef $! future
852+ forM_ cur $ \d -> case d of
853+ DelayedMerge subscribed -> do
854+ height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
855+ case height `compare` Height currentHeight of
856+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
857+ GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
858+ EQ -> do
859+ m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
860+ liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! DMap.empty
861+ --TODO: Assert that m is not empty
862+ liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $! Just m
863+ scheduleClear $ mergeSubscribedOccurrence subscribed
864+ propagateAndUpdateSubscribersRef (mergeSubscribedSubscribers subscribed) m
865+ go
866+ go
867+ putCurrentHeight maxBound
868+ after
869+ tracePropagate "Done running an event frame"
870+ return result
871+
872+data SomeClear = forall a. SomeClear (IORef (Maybe a))
873+
874+data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
875+
876+data SomeAssignment = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak Invalidator]) a
877+
878+data DelayedMerge = forall k. DelayedMerge (MergeSubscribed k)
879+
880+debugFinalize :: Bool
881+debugFinalize = False
882+
883+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
884+mkWeakPtrWithDebug x debugNote = do
885+ x' <- evaluate x
886+ mkWeakPtr x' $
887+ if debugFinalize
888+ then Just $ putStrLn $ "finalizing: " ++ debugNote
889+ else Nothing
890+
891+type WeakList a = [Weak a]
892+
893+{-# INLINE withIncreasedDepth #-}
894+#ifdef DEBUG
895+withIncreasedDepth :: CanTrace x m => m a -> m a
896+withIncreasedDepth a = do
897+ spiderEnv <- askSpiderEnv
898+ liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) succ
899+ result <- a
900+ liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) pred
901+ return result
902+#else
903+withIncreasedDepth :: m a -> m a
904+withIncreasedDepth = id
905+#endif
906+
907+type CanTrace x m = (HasSpiderEnv x m, MonadIO m)
908+
909+{-# INLINE tracePropagate #-}
910+tracePropagate :: (CanTrace x m) => String -> m ()
911+tracePropagate = traceWhen debugPropagate
912+
913+{-# INLINE traceSubscribe #-}
914+traceSubscribe :: String -> IO ()
915+traceSubscribe = when debugSubscribe . liftIO . putStrLn
916+
917+{-# INLINE traceInvalidate #-}
918+traceInvalidate :: String -> IO ()
919+traceInvalidate = when debugInvalidate . liftIO . putStrLn
920+
921+{-# INLINE traceWhen #-}
922+traceWhen :: (CanTrace x m) => Bool -> String -> m ()
923+traceWhen b message = traceMWhen b $ return message
924+
925+{-# INLINE traceMWhen #-}
926+traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
927+traceMWhen b getMessage = when b $ do
928+ message <- getMessage
929+#ifdef DEBUG
930+ spiderEnv <- askSpiderEnv
931+ d <- liftIO $ readIORef $ _spiderEnv_depth spiderEnv
932+#else
933+ let d = 0
934+#endif
935+ liftIO $ putStrLn $ replicate d ' ' <> message
936+
937+whoCreatedIORef :: IORef a -> IO [String]
938+whoCreatedIORef (IORef a) = whoCreated $! a
939+
940+whoCreatedEventSubscribed :: EventSubscribed a -> IO [String]
941+whoCreatedEventSubscribed = \case
942+ EventSubscribedRoot _ -> return ["root"]
943+ EventSubscribedNever -> return ["never"]
944+ EventSubscribedPush subscribed -> whoCreatedIORef $ pushSubscribedCachedSubscribed subscribed
945+ EventSubscribedFan _ subscribed -> whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
946+ EventSubscribedMerge subscribed -> whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
947+ EventSubscribedSwitch subscribed -> whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
948+ EventSubscribedCoincidence subscribed -> whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
949+
950+walkInvalidHeightParents :: EventSubscribed a -> IO [Some EventSubscribed]
951+walkInvalidHeightParents s0 = do
952+ subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
953+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
954+ when (h == invalidHeight) $ do
955+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
956+ modify (Some.This s :)
957+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
958+ forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
959+ return subscribers
960+
961+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
962+groupByHead = \case
963+ [] -> []
964+ (x :| xs) : t -> case groupByHead t of
965+ [] -> [(x, xs :| [])]
966+ l@((y, yss) : t')
967+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
968+ | otherwise -> (x, xs :| []) : l
969+
970+listsToForest :: Eq a => [[a]] -> Forest a
971+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
972+
973+-- | Propagate everything at the current height
974+propagate :: a -> SubscriberList a -> EventM x ()
975+propagate a subscribers = withIncreasedDepth $ do
976+ -- Note: in the following traversal, we do not visit nodes that are added to the list during our traversal; they are new events, which will necessarily have full information already, so there is no need to traverse them
977+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
978+ WeakBag.traverse subscribers $ \s -> case s of
979+ SubscriberPush compute subscribed -> {-# SCC "traversePush" #-} do
980+ tracePropagate $ "SubscriberPush" <> showNodeId subscribed
981+ occ <- runComputeM $ compute a
982+ case occ of
983+ Nothing -> return () -- No need to write a Nothing back into the Ref
984+ Just o -> do
985+ liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
986+ scheduleClear $ pushSubscribedOccurrence subscribed
987+ propagate o $ pushSubscribedSubscribers subscribed
988+ SubscriberMerge k subscribed -> {-# SCC "traverseMerge" #-} do
989+ tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
990+ oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
991+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge" <> showNodeId subscribed) k (Identity a) oldM
992+ tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
993+ liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! newM
994+ when (DMap.null oldM) $ do -- Only schedule the firing once
995+ height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
996+ --TODO: assertions about height
997+ currentHeight <- getCurrentHeight
998+ when (height <= currentHeight) $ do
999+ myStack <- liftIO $ whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
1000+ if height /= invalidHeight
1001+ then error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1002+ else liftIO $ do
1003+ nodesInvolvedInCycle <- walkInvalidHeightParents $ EventSubscribedMerge subscribed
1004+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1005+ error $ "Causality loop found:\n" <> drawForest (listsToForest stacks)
1006+ scheduleMerge height subscribed
1007+ SubscriberMergeChange subscribed -> {-# SCC "traverseMergeChange" #-} do
1008+ tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
1009+ defer $ SomeMergeUpdate a subscribed
1010+ SubscriberFan subscribed -> {-# SCC "traverseFan" #-} do
1011+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
1012+ tracePropagate $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
1013+ --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large
1014+ forM_ (DMap.toList a) $ \(k :=> Identity v) -> {-# SCC "SubscriberFan" #-} case DMap.lookup k subs of
1015+ Nothing -> do
1016+ tracePropagate "No subscriber for key"
1017+ return ()
1018+ Just subsubs -> do
1019+ propagate v $ _fanSubscribedChildren_list subsubs
1020+ return ()
1021+ SubscriberHold h -> {-# SCC "traverseHold" #-} propagateSubscriberHold h a
1022+ SubscriberHoldIdentity h -> {-# SCC "traverseHoldIdentity" #-} propagateSubscriberHold h a
1023+ SubscriberSwitch subscribed -> {-# SCC "traverseSwitch" #-} do
1024+ tracePropagate $ "SubscriberSwitch" <> showNodeId subscribed
1025+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $! Just a
1026+ scheduleClear $ switchSubscribedOccurrence subscribed
1027+ propagate a $ switchSubscribedSubscribers subscribed
1028+ SubscriberCoincidenceOuter subscribed -> {-# SCC "traverseCoincidenceOuter" #-} do
1029+ tracePropagate $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
1030+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
1031+ tracePropagate $ " outerHeight = " <> show outerHeight
1032+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
1033+ tracePropagate $ " isJust occ = " <> show (isJust occ)
1034+ tracePropagate $ " innerHeight = " <> show innerHeight
1035+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $! Just innerSubd
1036+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
1037+ case occ of
1038+ Nothing -> do
1039+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
1040+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
1041+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
1042+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
1043+ Just o -> do -- Since it's already firing, no need to adjust height
1044+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
1045+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
1046+ propagate o $ coincidenceSubscribedSubscribers subscribed
1047+ SubscriberCoincidenceInner subscribed -> {-# SCC "traverseCoincidenceInner" #-} do
1048+ tracePropagate $ "SubscriberCoincidenceInner" <> showNodeId subscribed
1049+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
1050+ case occ of
1051+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
1052+ Nothing -> do
1053+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $! Just a
1054+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
1055+ propagate a $ coincidenceSubscribedSubscribers subscribed
1056+ SubscriberHandle -> {-# SCC "traverseHandle" #-} tracePropagate "SubscriberHandle"
1057+
1058+{-# INLINE propagateSubscriberHold #-}
1059+propagateSubscriberHold :: R.Patch p => Hold p a -> p a -> EventM x ()
1060+propagateSubscriberHold h a = do
1061+ {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1062+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1063+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1064+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1065+ case {-# SCC "apply" #-} R.apply a v of
1066+ Nothing -> return ()
1067+ Just v' -> do
1068+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1069+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1070+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1071+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1072+
1073+data SomeResetCoincidence = forall a. SomeResetCoincidence !(EventSubscription a) !(Maybe (CoincidenceSubscribed a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1074+
1075+{-# INLINE subscribeCoincidenceInner #-}
1076+subscribeCoincidenceInner :: CanSubscribe x m => Event a -> Height -> CoincidenceSubscribed a -> m (Maybe a, Height, EventSubscribed a)
1077+subscribeCoincidenceInner o outerHeight subscribedUnsafe = do
1078+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
1079+ subscription@(EventSubscription _ innerSubd) <- subscribe o subInner
1080+ innerOcc <- liftIO $ readEventSubscribed innerSubd
1081+ innerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef innerSubd
1082+ let height = max innerHeight outerHeight
1083+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
1084+ return (innerOcc, height, innerSubd)
1085+
1086+{-# SPECIALIZE readBehaviorUntracked :: Behavior a -> BehaviorM a #-}
1087+{-# SPECIALIZE readBehaviorUntracked :: Behavior a -> EventM x a #-}
1088+readBehaviorUntracked :: Defer SomeHoldInit m => Behavior a -> m a
1089+readBehaviorUntracked b = do
1090+ holdInits <- getDeferralQueue
1091+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
1092+
1093+runBehaviorM :: BehaviorM a -> Maybe (Weak Invalidator, IORef [SomeBehaviorSubscribed]) -> IORef [SomeHoldInit] -> IO a
1094+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1095+
1096+askInvalidator :: BehaviorM (Maybe (Weak Invalidator))
1097+askInvalidator = liftM (fmap fst . fst) $ BehaviorM ask
1098+
1099+askParentsRef :: BehaviorM (Maybe (IORef [SomeBehaviorSubscribed]))
1100+askParentsRef = liftM (fmap snd . fst) $ BehaviorM ask
1101+
1102+askBehaviorHoldInits :: BehaviorM (IORef [SomeHoldInit])
1103+askBehaviorHoldInits = liftM snd $ BehaviorM ask
1104+
1105+readBehaviorTracked :: Behavior a -> BehaviorM a
1106+readBehaviorTracked b = case b of
1107+ BehaviorHold h -> readHoldTracked h
1108+ BehaviorHoldIdentity h -> readHoldTracked h
1109+ BehaviorConst a -> return a
1110+ BehaviorPull p -> do
1111+ val <- liftIO $ readIORef $ pullValue p
1112+ case val of
1113+ Just subscribed -> do
1114+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1115+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
1116+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
1117+ return $ pullSubscribedValue subscribed
1118+ Nothing -> do
1119+ i <- liftIO $ newInvalidatorPull p
1120+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
1121+ parentsRef <- liftIO $ newIORef []
1122+ holdInits <- askBehaviorHoldInits
1123+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
1124+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
1125+ parents <- liftIO $ readIORef parentsRef
1126+ let subscribed = PullSubscribed
1127+ { pullSubscribedValue = a
1128+ , pullSubscribedInvalidators = invsRef
1129+ , pullSubscribedOwnInvalidator = i
1130+ , pullSubscribedParents = parents
1131+ }
1132+ liftIO $ writeIORef (pullValue p) $! Just subscribed
1133+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1134+ return a
1135+ BehaviorDyn d -> readHoldTracked =<< getDynHold d
1136+ BehaviorDynIdentity d -> readHoldTracked =<< getDynHold d
1137+
1138+{-# INLINE readHoldTracked #-}
1139+readHoldTracked :: Hold p a -> BehaviorM a
1140+readHoldTracked h = do
1141+ result <- liftIO $ readIORef $ holdValue h
1142+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
1143+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
1144+ return result
1145+
1146+{-# INLINE getDynHold #-}
1147+getDynHold :: (Defer SomeHoldInit m, R.Patch p) => Dyn p a -> m (Hold p a)
1148+getDynHold d = do
1149+ mh <- liftIO $ readIORef $ unDyn d
1150+ case mh of
1151+ Right h -> return h
1152+ Left (readV0, v') -> do
1153+ holdInits <- getDeferralQueue
1154+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1155+ h <- hold v0 v'
1156+ liftIO $ writeIORef (unDyn d) $! Right h
1157+ return h
1158+
1159+{-
1160+readEvent :: Event a -> ResultM (Maybe a)
1161+readEvent e = case e of
1162+ EventRoot k r -> liftIO . liftM (coerce . DMap.lookup k) . readIORef $ rootOccurrence r
1163+ EventNever -> return Nothing
1164+ EventPush p -> do
1165+ subscribed <- getPushSubscribed p
1166+ liftIO $ readPushSubscribed subscribed
1167+ EventMerge m -> do
1168+ subscribed <- getMergeSubscribed m
1169+ liftIO $ readMergeSubscribed subscribed
1170+ EventFan k f -> do
1171+ subscribed <- getFanSubscribed f
1172+ liftIO $ readFanSubscribed k subscribed
1173+ EventSwitch s -> do
1174+ subscribed <- getSwitchSubscribed s
1175+ liftIO $ readSwitchSubscribed subscribed
1176+ EventCoincidence c -> do
1177+ subscribed <- getCoincidenceSubscribed c
1178+ liftIO $ readCoincidenceSubscribed subscribed
1179+ EventHold h -> liftIO . readEventSubscribed =<< getHoldEventSubscription h
1180+ EventDyn d -> liftIO . readEventSubscribed =<< getHoldEventSubscription =<< getDynHold d
1181+ EventHoldIdentity h -> liftIO . readEventSubscribed =<< getHoldEventSubscription h
1182+ EventDynIdentity d -> liftIO . readEventSubscribed =<< getHoldEventSubscription =<< getDynHold d
1183+-}
1184+
1185+readEventSubscribed :: EventSubscribed a -> IO (Maybe a)
1186+readEventSubscribed = \case
1187+ EventSubscribedRoot rs -> readRootSubscribed rs
1188+ EventSubscribedNever -> return Nothing
1189+ EventSubscribedPush ps -> readPushSubscribed ps
1190+ EventSubscribedMerge ms -> readMergeSubscribed ms
1191+ EventSubscribedFan k fs -> readFanSubscribed k fs
1192+ EventSubscribedSwitch ss -> readSwitchSubscribed ss
1193+ EventSubscribedCoincidence cs -> readCoincidenceSubscribed cs
1194+
1195+readRootSubscribed :: RootSubscribed a -> IO (Maybe a)
1196+readRootSubscribed = rootSubscribedOccurrence
1197+
1198+readPushSubscribed :: PushSubscribed b a -> IO (Maybe a)
1199+readPushSubscribed subscribed = do
1200+ result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
1201+ touch $ pushSubscribedSelf subscribed
1202+ return result
1203+
1204+readMergeSubscribed :: MergeSubscribed k -> IO (Maybe (DMap k Identity))
1205+readMergeSubscribed subscribed = do
1206+ result <- readIORef $ mergeSubscribedOccurrence subscribed
1207+ touch $ mergeSubscribedParents subscribed
1208+ return result
1209+
1210+readFanSubscribed :: GCompare k => k a -> FanSubscribed k -> IO (Maybe a)
1211+readFanSubscribed k fs = do
1212+ parentOcc <- readEventSubscribed $ _eventSubscription_subscribed $ fanSubscribedParent fs
1213+ return $ coerce $ DMap.lookup k =<< parentOcc
1214+
1215+readSwitchSubscribed :: SwitchSubscribed a -> IO (Maybe a)
1216+readSwitchSubscribed subscribed = do
1217+ result <- readIORef $ switchSubscribedOccurrence subscribed
1218+ touch $ switchSubscribedOwnInvalidator subscribed
1219+ return result
1220+
1221+readCoincidenceSubscribed :: CoincidenceSubscribed a -> IO (Maybe a)
1222+readCoincidenceSubscribed subscribed = do
1223+ result <- readIORef $ coincidenceSubscribedOccurrence subscribed
1224+ touch $ coincidenceSubscribedOuter subscribed
1225+ --TODO: do we need to touch the inner subscriber?
1226+ return result
1227+
1228+-- Always refers to 0
1229+{-# NOINLINE zeroRef #-}
1230+zeroRef :: IORef Height
1231+zeroRef = unsafePerformIO $ newIORef zeroHeight
1232+
1233+{-# SPECIALIZE subscribe :: Event a -> Subscriber a -> EventM x (EventSubscription a) #-}
1234+subscribe :: forall x m a. CanSubscribe x m => Event a -> Subscriber a -> m (EventSubscription a)
1235+subscribe e sub = case e of
1236+ EventRoot k r -> wrap EventSubscribedRoot $ liftIO . getRootSubscribed k r
1237+ EventNever -> return $ EventSubscription Nothing EventSubscribedNever
1238+ EventPush p -> wrap EventSubscribedPush $ getPushSubscribed p
1239+ EventFan k f -> wrap (EventSubscribedFan k) $ getFanSubscribed k f
1240+ EventMerge m -> wrap EventSubscribedMerge $ getMergeSubscribed m
1241+ EventSwitch s -> wrap EventSubscribedSwitch $ getSwitchSubscribed s
1242+ EventCoincidence c -> wrap EventSubscribedCoincidence $ getCoincidenceSubscribed c
1243+ EventHold h -> subscribeHoldEvent h sub
1244+ EventDyn j -> getDynHold j >>= \h -> subscribeHoldEvent h sub
1245+ EventHoldIdentity h -> subscribeHoldEvent h sub
1246+ EventDynIdentity j -> getDynHold j >>= \h -> subscribeHoldEvent h sub
1247+ where
1248+ wrap :: (t -> EventSubscribed a) -> (Subscriber a -> m (SubscriberListTicket a, t)) -> m (EventSubscription a)
1249+ wrap tag getSpecificSubscribed = do
1250+ (sln, subd) <- getSpecificSubscribed sub
1251+ return $ EventSubscription (Just sln) $ tag subd
1252+
1253+{-# INLINE subscribeHoldEvent #-}
1254+subscribeHoldEvent :: (CanSubscribe x m, R.Patch p) => Hold p a -> Subscriber (p a) -> m (EventSubscription (p a))
1255+subscribeHoldEvent h sub = do
1256+ EventSubscription _ subd <- getHoldEventSubscription h
1257+ sln <- liftIO $ subscribeEventSubscribed subd sub
1258+ return $ EventSubscription sln subd
1259+
1260+{-# INLINE debugSubscribe #-}
1261+debugSubscribe :: Bool
1262+debugSubscribe = False
1263+
1264+{-# INLINE subscribeEventSubscribed #-}
1265+subscribeEventSubscribed :: EventSubscribed a -> Subscriber a -> IO (Maybe (SubscriberListTicket a))
1266+subscribeEventSubscribed es sub = case es of
1267+ EventSubscribedRoot r -> do
1268+ traceSubscribe $ "subscribeEventSubscribed Root"
1269+ fmap Just $ subscribeRootSubscribed r sub
1270+ EventSubscribedNever -> do
1271+ traceSubscribe $ "subscribeEventSubscribed Never"
1272+ return Nothing
1273+ EventSubscribedPush subscribed -> do
1274+ traceSubscribe $ "subscribeEventSubscribed Push"
1275+ fmap Just $ subscribePushSubscribed subscribed sub
1276+ EventSubscribedFan k subscribed -> do
1277+ traceSubscribe $ "subscribeEventSubscribed Fan"
1278+ fmap Just $ subscribeFanSubscribed k subscribed sub
1279+ EventSubscribedMerge subscribed -> do
1280+ traceSubscribe $ "subscribeEventSubscribed Merge"
1281+ fmap Just $ subscribeMergeSubscribed subscribed sub
1282+ EventSubscribedSwitch subscribed -> do
1283+ traceSubscribe $ "subscribeEventSubscribed Switch"
1284+ fmap Just $ subscribeSwitchSubscribed subscribed sub
1285+ EventSubscribedCoincidence subscribed -> do
1286+ traceSubscribe $ "subscribeEventSubscribed Coincidence"
1287+ fmap Just $ subscribeCoincidenceSubscribed subscribed sub
1288+
1289+{-# INLINE eventSubscribedHeightRef #-}
1290+eventSubscribedHeightRef :: EventSubscribed a -> IORef Height
1291+eventSubscribedHeightRef = \case
1292+ EventSubscribedRoot _ -> zeroRef
1293+ EventSubscribedNever -> zeroRef
1294+ EventSubscribedPush subscribed -> pushSubscribedHeight subscribed
1295+ EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
1296+ EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed
1297+ EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed
1298+ EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed
1299+
1300+{-# INLINE eventSubscribedHasOwnHeightRef #-}
1301+eventSubscribedHasOwnHeightRef :: EventSubscribed a -> Bool
1302+eventSubscribedHasOwnHeightRef = \case
1303+ EventSubscribedRoot _ -> False
1304+ EventSubscribedNever -> False
1305+ EventSubscribedPush _ -> False
1306+ EventSubscribedFan _ _ -> False
1307+ EventSubscribedMerge _ -> True
1308+ EventSubscribedSwitch _ -> True
1309+ EventSubscribedCoincidence _ -> True
1310+
1311+{-# INLINE eventSubscribedGetParents #-}
1312+eventSubscribedGetParents :: EventSubscribed a -> IO [Some EventSubscribed]
1313+eventSubscribedGetParents = \case
1314+ EventSubscribedRoot _ -> return []
1315+ EventSubscribedNever -> return []
1316+ EventSubscribedPush subscribed -> return [Some.This $ _eventSubscription_subscribed $ pushSubscribedParent subscribed]
1317+ EventSubscribedFan _ subscribed -> return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
1318+ EventSubscribedMerge subscribed -> do
1319+ ps <- readIORef $ mergeSubscribedParents subscribed
1320+ return $ fmap (\(_ :=> v) -> Some.This $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription v) $ DMap.toList ps
1321+ EventSubscribedSwitch subscribed -> do
1322+ s <- readIORef $ switchSubscribedCurrentParent subscribed
1323+ return [Some.This $ _eventSubscription_subscribed s]
1324+ EventSubscribedCoincidence subscribed -> do
1325+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
1326+ let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1327+ innerParents = maybeToList $ fmap Some.This innerSubscription
1328+ return $ outerParent : innerParents
1329+
1330+type CanSubscribe x m =
1331+ ( HasSpiderEnv x m
1332+ , HasCurrentHeight m
1333+ , Defer SomeHoldInit m, Defer SomeMergeInit m -- The things we need to lazily initialize state
1334+ , Defer SomeClear m -- Wiping out event firings
1335+ , Defer SomeAssignment m -- Updating state
1336+ , Defer SomeResetCoincidence m
1337+ )
1338+
1339+getRootSubscribed :: GCompare k => k a -> Root k -> Subscriber a -> IO (SubscriberListTicket a, RootSubscribed a)
1340+getRootSubscribed k r sub = do
1341+ mSubscribed <- readIORef $ rootSubscribed r
1342+ case DMap.lookup k mSubscribed of
1343+ Just subscribed -> {-# SCC "hitRoot" #-} do
1344+ sln <- subscribeRootSubscribed subscribed sub
1345+ return (sln, subscribed)
1346+ Nothing -> {-# SCC "missRoot" #-} do
1347+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1348+ let !cached = rootSubscribed r
1349+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1350+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1351+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1352+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1353+ writeIORef uninitRef $! uninit
1354+ let subscribed = RootSubscribed
1355+ { rootSubscribedKey = k
1356+ , rootSubscribedCachedSubscribed = cached
1357+ , rootSubscribedOccurrence = liftM (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1358+ , rootSubscribedSubscribers = subs
1359+ , rootSubscribedUninit = uninit
1360+ , rootSubscribedWeakSelf = weakSelf
1361+#ifdef DEBUG_NODEIDS
1362+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1363+#endif
1364+ }
1365+ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1366+ modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it
1367+ return (sln, subscribed)
1368+
1369+cleanupRootSubscribed :: RootSubscribed a -> IO ()
1370+cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1371+ rootSubscribedUninit self
1372+ modifyIORef' cached $ DMap.delete k
1373+
1374+{-# INLINE subscribeRootSubscribed #-}
1375+subscribeRootSubscribed :: RootSubscribed a -> Subscriber a -> IO (SubscriberListTicket a)
1376+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1377+
1378+-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
1379+{-# SPECIALIZE getPushSubscribed :: Push a b -> Subscriber b -> EventM x (SubscriberListTicket b, PushSubscribed a b) #-}
1380+getPushSubscribed :: CanSubscribe x m => Push a b -> Subscriber b -> m (SubscriberListTicket b, PushSubscribed a b)
1381+getPushSubscribed p sub = do
1382+ mSubscribed <- liftIO $ readIORef $ pushSubscribed p
1383+ case mSubscribed of
1384+ Just subscribed -> {-# SCC "hitPush" #-} do
1385+ sln <- liftIO $ subscribePushSubscribed subscribed sub
1386+ return (sln, subscribed)
1387+ Nothing -> {-# SCC "missPush" #-} do -- Not yet subscribed
1388+ subscribedRef <- liftIO $ newIORef $ error "getPushSubscribed: subscribed not yet intialized"
1389+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1390+ s <- liftIO $ newSubscriberPush (pushCompute p) subscribedUnsafe
1391+ subscription@(EventSubscription _ subd) <- subscribe (pushParent p) s
1392+ parentOcc <- liftIO $ readEventSubscribed subd
1393+ occ <- runComputeM $ liftM join $ mapM (pushCompute p) parentOcc
1394+ occRef <- liftIO $ newIORef occ
1395+ when (isJust occ) $ scheduleClear occRef
1396+ weakSelf <- liftIO $ newIORef $ error "getPushSubscribed: weakSelf not initialized"
1397+ let !cached = pushSubscribed p
1398+ (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupPushSubscribed
1399+ let subscribed = PushSubscribed
1400+ { pushSubscribedCachedSubscribed = cached
1401+ , pushSubscribedOccurrence = occRef
1402+ , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
1403+ , pushSubscribedSubscribers = subs
1404+ , pushSubscribedSelf = s
1405+ , pushSubscribedWeakSelf = weakSelf
1406+ , pushSubscribedParent = subscription
1407+#ifdef DEBUG_NODEIDS
1408+ , pushSubscribedNodeId = unsafeNodeId p
1409+#endif
1410+ }
1411+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
1412+ liftIO $ writeIORef subscribedRef $! subscribed
1413+ liftIO $ writeIORef (pushSubscribed p) $! Just subscribed
1414+ return (sln, subscribed)
1415+
1416+cleanupPushSubscribed :: PushSubscribed a b -> IO ()
1417+cleanupPushSubscribed self = do
1418+ unsubscribe $ pushSubscribedParent self
1419+ writeIORef (pushSubscribedCachedSubscribed self) $! Nothing
1420+
1421+{-# INLINE subscribePushSubscribed #-}
1422+subscribePushSubscribed :: PushSubscribed a b -> Subscriber b -> IO (SubscriberListTicket b)
1423+subscribePushSubscribed subscribed sub = WeakBag.insert sub (pushSubscribedSubscribers subscribed) (pushSubscribedWeakSelf subscribed) cleanupPushSubscribed
1424+
1425+{-# SPECIALIZE getMergeSubscribed :: GCompare k => Merge k -> Subscriber (DMap k Identity) -> EventM x (SubscriberListTicket (DMap k Identity), MergeSubscribed k) #-}
1426+getMergeSubscribed :: forall x k m. (CanSubscribe x m, GCompare k) => Merge k -> Subscriber (DMap k Identity) -> m (SubscriberListTicket (DMap k Identity), MergeSubscribed k)
1427+getMergeSubscribed m sub = do
1428+ mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
1429+ case mSubscribed of
1430+ Just subscribed -> {-# SCC "hitMerge" #-} do
1431+ sln <- liftIO $ subscribeMergeSubscribed subscribed sub
1432+ return (sln, subscribed)
1433+ Nothing -> {-# SCC "missMerge" #-} do
1434+ subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
1435+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1436+ initialParents <- readBehaviorUntracked $ current $ mergeParents m
1437+ subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent k))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1438+ s <- liftIO $ newSubscriberMerge k subscribedUnsafe
1439+ subscription@(EventSubscription _ parentSubd) <- subscribe e s
1440+ parentOcc <- liftIO $ readEventSubscribed parentSubd
1441+ height <- liftIO $ readIORef $ eventSubscribedHeightRef parentSubd
1442+ return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> (MergeSubscribedParent subscription s))
1443+ let dm = DMap.fromDistinctAscList $ catMaybes $ map (\(x, _, _) -> x) subscribers
1444+ heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1445+ myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1446+ myHeight = if any (== invalidHeight) heights
1447+ then invalidHeight
1448+ else succHeight $ heightBagMax myHeightBag
1449+ currentHeight <- getCurrentHeight
1450+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1451+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1452+ else (Nothing, dm)
1453+ when (not $ DMap.null accum) $ do
1454+ scheduleMerge myHeight subscribedUnsafe
1455+ occRef <- liftIO $ newIORef occ
1456+ when (isJust occ) $ scheduleClear occRef
1457+ accumRef <- liftIO $ newIORef accum
1458+ heightRef <- liftIO $ newIORef myHeight
1459+ heightMapRef <- liftIO $ newIORef myHeightBag
1460+ weakSelf <- liftIO $ newIORef $ error "getMergeSubscribed: weakSelf not yet initialized"
1461+ (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupMergeSubscribed
1462+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1463+ parentsRef <- liftIO $ newIORef $ DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1464+ let !subscribed = MergeSubscribed
1465+ { mergeSubscribedCachedSubscribed = mergeSubscribed m
1466+ , mergeSubscribedOccurrence = occRef
1467+ , mergeSubscribedAccum = accumRef
1468+ , mergeSubscribedHeight = heightRef
1469+ , mergeSubscribedHeightBag = heightMapRef
1470+ , mergeSubscribedSubscribers = subs
1471+ , mergeSubscribedChange = changeSubdRef
1472+ , mergeSubscribedParents = parentsRef
1473+ , mergeSubscribedWeakSelf = weakSelf
1474+#ifdef DEBUG_NODEIDS
1475+ , mergeSubscribedNodeId = unsafeNodeId m
1476+#endif
1477+ }
1478+ defer $ SomeMergeInit subscribed $ updated $ mergeParents m
1479+ liftIO $ writeIORef subscribedRef $! subscribed
1480+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "MergeSubscribed"
1481+ liftIO $ writeIORef (mergeSubscribed m) $! Just subscribed
1482+ return (sln, subscribed)
1483+
1484+cleanupMergeSubscribed :: MergeSubscribed k -> IO ()
1485+cleanupMergeSubscribed subscribed = do
1486+ parents <- readIORef $ mergeSubscribedParents subscribed
1487+ forM_ (DMap.toList parents) $ \(_ :=> msp) -> unsubscribe $ mergeSubscribedParentSubscription msp
1488+ -- Not necessary, because this whole MergeSubscribed is dead: writeIORef (mergeSubscribedParents subscribed) DMap.empty
1489+ writeIORef (mergeSubscribedCachedSubscribed subscribed) $! Nothing -- Get rid of the cached subscribed
1490+
1491+{-# INLINE subscribeMergeSubscribed #-}
1492+subscribeMergeSubscribed :: MergeSubscribed k -> Subscriber (DMap k Identity) -> IO (SubscriberListTicket (DMap k Identity))
1493+subscribeMergeSubscribed subscribed sub = WeakBag.insert sub (mergeSubscribedSubscribers subscribed) (mergeSubscribedWeakSelf subscribed) cleanupMergeSubscribed
1494+
1495+{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan k -> Subscriber a -> EventM x (SubscriberListTicket a, FanSubscribed k) #-}
1496+getFanSubscribed :: (Defer SomeAssignment m, Defer SomeHoldInit m, Defer SomeMergeInit m, Defer SomeClear m, HasCurrentHeight m, Defer SomeResetCoincidence m, HasSpiderEnv x m, GCompare k) => k a -> Fan k -> Subscriber a -> m (SubscriberListTicket a, FanSubscribed k)
1497+getFanSubscribed k f sub = do
1498+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1499+ case mSubscribed of
1500+ Just subscribed -> {-# SCC "hitFan" #-} do
1501+ sln <- liftIO $ subscribeFanSubscribed k subscribed sub
1502+ return (sln, subscribed)
1503+ Nothing -> {-# SCC "missFan" #-} do
1504+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1505+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1506+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1507+ subscription <- subscribe (fanParent f) s
1508+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1509+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1510+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1511+ let subscribed = FanSubscribed
1512+ { fanSubscribedCachedSubscribed = fanSubscribed f
1513+ , fanSubscribedParent = subscription
1514+ , fanSubscribedSubscribers = subscribersRef
1515+#ifdef DEBUG_NODEIDS
1516+ , fanSubscribedNodeId = unsafeNodeId f
1517+#endif
1518+ }
1519+ let !self = (k, subscribed)
1520+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1521+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1522+ liftIO $ writeIORef subscribedRef $! subscribed
1523+ liftIO $ writeIORef (fanSubscribed f) $! Just subscribed
1524+ return (slnForSub, subscribed)
1525+
1526+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed k) -> IO ()
1527+cleanupFanSubscribed (k, subscribed) = do
1528+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1529+ let reducedSubscribers = DMap.delete k subscribers
1530+ if DMap.null reducedSubscribers
1531+ then do
1532+ unsubscribe $ fanSubscribedParent subscribed
1533+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1534+ writeIORef (fanSubscribedCachedSubscribed subscribed) $! Nothing
1535+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1536+
1537+{-# INLINE subscribeFanSubscribed #-}
1538+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed k -> Subscriber a -> IO (SubscriberListTicket a)
1539+subscribeFanSubscribed k subscribed sub = do
1540+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1541+ case DMap.lookup k subscribers of
1542+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1543+ let !self = (k, subscribed)
1544+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1545+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1546+ writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeEventSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1547+ return sln
1548+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1549+
1550+{-# SPECIALIZE getSwitchSubscribed :: Switch a -> Subscriber a -> EventM x (SubscriberListTicket a, SwitchSubscribed a) #-}
1551+getSwitchSubscribed :: (Defer SomeHoldInit m, Defer SomeAssignment m, Defer SomeMergeInit m, Defer SomeClear m, Defer SomeResetCoincidence m, HasCurrentHeight m, HasSpiderEnv x m) => Switch a -> Subscriber a -> m (SubscriberListTicket a, SwitchSubscribed a)
1552+getSwitchSubscribed s sub = do
1553+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1554+ case mSubscribed of
1555+ Just subscribed -> {-# SCC "hitSwitch" #-} do
1556+ sln <- liftIO $ subscribeSwitchSubscribed subscribed sub
1557+ return (sln, subscribed)
1558+ Nothing -> {-# SCC "missSwitch" #-} do
1559+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1560+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1561+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1562+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1563+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1564+ wiRef <- liftIO $ newIORef wi
1565+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1566+ holdInits <- getDeferralQueue
1567+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1568+ subscription@(EventSubscription _ subd) <- subscribe e mySub
1569+ subscriptionRef <- liftIO $ newIORef subscription
1570+ parentOcc <- liftIO $ readEventSubscribed subd
1571+ occRef <- liftIO $ newIORef parentOcc
1572+ when (isJust parentOcc) $ scheduleClear occRef
1573+ heightRef <- liftIO $ newIORef =<< readIORef (eventSubscribedHeightRef subd)
1574+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1575+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1576+ let !subscribed = SwitchSubscribed
1577+ { switchSubscribedCachedSubscribed = switchSubscribed s
1578+ , switchSubscribedOccurrence = occRef
1579+ , switchSubscribedHeight = heightRef
1580+ , switchSubscribedSubscribers = subs
1581+ , switchSubscribedOwnInvalidator = i
1582+ , switchSubscribedOwnWeakInvalidator = wiRef
1583+ , switchSubscribedBehaviorParents = parentsRef
1584+ , switchSubscribedParent = switchParent s
1585+ , switchSubscribedCurrentParent = subscriptionRef
1586+ , switchSubscribedWeakSelf = weakSelf
1587+#ifdef DEBUG_NODEIDS
1588+ , switchSubscribedNodeId = unsafeNodeId s
1589+#endif
1590+ }
1591+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1592+ liftIO $ writeIORef subscribedRef $! subscribed
1593+ liftIO $ writeIORef (switchSubscribed s) $! Just subscribed
1594+ return (slnForSub, subscribed)
1595+
1596+cleanupSwitchSubscribed :: SwitchSubscribed a -> IO ()
1597+cleanupSwitchSubscribed subscribed = do
1598+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1599+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1600+ writeIORef (switchSubscribedCachedSubscribed subscribed) $! Nothing
1601+
1602+{-# INLINE subscribeSwitchSubscribed #-}
1603+subscribeSwitchSubscribed :: SwitchSubscribed a -> Subscriber a -> IO (SubscriberListTicket a)
1604+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1605+
1606+{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence a -> Subscriber a -> EventM x (SubscriberListTicket a, CoincidenceSubscribed a) #-}
1607+getCoincidenceSubscribed :: forall x a m. (Defer SomeAssignment m, Defer SomeHoldInit m, Defer SomeMergeInit m, Defer SomeClear m, HasCurrentHeight m, Defer SomeResetCoincidence m, HasSpiderEnv x m) => Coincidence a -> Subscriber a -> m (SubscriberListTicket a, CoincidenceSubscribed a)
1608+getCoincidenceSubscribed c sub = do
1609+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1610+ case mSubscribed of
1611+ Just subscribed -> {-# SCC "hitCoincidence" #-} do
1612+ sln <- liftIO $ subscribeCoincidenceSubscribed subscribed sub
1613+ return (sln, subscribed)
1614+ Nothing -> {-# SCC "missCoincidence" #-} do
1615+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1616+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1617+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1618+ outerSubscription@(EventSubscription _ outerSubd) <- subscribe (coincidenceParent c) subOuter
1619+ outerOcc <- liftIO $ readEventSubscribed outerSubd
1620+ outerHeight <- liftIO $ readIORef $ eventSubscribedHeightRef outerSubd
1621+ (occ, height, mInnerSubd) <- case outerOcc of
1622+ Nothing -> return (Nothing, outerHeight, Nothing)
1623+ Just o -> do
1624+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1625+ return (occ, height, Just innerSubd)
1626+ occRef <- liftIO $ newIORef occ
1627+ when (isJust occ) $ scheduleClear occRef
1628+ heightRef <- liftIO $ newIORef height
1629+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1630+ scheduleClear innerSubdRef
1631+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1632+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1633+ let subscribed = CoincidenceSubscribed
1634+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1635+ , coincidenceSubscribedOccurrence = occRef
1636+ , coincidenceSubscribedHeight = heightRef
1637+ , coincidenceSubscribedSubscribers = subs
1638+ , coincidenceSubscribedOuter = subOuter
1639+ , coincidenceSubscribedOuterParent = outerSubscription
1640+ , coincidenceSubscribedInnerParent = innerSubdRef
1641+ , coincidenceSubscribedWeakSelf = weakSelf
1642+#ifdef DEBUG_NODEIDS
1643+ , coincidenceSubscribedNodeId = unsafeNodeId c
1644+#endif
1645+ }
1646+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1647+ liftIO $ writeIORef subscribedRef $! subscribed
1648+ liftIO $ writeIORef (coincidenceSubscribed c) $! Just subscribed
1649+ return (slnForSub, subscribed)
1650+
1651+cleanupCoincidenceSubscribed :: CoincidenceSubscribed a -> IO ()
1652+cleanupCoincidenceSubscribed subscribed = do
1653+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1654+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) $! Nothing
1655+
1656+{-# INLINE subscribeCoincidenceSubscribed #-}
1657+subscribeCoincidenceSubscribed :: CoincidenceSubscribed a -> Subscriber a -> IO (SubscriberListTicket a)
1658+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1659+
1660+{-# INLINE merge #-}
1661+merge :: GCompare k => Dynamic R.PatchDMap (DMap k Event) -> Event (DMap k Identity)
1662+merge m = EventMerge $ Merge
1663+ { mergeParents = m
1664+ , mergeSubscribed = unsafeNewIORef m Nothing
1665+ }
1666+
1667+newtype EventSelector k = EventSelector { select :: forall a. k a -> Event a }
1668+
1669+fan :: GCompare k => Event (DMap k Identity) -> EventSelector k
1670+fan e =
1671+ let f = Fan
1672+ { fanParent = e
1673+ , fanSubscribed = unsafeNewIORef e Nothing
1674+ }
1675+ in EventSelector $ \k -> EventFan k f
1676+
1677+{- SPECIALIZE runHoldInits :: IORef [SomeHoldInit] -> IORef [SomeMergeInit] -> EventM x () #-}
1678+--runHoldInits :: (CanSubscribe x m, Defer SomeMergeUpdate m) => IORef [SomeHoldInit] -> IORef [SomeMergeInit] -> m ()
1679+runHoldInits :: IORef [SomeHoldInit] -> IORef [SomeMergeInit] -> EventM x ()
1680+runHoldInits holdInitRef mergeInitRef = do
1681+ holdInits <- liftIO $ readIORef holdInitRef
1682+ mergeInits <- liftIO $ readIORef mergeInitRef
1683+ if null holdInits && null mergeInits then return () else do
1684+ liftIO $ writeIORef holdInitRef $! []
1685+ liftIO $ writeIORef mergeInitRef $! []
1686+ mapM_ initHold holdInits
1687+ mapM_ initMerge mergeInits
1688+ runHoldInits holdInitRef mergeInitRef
1689+
1690+{- SPECIALIZE initHold :: SomeHoldInit -> EventM x () #-}
1691+--initHold :: CanSubscribe x m => SomeHoldInit -> m ()
1692+initHold :: SomeHoldInit -> EventM x ()
1693+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1694+
1695+{- SPECIALIZE initMerge :: SomeMergeInit -> EventM x () #-}
1696+--initMerge :: (CanSubscribe x m, Defer SomeMergeUpdate m) => SomeMergeInit -> m ()
1697+initMerge :: SomeMergeInit -> EventM x ()
1698+initMerge (SomeMergeInit subscribed changed) = do
1699+ changeSub <- liftIO $ newSubscriberMergeChange subscribed
1700+ EventSubscription _ changeSubd <- subscribe changed changeSub
1701+ change <- liftIO $ readEventSubscribed changeSubd
1702+ forM_ change $ \c -> defer $ SomeMergeUpdate c subscribed
1703+ liftIO $ writeIORef (mergeSubscribedChange subscribed) $! (changeSub, changeSubd)
1704+
1705+-- | Run an event action outside of a frame
1706+runFrame :: EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1707+runFrame a = SpiderHost $ ask >>= \spiderEnv -> lift $ do
1708+ -- Clear out pending unsubscriptions; these will need to happen eventually anyway, and might cause us a lot of extra work during the frame, so get rid of them now
1709+ pendingCleanups <- atomicModifyIORef (_spiderEnv_cleanups spiderEnv) $ \x -> ([], x)
1710+ {-# SCC "cleanups" #-} sequence_ pendingCleanups
1711+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1712+ holdInitRef <- newIORef []
1713+ mergeUpdateRef <- newIORef []
1714+ mergeInitRef <- newIORef []
1715+ heightRef <- newIORef zeroHeight
1716+ toClearRef <- newIORef []
1717+ toClearRootRef <- newIORef []
1718+ coincidenceInfosRef <- newIORef []
1719+ delayedRef <- liftIO $ newIORef IntMap.empty
1720+ let env = EventEnv spiderEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1721+ let go = do
1722+ result <- a
1723+ runHoldInits holdInitRef mergeInitRef -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1724+ return result
1725+ result <- runEventM go env
1726+ toClear <- readIORef toClearRef
1727+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref $! Nothing
1728+ toClearRoot <- readIORef toClearRootRef
1729+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1730+ toAssign <- readIORef toAssignRef
1731+ toReconnectRef <- newIORef []
1732+ coincidenceInfos <- readIORef coincidenceInfosRef
1733+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1734+ writeIORef vRef v
1735+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1736+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1737+ mergeUpdates <- readIORef mergeUpdateRef
1738+ writeIORef mergeUpdateRef $! []
1739+ let updateMerge :: SomeMergeUpdate -> IO [SomeEventSubscription]
1740+ updateMerge (SomeMergeUpdate (R.PatchDMap p :: R.PatchDMap (DMap k Event)) m) = do
1741+ oldParents <- readIORef $ mergeSubscribedParents m
1742+ let f (subscriptionsToKill, ps) (k :=> Compose me) = do
1743+ (mOldSubd, newPs) <- case me of
1744+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1745+ Just e -> do
1746+ s <- liftIO $ newSubscriberMerge k m
1747+ subscription@(EventSubscription _ subd) <- subscribe e s
1748+ let newParent = MergeSubscribedParent subscription s
1749+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1750+ liftIO $ addMergeHeight newParentHeight m
1751+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1752+ forM_ mOldSubd $ \oldSubd -> do
1753+ oldHeight <- liftIO $ readIORef $ eventSubscribedHeightRef $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription oldSubd
1754+ liftIO $ removeMergeHeight oldHeight m
1755+ return (maybeToList (SomeEventSubscription . mergeSubscribedParentSubscription <$> mOldSubd) ++ subscriptionsToKill, newPs)
1756+ (subscriptionsToKill, newParents) <- flip runEventM env $ foldM f ([], oldParents) $ DMap.toList p --TODO: I think this runEventM is OK, since no events are firing at this time, but it might not be
1757+ writeIORef (mergeSubscribedParents m) $! newParents
1758+ return subscriptionsToKill
1759+ when debugPropagate $ putStrLn "Updating merges"
1760+ mergeSubscriptionsToKill <- concat <$> mapM updateMerge mergeUpdates
1761+ when debugPropagate $ putStrLn "Updating merges done"
1762+ toReconnect <- readIORef toReconnectRef
1763+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1764+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1765+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1766+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1767+ finalize wi
1768+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1769+ wi' <- mkWeakPtrWithDebug i "wi'"
1770+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1771+ writeIORef (switchSubscribedBehaviorParents subscribed) $! []
1772+ writeIORef holdInitRef $! [] --TODO: Should we reuse this?
1773+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) holdInitRef
1774+ runEventM (runHoldInits holdInitRef mergeInitRef) env --TODO: Is this actually OK? It seems like it should be, since we know that no events are firing at this point, but it still seems inelegant
1775+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1776+ sub <- newSubscriberSwitch subscribed
1777+ subscription <- runReaderT (unSpiderHost (runFrame ({-# SCC "subscribeSwitch" #-} subscribe e sub))) spiderEnv --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient
1778+ {-
1779+ stackTrace <- liftIO $ liftM renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1780+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1781+ EventRoot _ -> "EventRoot"
1782+ EventNever -> "EventNever"
1783+ _ -> "something else"
1784+ -}
1785+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1786+ return $ SomeEventSubscription oldSubscription
1787+ forM_ mergeSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1788+ forM_ switchSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1789+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1790+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1791+ parentHeight <- readIORef $ eventSubscribedHeightRef subd'
1792+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1793+ when (parentHeight /= myHeight) $ do
1794+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1795+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1796+ forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> do
1797+ invalidateMergeHeight m --TODO: In addition to when the patch is completely empty, we should also not run this if it has some Nothing values, but none of them have actually had any effect; potentially, we could even check for Just values with no effect (e.g. by comparing their IORefs and ignoring them if they are unchanged); actually, we could just check if the new height is different
1798+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1799+ unsubscribe subscription
1800+ mapM_ invalidateCoincidenceHeight mcs
1801+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1802+ forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> revalidateMergeHeight m
1803+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1804+ height <- calculateSwitchHeight subscribed
1805+ updateSwitchHeight height subscribed
1806+ return result
1807+
1808+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1809+
1810+{-# INLINE zeroHeight #-}
1811+zeroHeight :: Height
1812+zeroHeight = Height 0
1813+
1814+{-# INLINE invalidHeight #-}
1815+invalidHeight :: Height
1816+invalidHeight = Height (-1000)
1817+
1818+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1819+{-# INLINE invalidHeightBeingTraversed #-}
1820+invalidHeightBeingTraversed :: Height
1821+invalidHeightBeingTraversed = Height (-1001)
1822+
1823+{-# INLINE succHeight #-}
1824+succHeight :: Height -> Height
1825+succHeight h@(Height a) =
1826+ if h == invalidHeight
1827+ then invalidHeight
1828+ else Height $ succ a
1829+
1830+invalidateSubscriberHeight :: Height -> Subscriber a -> IO ()
1831+invalidateSubscriberHeight old s = case s of
1832+ SubscriberPush _ subscribed -> do
1833+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1834+ WeakBag.traverse (pushSubscribedSubscribers subscribed) $ invalidateSubscriberHeight old
1835+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1836+ SubscriberMerge _ subscribed -> do
1837+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1838+ removeMergeHeight old subscribed
1839+ invalidateMergeHeight subscribed
1840+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1841+ SubscriberMergeChange _ -> return () -- Doesn't affect the height of the merge, because its changes are delayed
1842+ SubscriberFan subscribed -> do
1843+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1844+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1845+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
1846+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1847+ SubscriberHold _ -> return ()
1848+ SubscriberHoldIdentity _ -> return ()
1849+ SubscriberSwitch subscribed -> do
1850+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1851+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1852+ when (oldHeight /= invalidHeight) $ do
1853+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1854+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1855+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1856+ SubscriberCoincidenceOuter subscribed -> do
1857+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1858+ invalidateCoincidenceHeight subscribed
1859+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1860+ SubscriberCoincidenceInner subscribed -> do
1861+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1862+ invalidateCoincidenceHeight subscribed
1863+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1864+ SubscriberHandle -> return ()
1865+
1866+removeMergeHeight :: Height -> MergeSubscribed k -> IO ()
1867+removeMergeHeight oldParentHeight subscribed = do
1868+ when debugInvalidateHeight $ putStrLn $ "removeMergeHeight: " <> show oldParentHeight <> " Merge" <> showNodeId subscribed
1869+ oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1870+ let newHeights = heightBagRemove oldParentHeight oldHeights
1871+ writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1872+
1873+invalidateMergeHeight :: MergeSubscribed k -> IO ()
1874+invalidateMergeHeight subscribed = do
1875+ oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1876+ -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1877+ when (oldHeight /= invalidHeight) $ do
1878+ writeIORef (mergeSubscribedHeight subscribed) $! invalidHeight
1879+ WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1880+
1881+addMergeHeight :: Height -> MergeSubscribed k -> IO ()
1882+addMergeHeight newParentHeight subscribed = do
1883+ when debugInvalidateHeight $ putStrLn $ "addMergeHeight: " <> show newParentHeight <> " Merge" <> showNodeId subscribed
1884+ oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1885+ let newHeights = heightBagAdd newParentHeight oldHeights
1886+ writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1887+
1888+revalidateMergeHeight :: MergeSubscribed k -> IO ()
1889+revalidateMergeHeight subscribed = do
1890+ currentHeight <- readIORef $ mergeSubscribedHeight subscribed
1891+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1892+ heights <- readIORef $ mergeSubscribedHeightBag subscribed
1893+ parents <- readIORef $ mergeSubscribedParents subscribed
1894+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1895+ case heightBagSize heights `compare` DMap.size parents of
1896+ LT -> return ()
1897+ EQ -> do
1898+ let height = succHeight $ heightBagMax heights
1899+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1900+ writeIORef (mergeSubscribedHeight subscribed) $! height
1901+ WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1902+ GT -> error $ "revalidateMergeHeight: more heights than parents for Merge" <> showNodeId subscribed
1903+
1904+invalidateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1905+invalidateCoincidenceHeight subscribed = do
1906+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1907+ when (oldHeight /= invalidHeight) $ do
1908+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1909+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1910+
1911+recalculateSubscriberHeight :: Height -> Subscriber a -> IO ()
1912+recalculateSubscriberHeight new s = case s of
1913+ SubscriberPush _ subscribed -> do
1914+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
1915+ WeakBag.traverse (pushSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1916+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
1917+ SubscriberMerge _ subscribed -> do
1918+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
1919+ addMergeHeight new subscribed
1920+ revalidateMergeHeight subscribed
1921+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
1922+ SubscriberMergeChange _ -> return ()
1923+ SubscriberFan subscribed -> do
1924+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
1925+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1926+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
1927+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
1928+ SubscriberHold _ -> return ()
1929+ SubscriberHoldIdentity _ -> return ()
1930+ SubscriberSwitch subscribed -> do
1931+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
1932+ updateSwitchHeight new subscribed
1933+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
1934+ SubscriberCoincidenceOuter subscribed -> do
1935+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
1936+ recalculateCoincidenceHeight subscribed
1937+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
1938+ SubscriberCoincidenceInner subscribed -> do
1939+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
1940+ recalculateCoincidenceHeight subscribed
1941+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
1942+ SubscriberHandle -> return ()
1943+
1944+updateSwitchHeight :: Height -> SwitchSubscribed a -> IO ()
1945+updateSwitchHeight new subscribed = do
1946+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1947+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1948+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1949+ writeIORef (switchSubscribedHeight subscribed) $! new
1950+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1951+
1952+recalculateCoincidenceHeight :: CoincidenceSubscribed a -> IO ()
1953+recalculateCoincidenceHeight subscribed = do
1954+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1955+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1956+ height <- calculateCoincidenceHeight subscribed
1957+ when (height /= invalidHeight) $ do
1958+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1959+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1960+
1961+getEventSubscribedHeight :: EventSubscribed a -> IO Height
1962+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
1963+
1964+calculateSwitchHeight :: SwitchSubscribed a -> IO Height
1965+calculateSwitchHeight subscribed = readIORef . eventSubscribedHeightRef . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1966+
1967+calculateCoincidenceHeight :: CoincidenceSubscribed a -> IO Height
1968+calculateCoincidenceHeight subscribed = do
1969+ outerHeight <- readIORef $ eventSubscribedHeightRef $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1970+ innerHeight <- maybe (return zeroHeight) (readIORef . eventSubscribedHeightRef) =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1971+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1972+
1973+data SomeSwitchSubscribed = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed a)
1974+
1975+invalidate :: IORef [SomeSwitchSubscribed] -> WeakList Invalidator -> IO (WeakList Invalidator)
1976+invalidate toReconnectRef wis = do
1977+ forM_ wis $ \wi -> do
1978+ mi <- deRefWeak wi
1979+ case mi of
1980+ Nothing -> do
1981+ traceInvalidate "invalidate Dead"
1982+ return () --TODO: Should we clean this up here?
1983+ Just i -> do
1984+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1985+ case i of
1986+ InvalidatorPull p -> do
1987+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1988+ mVal <- readIORef $ pullValue p
1989+ forM_ mVal $ \val -> do
1990+ writeIORef (pullValue p) $! Nothing
1991+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1992+ InvalidatorSwitch subscribed -> do
1993+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1994+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1995+ return [] -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them
1996+
1997+--------------------------------------------------------------------------------
1998+-- Reflex integration
1999+--------------------------------------------------------------------------------
2000+
2001+type Spider = SpiderEnv Global
2002+
2003+data Global
2004+
2005+{-# NOINLINE globalSpiderEnv #-}
2006+globalSpiderEnv :: SpiderEnv Global
2007+globalSpiderEnv = unsafePerformIO unsafeNewSpiderEnv
2008+
2009+type role SpiderEnv nominal
2010+data SpiderEnv x = SpiderEnv
2011+ { _spiderEnv_toUnsubscribe :: !(IORef [SomeEventSubscription])
2012+ , _spiderEnv_lock :: !(MVar ())
2013+ , _spiderEnv_cleanups :: !(IORef [IO ()])
2014+#ifdef DEBUG
2015+ , _spiderEnv_depth :: !(IORef Int)
2016+#endif
2017+ }
2018+
2019+instance GEq SpiderEnv where
2020+ a `geq` b = if _spiderEnv_toUnsubscribe a == _spiderEnv_toUnsubscribe b
2021+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderEnv can't have two different 'x' arguments
2022+ else Nothing
2023+
2024+unsafeNewSpiderEnv :: forall x. IO (SpiderEnv x)
2025+unsafeNewSpiderEnv = do
2026+ toUnsubscribe <- newIORef []
2027+ lock <- newMVar ()
2028+ cleanups <- newIORef []
2029+#ifdef DEBUG
2030+ depthRef <- newIORef 0
2031+#endif
2032+ return $ SpiderEnv
2033+ { _spiderEnv_toUnsubscribe = toUnsubscribe
2034+ , _spiderEnv_lock = lock
2035+ , _spiderEnv_cleanups = cleanups
2036+#ifdef DEBUG
2037+ , _spiderEnv_depth = depthRef
2038+#endif
2039+ }
2040+
2041+newSpiderEnv :: IO (Some SpiderEnv)
2042+newSpiderEnv = Some.This <$> unsafeNewSpiderEnv
2043+
2044+newtype SpiderPullM x a = SpiderPullM { runSpiderPullM :: BehaviorM a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2045+
2046+newtype SpiderPushM x a = SpiderPushM { runSpiderPushM :: ComputeM a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2047+
2048+instance R.Reflex (SpiderEnv x) where
2049+ newtype Behavior (SpiderEnv x) a = SpiderBehavior { unSpiderBehavior :: Behavior a }
2050+ newtype Event (SpiderEnv x) a = SpiderEvent { unSpiderEvent :: Event a }
2051+ newtype Dynamic (SpiderEnv x) a = SpiderDynamic { unSpiderDynamic :: Dynamic Identity a } deriving (Functor, Applicative, Monad)
2052+ newtype Incremental (SpiderEnv x) p a = SpiderIncremental { unSpiderIncremental :: Dynamic p a }
2053+ type PullM (SpiderEnv x) = SpiderPullM x
2054+ type PushM (SpiderEnv x) = SpiderPushM x
2055+ {-# INLINABLE never #-}
2056+ never = SpiderEvent EventNever
2057+ {-# INLINABLE constant #-}
2058+ constant = SpiderBehavior . BehaviorConst
2059+ {-# INLINABLE push #-}
2060+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2061+ {-# INLINABLE pull #-}
2062+ pull = SpiderBehavior . pull . coerce
2063+ {-# INLINABLE merge #-}
2064+ merge = SpiderEvent . merge . DynamicConst . (unsafeCoerce :: DMap k (R.Event (SpiderEnv x)) -> DMap k Event)
2065+ {-# INLINABLE fan #-}
2066+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2067+ {-# INLINABLE switch #-}
2068+ switch = SpiderEvent . switch . (unsafeCoerce :: Behavior (R.Event (SpiderEnv x) a) -> Behavior (Event a)) . unSpiderBehavior
2069+ {-# INLINABLE coincidence #-}
2070+ coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event (R.Event (SpiderEnv x) a) -> Event (Event a)) . unSpiderEvent
2071+ {-# INLINABLE current #-}
2072+ current = SpiderBehavior . current . unSpiderDynamic
2073+ {-# INLINABLE updated #-}
2074+ updated = SpiderEvent . fmap runIdentity . updated . unSpiderDynamic
2075+ {-# INLINABLE unsafeBuildDynamic #-}
2076+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (coerce readV0) $ addIdentity $ unSpiderEvent v'
2077+ {-# INLINABLE unsafeBuildIncremental #-}
2078+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ DynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2079+ {-# INLINABLE mergeIncremental #-}
2080+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic R.PatchDMap (DMap k (R.Event (SpiderEnv x))) -> Dynamic R.PatchDMap (DMap k Event)) . unSpiderIncremental
2081+ {-# INLINABLE currentIncremental #-}
2082+ currentIncremental = SpiderBehavior . current . unSpiderIncremental
2083+ {-# INLINABLE updatedIncremental #-}
2084+ updatedIncremental = SpiderEvent . updated . unSpiderIncremental
2085+ {-# INLINABLE incrementalToDynamic #-}
2086+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ current i) $ flip push (updated i) $ \p -> do
2087+ c <- readBehaviorUntracked $ current i
2088+ return $ fmap Identity $ R.apply p c --TODO: Avoid the redundant 'apply'
2089+
2090+instance R.MonadSample (SpiderEnv x) (EventM x) where
2091+ {-# INLINABLE sample #-}
2092+ sample (SpiderBehavior b) = readBehaviorUntracked b
2093+
2094+instance R.MonadHold (SpiderEnv x) (EventM x) where
2095+ {-# INLINABLE hold #-}
2096+ hold = holdSpiderEventM
2097+ {-# INLINABLE holdDyn #-}
2098+ holdDyn = holdDynSpiderEventM
2099+ {-# INLINABLE holdIncremental #-}
2100+ holdIncremental = holdIncrementalSpiderEventM
2101+
2102+holdSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Behavior (SpiderEnv x) a)
2103+holdSpiderEventM v0 e = liftM (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2104+
2105+holdDynSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Dynamic (SpiderEnv x) a)
2106+holdDynSpiderEventM v0 e = liftM (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2107+
2108+holdIncrementalSpiderEventM :: R.Patch p => a -> R.Event (SpiderEnv x) (p a) -> EventM x (R.Incremental (SpiderEnv x) p a)
2109+holdIncrementalSpiderEventM v0 e = liftM (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2110+
2111+instance R.MonadHold (SpiderEnv x) (SpiderHost x) where
2112+ {-# INLINABLE hold #-}
2113+ hold v0 e = R.runHostFrame $ R.hold v0 e
2114+ {-# INLINABLE holdDyn #-}
2115+ holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
2116+ {-# INLINABLE holdIncremental #-}
2117+ holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
2118+
2119+instance R.MonadSample (SpiderEnv x) (SpiderHost x) where
2120+ {-# INLINABLE sample #-}
2121+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2122+
2123+instance R.MonadSample (SpiderEnv x) (SpiderPullM x) where
2124+ {-# INLINABLE sample #-}
2125+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2126+
2127+instance R.MonadSample (SpiderEnv x) (SpiderPushM x) where
2128+ {-# INLINABLE sample #-}
2129+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2130+
2131+instance R.MonadHold (SpiderEnv x) (SpiderPushM x) where
2132+ {-# INLINABLE hold #-}
2133+ hold v0 e = R.current <$> R.holdDyn v0 e
2134+ {-# INLINABLE holdDyn #-}
2135+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ liftM (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity e
2136+ {-# INLINABLE holdIncremental #-}
2137+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ liftM (SpiderIncremental . DynamicHold) $ hold v0 e
2138+
2139+data RootTrigger a = forall k. GCompare k => RootTrigger (SubscriberList a, IORef (DMap k Identity), k a)
2140+newtype SpiderEventHandle a = SpiderEventHandle { unSpiderEventHandle :: EventSubscription a }
2141+
2142+instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHostFrame x) where
2143+ {-# INLINABLE subscribeEvent #-}
2144+ subscribeEvent e = SpiderHostFrame $ do
2145+ subscription <- subscribe (unSpiderEvent e) SubscriberHandle --TODO: Unsubscribe eventually (manually and/or with weak ref)
2146+ return $ SpiderEventHandle subscription
2147+
2148+instance R.ReflexHost (SpiderEnv x) where
2149+ type EventTrigger (SpiderEnv x) = RootTrigger
2150+ type EventHandle (SpiderEnv x) = SpiderEventHandle
2151+ type HostFrame (SpiderEnv x) = SpiderHostFrame x
2152+
2153+instance R.MonadReadEvent (SpiderEnv x) (ReadPhase x) where
2154+ {-# INLINABLE readEvent #-}
2155+ readEvent h = ReadPhase $ liftM (fmap return) $ liftIO $ do
2156+ let EventSubscription sln subscribed = unSpiderEventHandle h
2157+ result <- readEventSubscribed subscribed
2158+ touch sln
2159+ return result
2160+
2161+instance MonadRef (EventM x) where
2162+ type Ref (EventM x) = Ref IO
2163+ {-# INLINABLE newRef #-}
2164+ {-# INLINABLE readRef #-}
2165+ {-# INLINABLE writeRef #-}
2166+ newRef = liftIO . newRef
2167+ readRef = liftIO . readRef
2168+ writeRef r a = liftIO $ writeRef r a
2169+
2170+instance MonadAtomicRef (EventM x) where
2171+ {-# INLINABLE atomicModifyRef #-}
2172+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2173+
2174+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2175+
2176+instance Monad (SpiderHost x) where
2177+ {-# INLINABLE (>>=) #-}
2178+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2179+ {-# INLINABLE (>>) #-}
2180+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2181+ {-# INLINABLE return #-}
2182+ return x = SpiderHost $ return x
2183+ {-# INLINABLE fail #-}
2184+ fail s = SpiderHost $ fail s
2185+
2186+runSpiderHost :: SpiderHost Global a -> IO a
2187+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderEnv
2188+
2189+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2190+
2191+instance Monad (SpiderHostFrame x) where
2192+ {-# INLINABLE (>>=) #-}
2193+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2194+ {-# INLINABLE (>>) #-}
2195+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2196+ {-# INLINABLE return #-}
2197+ return x = SpiderHostFrame $ return x
2198+ {-# INLINABLE fail #-}
2199+ fail s = SpiderHostFrame $ fail s
2200+
2201+instance R.MonadSample (SpiderEnv x) (SpiderHostFrame x) where
2202+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2203+
2204+addIdentity :: Event a -> Event (Identity a)
2205+--addIdentity = fmap Identity
2206+addIdentity = unsafeCoerce
2207+
2208+instance R.MonadHold (SpiderEnv x) (SpiderHostFrame x) where
2209+ {-# INLINABLE hold #-}
2210+ hold v0 e = SpiderHostFrame $ liftM (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2211+ {-# INLINABLE holdDyn #-}
2212+ holdDyn v0 e = SpiderHostFrame $ liftM (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2213+ {-# INLINABLE holdIncremental #-}
2214+ holdIncremental v0 e = SpiderHostFrame $ liftM (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2215+
2216+newEventWithTriggerIO :: forall a. (RootTrigger a -> IO (IO ())) -> IO (Event a)
2217+newEventWithTriggerIO f = do
2218+ es <- newFanEventWithTriggerIO $ \Refl -> f
2219+ return $ select es Refl
2220+
2221+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger a -> IO (IO ())) -> IO (EventSelector k)
2222+newFanEventWithTriggerIO f = do
2223+ occRef <- newIORef DMap.empty
2224+ subscribedRef <- newIORef DMap.empty
2225+ let !r = Root
2226+ { rootOccurrence = occRef
2227+ , rootSubscribed = subscribedRef
2228+ , rootInit = f
2229+ }
2230+ return $ EventSelector $ \k -> EventRoot k r
2231+
2232+instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHost x) where
2233+ newEventWithTrigger = SpiderHost . lift . liftM SpiderEvent . newEventWithTriggerIO
2234+ newFanEventWithTrigger f = SpiderHost $ lift $ do
2235+ es <- newFanEventWithTriggerIO f
2236+ return $ R.EventSelector $ SpiderEvent . select es
2237+
2238+instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHostFrame x) where
2239+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . liftM SpiderEvent . newEventWithTriggerIO
2240+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2241+ es <- newFanEventWithTriggerIO f
2242+ return $ R.EventSelector $ SpiderEvent . select es
2243+
2244+instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHost x) where
2245+ {-# INLINABLE subscribeEvent #-}
2246+ subscribeEvent = subscribeEventSpiderHost
2247+
2248+subscribeEventSpiderHost :: R.Event (SpiderEnv x) a -> SpiderHost x (R.EventHandle (SpiderEnv x) a)
2249+subscribeEventSpiderHost e = do
2250+ subscription <- runFrame $ subscribe (unSpiderEvent e) SubscriberHandle --TODO: Unsubscribe eventually (manually and/or with weak ref)
2251+ return $ SpiderEventHandle subscription
2252+
2253+newtype ReadPhase x a = ReadPhase { runReadPhase :: ResultM x a } deriving (Functor, Applicative, Monad, MonadFix)
2254+
2255+instance R.MonadSample (SpiderEnv x) (ReadPhase x) where
2256+ {-# INLINABLE sample #-}
2257+ sample = ReadPhase . R.sample
2258+
2259+instance R.MonadHold (SpiderEnv x) (ReadPhase x) where
2260+ {-# INLINABLE hold #-}
2261+ hold v0 e = ReadPhase $ R.hold v0 e
2262+ {-# INLINABLE holdDyn #-}
2263+ holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2264+ {-# INLINABLE holdIncremental #-}
2265+ holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2266+
2267+instance R.MonadReflexHost (SpiderEnv x) (SpiderHost x) where
2268+ type ReadPhase (SpiderHost x) = ReadPhase x
2269+ fireEventsAndRead es (ReadPhase a) = run es a
2270+ runHostFrame = runFrame . runSpiderHostFrame
2271+
2272+instance MonadRef (SpiderHost x) where
2273+ type Ref (SpiderHost x) = Ref IO
2274+ newRef = SpiderHost . newRef
2275+ readRef = SpiderHost . readRef
2276+ writeRef r = SpiderHost . writeRef r
2277+
2278+instance MonadAtomicRef (SpiderHost x) where
2279+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2280+
2281+instance MonadRef (SpiderHostFrame x) where
2282+ type Ref (SpiderHostFrame x) = Ref IO
2283+ newRef = SpiderHostFrame . newRef
2284+ readRef = SpiderHostFrame . readRef
2285+ writeRef r = SpiderHostFrame . writeRef r
2286+
2287+instance MonadAtomicRef (SpiderHostFrame x) where
2288+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r