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