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