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