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