@@ -1,2049 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE ExistentialQuantification #-}
6−{-# LANGUAGE FlexibleContexts #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
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−#ifdef USE_REFLEX_OPTIMIZER
22−{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
24−#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
25−{-# OPTIONS_GHC -fno-warn-orphans #-}
27−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
28−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
29−module Reflex.Spider.Internal where
31−import Control.Applicative
32−import Control.Concurrent
33−import Control.Exception
34−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
35−import Control.Monad.Exception
36−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
37−import Control.Monad.Primitive
38−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
39−import Control.Monad.Ref
42−import Data.Dependent.Map (DMap, DSum (..))
43−import qualified Data.Dependent.Map as DMap
44−import Data.Foldable hiding (concat, elem, sequence_)
46−import Data.Functor.Constant
47−import Data.Functor.Misc
48−import Data.Functor.Product
49−import Data.GADT.Compare
50−import Data.IntMap.Strict (IntMap)
51−import qualified Data.IntMap.Strict as IntMap
53−import Data.List hiding (foldl')
55−import Data.Monoid ((<>))
58−import Data.Traversable
61−import GHC.IORef (IORef (..))
63−import Reflex.FunctorMaybe
64−import System.IO.Unsafe
65−import System.Mem.Weak
69−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
70−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
71−import qualified Data.List.NonEmpty as NonEmpty
72−import Data.Monoid (mempty)
73−import Data.Tree (Forest, Tree (..), drawForest)
76−import Data.WeakBag (WeakBag, WeakBagTicket)
77−import qualified Data.WeakBag as WeakBag
78−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
79−import Data.Reflection
80−import Data.Some (Some)
81−import qualified Data.Some as Some
82−import Data.Type.Coercion
83−import qualified Reflex.Class
84−import qualified Reflex.Class as R
85−import qualified Reflex.Host.Class
89−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
90−import Prelude hiding (any, concat, mapM, mapM_, sequence)
92−debugPropagate :: Bool
94−debugInvalidateHeight :: Bool
96−debugInvalidate :: Bool
100−#define DEBUG_NODEIDS
102−debugPropagate = True
104−debugInvalidateHeight = False
106−debugInvalidate = True
108−class HasNodeId a where
109− getNodeId :: a -> Int
111−instance HasNodeId (Hold x p a) where
112− getNodeId = holdNodeId
114−instance HasNodeId (PushSubscribed x a b) where
115− getNodeId = pushSubscribedNodeId
117−instance HasNodeId (SwitchSubscribed x a) where
118− getNodeId = switchSubscribedNodeId
120−instance HasNodeId (FanSubscribed x a) where
121− getNodeId = fanSubscribedNodeId
123−instance HasNodeId (CoincidenceSubscribed x a) where
124− getNodeId = coincidenceSubscribedNodeId
126−instance HasNodeId (RootSubscribed x a) where
127− getNodeId = rootSubscribedNodeId
129−instance HasNodeId (Pull x a) where
130− getNodeId = pullNodeId
132−{-# INLINE showNodeId #-}
133−showNodeId :: HasNodeId a => a -> String
134−showNodeId = ("#"<>) . show . getNodeId
136−showSubscriberType :: Subscriber x a -> String
137−showSubscriberType = \case
138− SubscriberPush _ _ -> "SubscriberPush"
139− SubscriberMerge _ _ -> "SubscriberMerge"
140− SubscriberFan _ -> "SubscriberFan"
141− SubscriberMergeChange _ -> "SubscriberMergeChange"
142− SubscriberHold _ -> "SubscriberHold"
143− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
144− SubscriberSwitch _ -> "SubscriberSwitch"
145− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
146− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
147− SubscriberHandle -> "SubscriberHandle"
149−showEventType :: Event x a -> String
150−showEventType = \case
151− EventRoot _ _ -> "EventRoot"
152− EventNever -> "EventNever"
153− EventPush _ -> "EventPush"
154− EventMerge _ -> "EventMerge"
155− EventFan _ _ -> "EventFan"
156− EventSwitch _ -> "EventSwitch"
157− EventCoincidence _ -> "EventCoincidence"
158− EventHold _ -> "EventHold"
159− EventDyn _ -> "EventDyn"
160− EventHoldIdentity _ -> "EventHoldIdentity"
161− EventDynIdentity _ -> "EventDynIdentity"
165−debugPropagate = False
167−debugInvalidateHeight = False
169−debugInvalidate = False
171−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
172−{-# INLINE showNodeId #-}
173−showNodeId :: a -> String
179−{-# NOINLINE nextNodeIdRef #-}
180−nextNodeIdRef :: IORef Int
181−nextNodeIdRef = unsafePerformIO $ newIORef 1
184−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
186−{-# NOINLINE unsafeNodeId #-}
187−unsafeNodeId :: a -> Int
188−unsafeNodeId a = unsafePerformIO $ do
193−--------------------------------------------------------------------------------
195−--------------------------------------------------------------------------------
197−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
199−{-# INLINE subscribeAndRead #-}
200−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
201−subscribeAndRead = unEvent
204−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
205−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
206−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
209−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
210−-- caching; if the computation function is very cheap, this is (much) more
211−-- efficient than 'push'
212−{-# NOINLINE pushCheap #-}
213−pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
214−pushCheap f e = Event $ \sub -> do
215− (subscription, occ) <- subscribeAndRead e $ sub
216− { subscriberPropagate = \a -> do
217− mb <- runComputeM $ f a
218− mapM_ (subscriberPropagate sub) mb
220− occ' <- join <$> mapM (runComputeM . f) occ
221− return (subscription, occ')
223−data CacheSubscribed x a
224− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))
225− , _cacheSubscribed_weakSelf :: {-# UNPACK #-} !(IORef (Weak (CacheSubscribed x a)))
226− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
227− , _cacheSubscribed_cached :: {-# UNPACK #-} !(IORef (Maybe (CacheSubscribed x a)))
228− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
231−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
234−--TODO: Try a caching strategy where we subscribe directly to the parent when
235−--there's only one subscriber, and then build our own WeakBag only when a second
237−{-# NOINLINE cacheEvent #-}
238−cacheEvent :: HasSpiderTimeline x => Event x a -> Event x a
239−cacheEvent e = Event $ \sub -> {-# SCC "cacheEvent" #-} do
240− let !mSubscribedRef = unsafeNewIORef e Nothing
241− mSubscribed <- liftIO $ readIORef mSubscribedRef
243− Just subscribed -> liftIO $ do
244− ticket <- WeakBag.insert sub (_cacheSubscribed_subscribers subscribed) (_cacheSubscribed_weakSelf subscribed) cleanupCacheSubscribed
245− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
246− let es = EventSubscribed
247− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
248− , eventSubscribedRetained = toAny subscribed
250− return (EventSubscription (WeakBag.remove ticket >> touch ticket) es, occ)
252− weakSelf <- liftIO $ newIORef $ error "cacheEvent: weakSelf not yet intialized"
253− (subscribers, ticket) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCacheSubscribed
254− occRef <- liftIO $ newIORef undefined
255− (parentSub, occ) <- subscribeAndRead e $ Subscriber
256− { subscriberPropagate = \a -> do
257− liftIO $ writeIORef occRef $ Just a
258− scheduleClear occRef
259− propagate a subscribers
260− , subscriberInvalidateHeight = \old -> do
261− WeakBag.traverse subscribers $ invalidateSubscriberHeight old
262− , subscriberRecalculateHeight = \new -> do
263− WeakBag.traverse subscribers $ recalculateSubscriberHeight new
265− liftIO $ writeIORef occRef occ
266− when (isJust occ) $ scheduleClear occRef
267− let !subscribed = CacheSubscribed
268− { _cacheSubscribed_subscribers = subscribers
269− , _cacheSubscribed_weakSelf = weakSelf
270− , _cacheSubscribed_parent = parentSub
271− , _cacheSubscribed_cached = mSubscribedRef
272− , _cacheSubscribed_occurrence = occRef
274− liftIO $ writeIORef mSubscribedRef $ Just subscribed
275− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
276− return (EventSubscription (WeakBag.remove ticket >> touch ticket) (EventSubscribed (eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub) (toAny subscribed)), occ)
278−cleanupCacheSubscribed :: CacheSubscribed x a -> IO ()
279−cleanupCacheSubscribed self = do
280− unsubscribe $ _cacheSubscribed_parent self
281− writeIORef (_cacheSubscribed_cached self) Nothing
283−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
284−subscribe e s = fst <$> subscribeAndRead e s
287−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
288−wrap tag getSpecificSubscribed sub = do
289− (sln, subd, occ) <- getSpecificSubscribed sub
291− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
293−eventRoot :: GCompare k => k a -> Root x k -> Event x a
294−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
296−eventNever :: Event x a
297−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
299−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
300−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
302−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
303−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
305−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
306−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
308−eventHold :: HasSpiderTimeline x => Hold x p -> Event x p
309−eventHold !h = Event $ subscribeHoldEvent h
311−eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
312−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
314−{-# INLINE subscribeCoincidenceInner #-}
315−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x)
316−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
317− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
318− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
319− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
320− let height = max innerHeight outerHeight
321− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
322− return (innerOcc, height, innerSubd)
324−--------------------------------------------------------------------------------
326−--------------------------------------------------------------------------------
328−data Subscriber x a = Subscriber
329− { subscriberPropagate :: !(a -> EventM x ())
330− , subscriberInvalidateHeight :: !(Height -> IO ())
331− , subscriberRecalculateHeight :: !(Height -> IO ())
334−--TODO: Move this comment to WeakBag
335−-- These function are constructor functions that are marked NOINLINE so they are
336−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
337−-- so any weak references that are attached to the constructors will have their
338−-- finalizer run. Using the opaque constructor, does not see the
339−-- constructor application, so it behaves like an IORef and cannot be fused away.
341−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
342−-- the weak pointer to it in some cases.
344−newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
345−newSubscriberHold h = return $ Subscriber
346− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
347− , subscriberInvalidateHeight = \_ -> return ()
348− , subscriberRecalculateHeight = \_ -> return ()
351−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
352−newSubscriberFan subscribed = return $ Subscriber
353− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
354− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
355− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
356− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
357− scheduleClear $ fanSubscribedOccurrence subscribed
358− let f _ (Pair (Identity v) subsubs) = do
359− propagate v $ _fanSubscribedChildren_list subsubs
360− return $ Constant ()
361− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
363− , subscriberInvalidateHeight = \old -> do
364− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
365− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
366− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
367− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
368− , subscriberRecalculateHeight = \new -> do
369− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
370− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
371− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
372− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
375−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
376−newSubscriberSwitch subscribed = return $ Subscriber
377− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
378− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
379− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
380− scheduleClear $ switchSubscribedOccurrence subscribed
381− propagate a $ switchSubscribedSubscribers subscribed
382− , subscriberInvalidateHeight = \_ -> do
383− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
384− oldHeight <- readIORef $ switchSubscribedHeight subscribed
385− when (oldHeight /= invalidHeight) $ do
386− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
387− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
388− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
389− , subscriberRecalculateHeight = \new -> do
390− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
391− updateSwitchHeight new subscribed
392− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
395−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
396−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
397− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
398− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
399− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
400− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
401− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
402− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
403− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
404− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
405− scheduleClear $ coincidenceSubscribedInnerParent subscribed
408− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
409− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
410− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
411− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
412− Just o -> do -- Since it's already firing, no need to adjust height
413− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
414− scheduleClear $ coincidenceSubscribedOccurrence subscribed
415− propagate o $ coincidenceSubscribedSubscribers subscribed
416− , subscriberInvalidateHeight = \_ -> do
417− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
418− invalidateCoincidenceHeight subscribed
419− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
420− , subscriberRecalculateHeight = \_ -> do
421− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
422− recalculateCoincidenceHeight subscribed
423− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
426−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
427−newSubscriberCoincidenceInner subscribed = return $ Subscriber
428− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
429− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
430− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
432− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
434− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
435− scheduleClear $ coincidenceSubscribedOccurrence subscribed
436− propagate a $ coincidenceSubscribedSubscribers subscribed
437− , subscriberInvalidateHeight = \_ -> do
438− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
439− invalidateCoincidenceHeight subscribed
440− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
441− , subscriberRecalculateHeight = \_ -> do
442− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
443− recalculateCoincidenceHeight subscribed
444− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
447−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
448−invalidateSubscriberHeight = flip subscriberInvalidateHeight
450−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
451−recalculateSubscriberHeight = flip subscriberRecalculateHeight
453−-- | Propagate everything at the current height
454−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
455−propagate a subscribers = withIncreasedDepth $ do
456− -- 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
457− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
458− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
460−--------------------------------------------------------------------------------
462−--------------------------------------------------------------------------------
467−data EventSubscribed x = EventSubscribed
468− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
469− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
471− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
472− , eventSubscribedHasOwnHeightRef :: !Bool
473− , eventSubscribedWhoCreated :: !(IO [String])
477−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
478−eventSubscribedRoot !r = EventSubscribed
479− { eventSubscribedHeightRef = zeroRef
480− , eventSubscribedRetained = toAny r
482− , eventSubscribedGetParents = return []
483− , eventSubscribedHasOwnHeightRef = False
484− , eventSubscribedWhoCreated = return ["root"]
488−eventSubscribedNever :: EventSubscribed x
489−eventSubscribedNever = EventSubscribed
490− { eventSubscribedHeightRef = zeroRef
491− , eventSubscribedRetained = toAny ()
493− , eventSubscribedGetParents = return []
494− , eventSubscribedHasOwnHeightRef = False
495− , eventSubscribedWhoCreated = return ["never"]
499−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
500−eventSubscribedFan !subscribed = EventSubscribed
501− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
502− , eventSubscribedRetained = toAny subscribed
504− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
505− , eventSubscribedHasOwnHeightRef = False
506− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
510−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
511−eventSubscribedSwitch !subscribed = EventSubscribed
512− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
513− , eventSubscribedRetained = toAny subscribed
515− , eventSubscribedGetParents = do
516− s <- readIORef $ switchSubscribedCurrentParent subscribed
517− return [Some.This $ _eventSubscription_subscribed s]
518− , eventSubscribedHasOwnHeightRef = True
519− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
523−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
524−eventSubscribedCoincidence !subscribed = EventSubscribed
525− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
526− , eventSubscribedRetained = toAny subscribed
528− , eventSubscribedGetParents = do
529− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
530− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
531− innerParents = maybeToList $ fmap Some.This innerSubscription
532− return $ outerParent : innerParents
533− , eventSubscribedHasOwnHeightRef = True
534− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
538−getEventSubscribedHeight :: EventSubscribed x -> IO Height
539−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
542−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
543−whoCreatedEventSubscribed = eventSubscribedWhoCreated
545−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
546−walkInvalidHeightParents s0 = do
547− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
548− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
549− when (h == invalidHeight) $ do
550− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
551− modify (Some.This s :)
552− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
553− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
557−{-# INLINE subscribeHoldEvent #-}
558−subscribeHoldEvent :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (EventSubscription x, Maybe p)
559−subscribeHoldEvent = subscribeAndRead . holdEvent
561−--------------------------------------------------------------------------------
563−--------------------------------------------------------------------------------
565−data EventSubscription x = EventSubscription
566− { _eventSubscription_unsubscribe :: !(IO ())
567− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
570−unsubscribe :: EventSubscription x -> IO ()
571−unsubscribe (EventSubscription u _) = u
573−--------------------------------------------------------------------------------
575−--------------------------------------------------------------------------------
577−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
579−behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
580−behaviorHold !h = Behavior $ readHoldTracked h
582−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
583−behaviorHoldIdentity = behaviorHold
585−behaviorConst :: a -> Behavior x a
586−behaviorConst !a = Behavior $ return a
588−behaviorPull :: Pull x a -> Behavior x a
589−behaviorPull !p = Behavior $ do
590− val <- liftIO $ readIORef $ pullValue p
592− Just subscribed -> do
593− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
594− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
595− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
596− return $ pullSubscribedValue subscribed
598− i <- liftIO $ newInvalidatorPull p
599− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
600− parentsRef <- liftIO $ newIORef []
601− holdInits <- askBehaviorHoldInits
602− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
603− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
604− parents <- liftIO $ readIORef parentsRef
605− let subscribed = PullSubscribed
606− { pullSubscribedValue = a
607− , pullSubscribedInvalidators = invsRef
608− , pullSubscribedOwnInvalidator = i
609− , pullSubscribedParents = parents
611− liftIO $ writeIORef (pullValue p) $ Just subscribed
612− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
615−behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
616−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
618−{-# INLINE readHoldTracked #-}
619−readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
620−readHoldTracked h = do
621− result <- liftIO $ readIORef $ holdValue h
622− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
623− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
626−{-# INLINABLE readBehaviorUntracked #-}
627−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
628−readBehaviorUntracked b = do
629− holdInits <- getDeferralQueue
630− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
632−--------------------------------------------------------------------------------
634−--------------------------------------------------------------------------------
636−data Dynamic x p = Dynamic
637− { dynamicCurrent :: !(Behavior x (PatchTarget p))
638− , dynamicUpdated :: !(Event x p)
641−dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
642−dynamicHold !h = Dynamic
643− { dynamicCurrent = behaviorHold h
644− , dynamicUpdated = eventHold h
647−dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
648−dynamicHoldIdentity = dynamicHold
650−dynamicConst :: PatchTarget p -> Dynamic x p
651−dynamicConst !a = Dynamic
652− { dynamicCurrent = behaviorConst a
653− , dynamicUpdated = eventNever
656−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
657−dynamicDyn !d = Dynamic
658− { dynamicCurrent = behaviorDyn d
659− , dynamicUpdated = eventDyn d
662−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
663−dynamicDynIdentity = dynamicDyn
665−--------------------------------------------------------------------------------
667−--------------------------------------------------------------------------------
669−--TODO: Figure out why certain things are not 'representational', then make them
670−--representational so we can use coerce
672−--type role Hold representational
674− = Hold { holdValue :: !(IORef (PatchTarget p))
675− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
676− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
677− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
683−-- | A statically allocated 'SpiderTimeline'; this is the only instance of
684−-- 'SpiderTimeline' that can used when using
685−-- -fspecialize-to-spidertimeline-global.
688−{-# NOINLINE globalSpiderTimelineEnv #-}
689−globalSpiderTimelineEnv :: SpiderTimelineEnv Global
690−globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
692−-- | Stores all global data relevant to a particular Spider timeline; only one
693−-- value should exist for each type @x@
694−data SpiderTimelineEnv x = SpiderTimelineEnv
695− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
696− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
698− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
701−type role SpiderTimelineEnv nominal
703−instance GEq SpiderTimelineEnv where
704− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
705− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
709− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
710− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
711− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
712− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
713− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
714− , eventEnvRootClears :: !(IORef [SomeRootClear])
715− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
716− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
717− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
720−{-# INLINE runEventM #-}
721−runEventM :: EventM x a -> IO a
724−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
725−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
727−class MonadIO m => Defer a m where
728− getDeferralQueue :: m (IORef [a])
731−defer :: Defer a m => a -> m ()
733− q <- getDeferralQueue
734− liftIO $ modifyIORef' q (a:)
736−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
737− {-# INLINE getDeferralQueue #-}
738− getDeferralQueue = asksEventEnv eventEnvAssignments
740−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
741− {-# INLINE getDeferralQueue #-}
742− getDeferralQueue = asksEventEnv eventEnvHoldInits
744−instance Defer (SomeHoldInit x) (BehaviorM x) where
745− {-# INLINE getDeferralQueue #-}
746− getDeferralQueue = BehaviorM $ asks snd
748−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
749− {-# INLINE getDeferralQueue #-}
750− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
752−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
753− {-# INLINE getDeferralQueue #-}
754− getDeferralQueue = asksEventEnv eventEnvMergeInits
756−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
757− getCurrentHeight :: m Height
758− scheduleMerge :: Height -> EventM x () -> m ()
760−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
761− {-# INLINE getCurrentHeight #-}
762− getCurrentHeight = do
763− heightRef <- asksEventEnv eventEnvCurrentHeight
764− liftIO $ readIORef heightRef
765− {-# INLINE scheduleMerge #-}
766− scheduleMerge height subscribed = do
767− delayedRef <- asksEventEnv eventEnvDelayedMerges
768− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
770−#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
771−class x ~ Global => HasSpiderTimeline x where
773−class HasSpiderTimeline x where
775− -- | Retrieve the current SpiderTimelineEnv
776− spiderTimeline :: SpiderTimelineEnv x
778−instance HasSpiderTimeline Global where
779− spiderTimeline = globalSpiderTimelineEnv
781−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
782−putCurrentHeight h = do
783− heightRef <- asksEventEnv eventEnvCurrentHeight
784− liftIO $ writeIORef heightRef $! h
786−instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
787− {-# INLINE getDeferralQueue #-}
788− getDeferralQueue = asksEventEnv eventEnvClears
790−{-# INLINE scheduleClear #-}
791−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
792−scheduleClear r = defer $ SomeClear r
794−instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
795− {-# INLINE getDeferralQueue #-}
796− getDeferralQueue = asksEventEnv eventEnvRootClears
798−{-# INLINE scheduleRootClear #-}
799−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
800−scheduleRootClear r = defer $ SomeRootClear r
802−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
803− {-# INLINE getDeferralQueue #-}
804− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
806−-- Note: hold cannot examine its event until after the phase is over
807−{-# INLINE [1] hold #-}
808−hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
810− valRef <- liftIO $ newIORef v0
811− invsRef <- liftIO $ newIORef []
812− parentRef <- liftIO $ newIORef Nothing
814− nodeId <- liftIO newNodeId
817− { holdValue = valRef
818− , holdInvalidators = invsRef
820− , holdParent = parentRef
822− , holdNodeId = nodeId
825− defer $ SomeHoldInit h
828−{-# INLINE getHoldEventSubscription #-}
829−getHoldEventSubscription :: forall m p x. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer SomeClear m, Patch p, HasCurrentHeight x m, Defer (SomeMergeInit x) m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Hold x p -> m (EventSubscription x)
830−getHoldEventSubscription h = do
831− ep <- liftIO $ readIORef $ holdParent h
833− Just subd -> return subd
836− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
837− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
838− liftIO $ writeIORef subscriptionRef $! subscription
840− Nothing -> return ()
842− old <- liftIO $ readIORef $ holdValue h
844− Nothing -> return ()
846− -- Need to evaluate these so that we don't retain the Hold itself
847− v <- liftIO $ evaluate $ holdValue h
848− i <- liftIO $ evaluate $ holdInvalidators h
849− defer $ SomeAssignment v i new
850− liftIO $ writeIORef (holdParent h) $ Just subscription
853−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
855−--type role BehaviorM representational
856−-- BehaviorM can sample behaviors
857−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
859−instance Monad (BehaviorM x) where
860− {-# INLINE (>>=) #-}
861− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
863− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
864− {-# INLINE return #-}
865− return x = BehaviorM $ return x
867− fail s = BehaviorM $ fail s
869−data BehaviorSubscribed x a
870− = forall p. BehaviorSubscribedHold (Hold x p)
871− | BehaviorSubscribedPull (PullSubscribed x a)
873−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
875−--type role PullSubscribed representational
876−data PullSubscribed x a
877− = PullSubscribed { pullSubscribedValue :: !a
878− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
879− , pullSubscribedOwnInvalidator :: !(Invalidator x)
880− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
883−--type role Pull representational
885− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
886− , pullCompute :: !(BehaviorM x a)
893− = forall a. InvalidatorPull (Pull x a)
894− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
896−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
897− { rootSubscribedKey :: !(k a)
898− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
899− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
900− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
901− , rootSubscribedUninit :: IO ()
902− , rootSubscribedWeakSelf :: !(IORef (Weak (RootSubscribed x a))) --TODO: Can we make this a lazy non-IORef and then force it manually to avoid an indirection each time we use it?
904− , rootSubscribedNodeId :: Int
908−data Root x (k :: * -> *)
909− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
910− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
911− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
914−data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
916−data SomeMergeUpdate x = SomeMergeUpdate
917− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
918− , _someMergeUpdate_invalidateHeight :: !(IO ())
919− , _someMergeUpdate_recalculateHeight :: !(IO ())
922−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
924−-- EventM can do everything BehaviorM can, plus create holds
925−newtype EventM x a = EventM { unEventM :: 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
927−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
929−instance Defer (SomeHoldInit x) (ComputeM x) where
930− getDeferralQueue = ComputeM ask
932−{-# INLINABLE runComputeM #-}
933−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
934−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
936−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
938−data HeightBag = HeightBag
939− { _heightBag_size :: {-# UNPACK #-} !Int
940− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
942− deriving (Show, Read, Eq, Ord)
944−heightBagEmpty :: HeightBag
945−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
947−heightBagSize :: HeightBag -> Int
948−heightBagSize = _heightBag_size
950−heightBagFromList :: [Height] -> HeightBag
951−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
953−heightBagAdd :: Height -> HeightBag -> HeightBag
954−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
956−heightBagRemove :: Height -> HeightBag -> HeightBag
957−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
958− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
959− Just old -> HeightBag (pred s) $ case old of
960− 0 -> IntMap.delete h c
961− _ -> IntMap.insert h (pred old) c
963−heightBagMax :: HeightBag -> Height
964−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
965− Just ((h, _), _) -> Height h
966− Nothing -> zeroHeight
968−heightBagVerify :: HeightBag -> HeightBag
970−heightBagVerify b@(HeightBag s c) = if
971− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
972− -> error $ "heightBagVerify: size doesn't match: " <> show b
973− | unHeight invalidHeight `IntMap.member` c
974− -> error $ "heightBagVerify: contains invalid height: " <> show b
980−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
981− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
982− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
983− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
986−data FanSubscribed (x :: *) k
987− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
988− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
989− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
990− , fanSubscribedParent :: !(EventSubscription x)
992− , fanSubscribedNodeId :: Int
997− = Fan { fanParent :: !(Event x (DMap k Identity))
998− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1001−data SwitchSubscribed x a
1002− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1003− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1004− , switchSubscribedHeight :: !(IORef Height)
1005− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1006− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1007− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1008− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1009− , switchSubscribedParent :: !(Behavior x (Event x a))
1010− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1011− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1012−#ifdef DEBUG_NODEIDS
1013− , switchSubscribedNodeId :: Int
1018− = Switch { switchParent :: !(Behavior x (Event x a))
1019− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1022−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1023−data CoincidenceSubscribed x a
1024− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1025− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1026− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1027− , coincidenceSubscribedHeight :: !(IORef Height)
1028− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1029− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1030− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1031− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1032−#ifdef DEBUG_NODEIDS
1033− , coincidenceSubscribedNodeId :: Int
1037−data Coincidence x a
1038− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1039− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1042−{-# NOINLINE newInvalidatorSwitch #-}
1043−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1044−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1046−{-# NOINLINE newInvalidatorPull #-}
1047−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1048−newInvalidatorPull p = return $! InvalidatorPull p
1050−instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1051− fmapMaybe f = push $ return . f
1053−instance HasSpiderTimeline x => Align (Event x) where
1055− align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1057−newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1059−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1060−newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1062−--TODO: Avoid the duplication between this and R.zipDynWith
1063−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1064−zipDynWith f da db =
1065− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1066− ec = flip push eab $ \o -> do
1067− (a, b) <- case o of
1068− This (Identity a) -> do
1069− b <- readBehaviorUntracked $ dynamicCurrent db
1071− That (Identity b) -> do
1072− a <- readBehaviorUntracked $ dynamicCurrent da
1074− These (Identity a) (Identity b) -> return (a, b)
1075− return $ Just $ Identity $ f a b
1076− in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1078−unsafeDyn :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1079−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1080− where x = (readV0, v')
1082−-- ResultM can read behaviors and events
1083−type ResultM = EventM
1085−{-# NOINLINE unsafeNewIORef #-}
1086−unsafeNewIORef :: a -> b -> IORef b
1087−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1089−instance HasSpiderTimeline x => Functor (Event x) where
1090− fmap f = push $ return . Just . f
1092−instance Functor (Behavior x) where
1093− fmap f = pull . fmap f . readBehaviorTracked
1096−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1097−push f e = cacheEvent (pushCheap f e)
1099−{-# INLINABLE pull #-}
1100−pull :: BehaviorM x a -> Behavior x a
1101−pull a = behaviorPull $ Pull
1103− , pullValue = unsafeNewIORef a Nothing
1104−#ifdef DEBUG_NODEIDS
1105− , pullNodeId = unsafeNodeId a
1109−{-# INLINABLE switch #-}
1110−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1111−switch a = eventSwitch $ Switch
1113− , switchSubscribed = unsafeNewIORef a Nothing
1116−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1117−coincidence a = eventCoincidence $ Coincidence
1118− { coincidenceParent = a
1119− , coincidenceSubscribed = unsafeNewIORef a Nothing
1122−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1123−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1124−run roots after = do
1125− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1126− t <- SpiderHost ask
1127− result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1128− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1129− occBefore <- liftIO $ do
1130− occBefore <- readIORef occRef
1131− writeIORef occRef $! DMap.insert k a occBefore
1133− if DMap.null occBefore
1134− then do scheduleRootClear occRef
1136− else return Nothing
1137− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1138− propagate a subscribersRef
1139− delayedRef <- asksEventEnv eventEnvDelayedMerges
1141− delayed <- liftIO $ readIORef delayedRef
1142− case IntMap.minViewWithKey delayed of
1143− Nothing -> return ()
1144− Just ((currentHeight, cur), future) -> do
1145− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1146− putCurrentHeight $ Height currentHeight
1147− liftIO $ writeIORef delayedRef $! future
1151− putCurrentHeight maxBound
1153− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1156−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1157−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1158− height <- liftIO $ readIORef heightRef
1159− currentHeight <- getCurrentHeight
1160− case height `compare` currentHeight of
1161− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1162− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1165−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1167−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1169−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1171−debugFinalize :: Bool
1172−debugFinalize = False
1174−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1175−mkWeakPtrWithDebug x debugNote = do
1179− then Just $ putStrLn $ "finalizing: " ++ debugNote
1182−type WeakList a = [Weak a]
1184−{-# INLINE withIncreasedDepth #-}
1186−withIncreasedDepth :: CanTrace x m => m a -> m a
1187−withIncreasedDepth a = do
1188− spiderTimeline <- askSpiderTimelineEnv
1189− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1191− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1194−withIncreasedDepth :: m a -> m a
1195−withIncreasedDepth = id
1198−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1200−{-# INLINE tracePropagate #-}
1201−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1202−tracePropagate p = traceWhen p debugPropagate
1204−{-# INLINE traceInvalidate #-}
1205−traceInvalidate :: String -> IO ()
1206−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1208−{-# INLINE traceWhen #-}
1209−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1210−traceWhen p b message = traceMWhen p b $ return message
1212−{-# INLINE traceMWhen #-}
1213−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1214−traceMWhen _ b getMessage = when b $ do
1215− message <- getMessage
1217− spiderTimeline <- askSpiderTimelineEnv
1218− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1222− liftIO $ putStrLn $ replicate d ' ' <> message
1224−whoCreatedIORef :: IORef a -> IO [String]
1225−whoCreatedIORef (IORef a) = whoCreated $! a
1228−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1231− (x :| xs) : t -> case groupByHead t of
1232− [] -> [(x, xs :| [])]
1234− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1235− | otherwise -> (x, xs :| []) : l
1237−listsToForest :: Eq a => [[a]] -> Forest a
1238−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1241−{-# INLINE propagateSubscriberHold #-}
1242−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1243−propagateSubscriberHold h a = do
1244− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1245− invalidators <- liftIO $ readIORef $ holdInvalidators h
1246− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1247− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1248− case {-# SCC "apply" #-} apply a v of
1249− Nothing -> return ()
1251− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1252− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1253− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1254− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1256−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1258−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1259−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1261−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1263− (!m, _) <- BehaviorM ask
1265− Nothing -> return Nothing
1266− Just (!wi, _) -> return $ Just wi
1268−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1270− (!m, _) <- BehaviorM ask
1272− Nothing -> return Nothing
1273− Just (_, !p) -> return $ Just p
1275−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1276−askBehaviorHoldInits = do
1277− (_, !his) <- BehaviorM ask
1280−{-# INLINE getDynHold #-}
1281−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1283− mh <- liftIO $ readIORef $ unDyn d
1285− Right h -> return h
1286− Left (readV0, v') -> do
1287− holdInits <- getDeferralQueue
1288− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1290− liftIO $ writeIORef (unDyn d) $ Right h
1293−-- Always refers to 0
1294−{-# NOINLINE zeroRef #-}
1295−zeroRef :: IORef Height
1296−zeroRef = unsafePerformIO $ newIORef zeroHeight
1298−type CanSubscribe x m =
1299− ( HasSpiderTimeline x
1300− , HasCurrentHeight x m
1301− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1302− , Defer SomeClear m -- Wiping out event firings
1303− , Defer (SomeAssignment x) m -- Updating state
1304− , Defer (SomeResetCoincidence x) m
1308−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1309−getRootSubscribed k r sub = do
1310− mSubscribed <- readIORef $ rootSubscribed r
1311− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1312− case DMap.lookup k mSubscribed of
1313− Just subscribed -> {-# SCC "hitRoot" #-} do
1314− sln <- subscribeRootSubscribed subscribed sub
1316− return (sln, subscribed, occ)
1317− Nothing -> {-# SCC "missRoot" #-} do
1318− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1319− let !cached = rootSubscribed r
1320− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1321− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1322− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1323− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1324− writeIORef uninitRef $! uninit
1325− let subscribed = RootSubscribed
1326− { rootSubscribedKey = k
1327− , rootSubscribedCachedSubscribed = cached
1328− , rootSubscribedOccurrence = getOcc
1329− , rootSubscribedSubscribers = subs
1330− , rootSubscribedUninit = uninit
1331− , rootSubscribedWeakSelf = weakSelf
1332−#ifdef DEBUG_NODEIDS
1333− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1336− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1337− 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
1339− return (sln, subscribed, occ)
1341−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1342−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1343−cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1344− rootSubscribedUninit self
1345− modifyIORef' cached $ DMap.delete k
1347−{-# INLINE subscribeRootSubscribed #-}
1348−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1349−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1351−{-# INLINABLE getFanSubscribed #-}
1352−getFanSubscribed :: (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x, GCompare k) => k a -> Fan x k -> Subscriber x a -> m (WeakBagTicket, FanSubscribed x k, Maybe a)
1353−getFanSubscribed k f sub = do
1354− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1355− case mSubscribed of
1356− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1357− sln <- subscribeFanSubscribed k subscribed sub
1358− occ <- readIORef $ fanSubscribedOccurrence subscribed
1359− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1360− Nothing -> {-# SCC "missFan" #-} do
1361− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1362− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1363− s <- liftIO $ newSubscriberFan subscribedUnsafe
1364− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1365− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1366− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1367− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1368− occRef <- liftIO $ newIORef parentOcc
1369− when (isJust parentOcc) $ scheduleClear occRef
1370− let subscribed = FanSubscribed
1371− { fanSubscribedCachedSubscribed = fanSubscribed f
1372− , fanSubscribedOccurrence = occRef
1373− , fanSubscribedParent = subscription
1374− , fanSubscribedSubscribers = subscribersRef
1375−#ifdef DEBUG_NODEIDS
1376− , fanSubscribedNodeId = unsafeNodeId f
1379− let !self = (k, subscribed)
1380− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1381− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1382− liftIO $ writeIORef subscribedRef $! subscribed
1383− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1384− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1386−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1387−cleanupFanSubscribed (k, subscribed) = do
1388− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1389− let reducedSubscribers = DMap.delete k subscribers
1390− if DMap.null reducedSubscribers
1392− unsubscribe $ fanSubscribedParent subscribed
1393− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1394− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1395− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1397−{-# INLINE subscribeFanSubscribed #-}
1398−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1399−subscribeFanSubscribed k subscribed sub = do
1400− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1401− case DMap.lookup k subscribers of
1402− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1403− let !self = (k, subscribed)
1404− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1405− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1406− writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1408− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1410−{-# INLINABLE getSwitchSubscribed #-}
1411−getSwitchSubscribed :: (Defer (SomeHoldInit x) m, Defer (SomeAssignment x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, Defer (SomeResetCoincidence x) m, HasCurrentHeight x m, HasSpiderTimeline x, m ~ EventM x) => Switch x a -> Subscriber x a -> m (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1412−getSwitchSubscribed s sub = do
1413− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1414− case mSubscribed of
1415− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1416− sln <- subscribeSwitchSubscribed subscribed sub
1417− occ <- readIORef $ switchSubscribedOccurrence subscribed
1418− return (sln, subscribed, occ)
1419− Nothing -> {-# SCC "missSwitch" #-} do
1420− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1421− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1422− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1423− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1424− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1425− wiRef <- liftIO $ newIORef wi
1426− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1427− holdInits <- getDeferralQueue
1428− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1429− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1430− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1431− subscriptionRef <- liftIO $ newIORef subscription
1432− occRef <- liftIO $ newIORef parentOcc
1433− when (isJust parentOcc) $ scheduleClear occRef
1434− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1435− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1436− let !subscribed = SwitchSubscribed
1437− { switchSubscribedCachedSubscribed = switchSubscribed s
1438− , switchSubscribedOccurrence = occRef
1439− , switchSubscribedHeight = heightRef
1440− , switchSubscribedSubscribers = subs
1441− , switchSubscribedOwnInvalidator = i
1442− , switchSubscribedOwnWeakInvalidator = wiRef
1443− , switchSubscribedBehaviorParents = parentsRef
1444− , switchSubscribedParent = switchParent s
1445− , switchSubscribedCurrentParent = subscriptionRef
1446− , switchSubscribedWeakSelf = weakSelf
1447−#ifdef DEBUG_NODEIDS
1448− , switchSubscribedNodeId = unsafeNodeId s
1451− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1452− liftIO $ writeIORef subscribedRef $! subscribed
1453− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1454− return (slnForSub, subscribed, parentOcc)
1456−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1457−cleanupSwitchSubscribed subscribed = do
1458− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1459− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1460− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1462−{-# INLINE subscribeSwitchSubscribed #-}
1463−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1464−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1466−{-# INLINABLE getCoincidenceSubscribed #-}
1467−getCoincidenceSubscribed :: forall x a m. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Coincidence x a -> Subscriber x a -> m (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1468−getCoincidenceSubscribed c sub = do
1469− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1470− case mSubscribed of
1471− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1472− sln <- subscribeCoincidenceSubscribed subscribed sub
1473− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1474− return (sln, subscribed, occ)
1475− Nothing -> {-# SCC "missCoincidence" #-} do
1476− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1477− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1478− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1479− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1480− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1481− (occ, height, mInnerSubd) <- case outerOcc of
1482− Nothing -> return (Nothing, outerHeight, Nothing)
1484− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1485− return (occ, height, Just innerSubd)
1486− occRef <- liftIO $ newIORef occ
1487− when (isJust occ) $ scheduleClear occRef
1488− heightRef <- liftIO $ newIORef height
1489− innerSubdRef <- liftIO $ newIORef mInnerSubd
1490− scheduleClear innerSubdRef
1491− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1492− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1493− let subscribed = CoincidenceSubscribed
1494− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1495− , coincidenceSubscribedOccurrence = occRef
1496− , coincidenceSubscribedHeight = heightRef
1497− , coincidenceSubscribedSubscribers = subs
1498− , coincidenceSubscribedOuter = subOuter
1499− , coincidenceSubscribedOuterParent = outerSubscription
1500− , coincidenceSubscribedInnerParent = innerSubdRef
1501− , coincidenceSubscribedWeakSelf = weakSelf
1502−#ifdef DEBUG_NODEIDS
1503− , coincidenceSubscribedNodeId = unsafeNodeId c
1506− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1507− liftIO $ writeIORef subscribedRef $! subscribed
1508− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1509− return (slnForSub, subscribed, occ)
1511−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1512−cleanupCoincidenceSubscribed subscribed = do
1513− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1514− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1516−{-# INLINE subscribeCoincidenceSubscribed #-}
1517−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1518−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1520−{-# INLINE merge #-}
1521−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1522−merge d = cacheEvent (mergeCheap d)
1524−{-# INLINE [1] mergeCheap #-}
1525−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1526−mergeCheap d = Event $ \sub -> do
1527− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1528− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1529− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1530− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1531− parentsRef <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1532− let scheduleSelf height = scheduleMerge' height heightRef $ do
1533− m <- liftIO $ readIORef accumRef
1534− liftIO $ writeIORef accumRef $! DMap.empty
1535− --TODO: Assert that m is not empty
1536− subscriberPropagate sub m
1537− invalidateMyHeight = do
1538− oldHeight <- readIORef heightRef
1539− when (oldHeight /= invalidHeight) $ do -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1540− writeIORef heightRef $! invalidHeight
1541− subscriberInvalidateHeight sub oldHeight
1542− revalidateMyHeight = do
1543− currentHeight <- readIORef heightRef
1544− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1545− heights <- readIORef heightBagRef
1546− parents <- readIORef parentsRef
1547− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1548− case heightBagSize heights `compare` DMap.size parents of
1551− let height = succHeight $ heightBagMax heights
1552− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1553− writeIORef heightRef $! height
1554− subscriberRecalculateHeight sub height
1555− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge"
1556− subscriber :: forall a. k a -> Subscriber x a
1557− subscriber k = Subscriber
1558− { subscriberPropagate = \a -> do
1559− oldM <- liftIO $ readIORef accumRef
1560− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1561− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1562− liftIO $ writeIORef accumRef $! newM
1563− when (DMap.null oldM) $ do -- Only schedule the firing once
1564− height <- liftIO $ readIORef heightRef
1565− --TODO: assertions about height
1566− currentHeight <- getCurrentHeight
1567− when (height <= currentHeight) $ do
1568− if height /= invalidHeight
1570− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1571− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1574− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1575− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1576− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1580− error $ "Causality loop found" <> cycleInfo
1581− scheduleSelf height
1582− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1583− modifyIORef' heightBagRef $ heightBagRemove old
1585− , subscriberRecalculateHeight = \new -> do
1586− modifyIORef' heightBagRef $ heightBagAdd new
1589− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1590− let s = subscriber k
1591− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1592− height <- liftIO $ getEventSubscribedHeight parentSubd
1593− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1594− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1595− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1596− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1597− myHeight = if invalidHeight `elem` heights
1599− else succHeight $ heightBagMax myHeightBag
1600− currentHeight <- getCurrentHeight
1601− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1602− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1604− unless (DMap.null accum) $ do
1605− scheduleSelf myHeight
1606− occRef <- liftIO $ newIORef occ
1607− when (isJust occ) $ scheduleClear occRef
1608− liftIO $ writeIORef accumRef $! accum
1609− liftIO $ writeIORef heightRef $! myHeight
1610− liftIO $ writeIORef heightBagRef $! myHeightBag
1611− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1612− liftIO $ writeIORef parentsRef $! DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1613− let updateMe (PatchDMap p) = do
1614− oldParents <- liftIO $ readIORef parentsRef
1615− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1616− (mOldSubd, newPs) <- case me of
1617− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1619− let s = subscriber k
1620− subscription@(EventSubscription _ subd) <- subscribe e s
1621− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1622− let newParent = MergeSubscribedParent subscription
1623− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1624− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1625− forM_ mOldSubd $ \oldSubd -> do
1626− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1627− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1628− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1629− (subscriptionsToKill, newParents) <- 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
1630− liftIO $ writeIORef parentsRef $! newParents
1631− return subscriptionsToKill
1632− defer $ SomeMergeInit $ do
1634− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1635− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1636− defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1637− , subscriberInvalidateHeight = \_ -> return ()
1638− , subscriberRecalculateHeight = \_ -> return ()
1640− (EventSubscription _ changeSubd, change) <- subscribeAndRead (dynamicUpdated d) s
1641− forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1642− liftIO $ writeIORef changeSubdRef (s, changeSubd)
1643− let unsubscribeAll = do
1644− parents <- readIORef parentsRef
1645− forM_ (DMap.toList parents) $ \(_ :=> MergeSubscribedParent s) -> unsubscribe s
1646− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1650−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1652−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1656− , fanSubscribed = unsafeNewIORef e Nothing
1658− in EventSelector $ \k -> eventFan k f
1660−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1661−runHoldInits holdInitRef mergeInitRef = do
1662− holdInits <- liftIO $ readIORef holdInitRef
1663− mergeInits <- liftIO $ readIORef mergeInitRef
1664− unless (null holdInits && null mergeInits) $ do
1665− liftIO $ writeIORef holdInitRef []
1666− liftIO $ writeIORef mergeInitRef []
1667− mapM_ initHold holdInits
1668− mapM_ unSomeMergeInit mergeInits
1669− runHoldInits holdInitRef mergeInitRef
1671−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1672−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1674−newEventEnv :: IO (EventEnv x)
1676− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1677− holdInitRef <- newIORef []
1678− mergeUpdateRef <- newIORef []
1679− mergeInitRef <- newIORef []
1680− heightRef <- newIORef zeroHeight
1681− toClearRef <- newIORef []
1682− toClearRootRef <- newIORef []
1683− coincidenceInfosRef <- newIORef []
1684− delayedRef <- newIORef IntMap.empty
1685− return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1687−clearEventEnv :: EventEnv x -> IO ()
1688−clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1689− writeIORef toAssignRef []
1690− writeIORef holdInitRef []
1691− writeIORef mergeUpdateRef []
1692− writeIORef mergeInitRef []
1693− writeIORef heightRef zeroHeight
1694− writeIORef toClearRef []
1695− writeIORef toClearRootRef []
1696− writeIORef coincidenceInfosRef []
1697− writeIORef delayedRef IntMap.empty
1699−-- | Run an event action outside of a frame
1700−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1701−runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
1702− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
1705− runHoldInits (eventEnvHoldInits env) (eventEnvMergeInits env) -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1707− result <- runEventM go
1708− toClear <- readIORef $ eventEnvClears env
1709− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1710− toClearRoot <- readIORef $ eventEnvRootClears env
1711− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1712− toAssign <- readIORef $ eventEnvAssignments env
1713− toReconnectRef <- newIORef []
1714− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1715− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1717− when debugInvalidate $ putStrLn $ "Invalidating Hold"
1718− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1719− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1720− writeIORef (eventEnvMergeUpdates env) []
1721− when debugPropagate $ putStrLn "Updating merges"
1722− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1723− when debugPropagate $ putStrLn "Updating merges done"
1724− toReconnect <- readIORef toReconnectRef
1726− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1727− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1728− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1729− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1731− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1732− wi' <- mkWeakPtrWithDebug i "wi'"
1733− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1734− writeIORef (switchSubscribedBehaviorParents subscribed) []
1735− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1736− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1737− runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvMergeInits 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
1738− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1739− sub <- newSubscriberSwitch subscribed
1740− subscription <- runReaderT (unSpiderHost (runFrame ({-# SCC "subscribeSwitch" #-} subscribe e sub))) spiderTimeline --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
1742− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1743− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1744− EventRoot _ -> "EventRoot"
1745− EventNever -> "EventNever"
1746− _ -> "something else"
1748− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1749− return oldSubscription
1750− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1751− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1752− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1753− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1754− parentHeight <- getEventSubscribedHeight subd'
1755− myHeight <- readIORef $ switchSubscribedHeight subscribed
1756− when (parentHeight /= myHeight) $ do
1757− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1758− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1759− mapM_ _someMergeUpdate_invalidateHeight mergeUpdates --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
1760− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1761− unsubscribe subscription
1762− mapM_ invalidateCoincidenceHeight mcs
1763− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1764− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1765− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1766− height <- calculateSwitchHeight subscribed
1767− updateSwitchHeight height subscribed
1770−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1772−{-# INLINE zeroHeight #-}
1773−zeroHeight :: Height
1774−zeroHeight = Height 0
1776−{-# INLINE invalidHeight #-}
1777−invalidHeight :: Height
1778−invalidHeight = Height (-1000)
1781−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1782−{-# INLINE invalidHeightBeingTraversed #-}
1783−invalidHeightBeingTraversed :: Height
1784−invalidHeightBeingTraversed = Height (-1001)
1787−{-# INLINE succHeight #-}
1788−succHeight :: Height -> Height
1789−succHeight h@(Height a) =
1790− if h == invalidHeight
1792− else Height $ succ a
1794−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1795−invalidateCoincidenceHeight subscribed = do
1796− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1797− when (oldHeight /= invalidHeight) $ do
1798− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1799− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1801−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1802−updateSwitchHeight new subscribed = do
1803− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1804− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1805− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1806− writeIORef (switchSubscribedHeight subscribed) $! new
1807− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1809−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1810−recalculateCoincidenceHeight subscribed = do
1811− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1812− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1813− height <- calculateCoincidenceHeight subscribed
1814− when (height /= invalidHeight) $ do
1815− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1816− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1818−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1819−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1821−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1822−calculateCoincidenceHeight subscribed = do
1823− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1824− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1825− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1827−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1829−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1830−invalidate toReconnectRef wis = do
1831− forM_ wis $ \wi -> do
1835− traceInvalidate "invalidate Dead"
1836− return () --TODO: Should we clean this up here?
1838− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1840− InvalidatorPull p -> do
1841− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1842− mVal <- readIORef $ pullValue p
1843− forM_ mVal $ \val -> do
1844− writeIORef (pullValue p) Nothing
1845− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1846− InvalidatorSwitch subscribed -> do
1847− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1848− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1849− 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
1851−--------------------------------------------------------------------------------
1852−-- Reflex integration
1853−--------------------------------------------------------------------------------
1855−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1856−-- When we're specializing, we include this from Reflex.Class instead, because
1857−-- it needs access to these types; when we're not, we want them here, so our
1858−-- instance isn't an orphan instance.
1859−#include "SpiderTimeline.include.hs"
1860−#include "SpiderTimelineHost.include.hs"
1863−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
1864−unsafeNewSpiderTimelineEnv = do
1868− depthRef <- newIORef 0
1870− return $ SpiderTimelineEnv
1871− { _spiderTimeline_lock = lock
1872− , _spiderTimeline_eventEnv = env
1874− , _spiderTimeline_depth = depthRef
1878−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1879−-- | Create a new SpiderTimelineEnv
1880−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
1881−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
1883−data LocalSpiderTimeline x s
1885−instance Reifies s (SpiderTimelineEnv x) =>
1886− HasSpiderTimeline (LocalSpiderTimeline x s) where
1887− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
1891− -> SpiderTimelineEnv x
1892− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
1893−localSpiderTimeline _ = unsafeCoerce
1895−-- | Pass a new timeline to the given function.
1896−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
1897−withSpiderTimeline k = do
1898− env <- unsafeNewSpiderTimelineEnv
1899− reify env $ \s -> k $ localSpiderTimeline s env
1902−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1904−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1906−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1907−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
1908− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
1909− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
1910− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
1911− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
1912− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
1913− type PullM (SpiderTimeline x) = SpiderPullM x
1914− type PushM (SpiderTimeline x) = SpiderPushM x
1915− {-# INLINABLE never #-}
1916− never = SpiderEvent eventNever
1917− {-# INLINABLE constant #-}
1918− constant = SpiderBehavior . behaviorConst
1919− {-# INLINE push #-}
1920− push f = SpiderEvent . push (coerce f) . unSpiderEvent
1921− {-# INLINABLE pull #-}
1922− pull = SpiderBehavior . pull . coerce
1923− {-# INLINABLE merge #-}
1924− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
1925− {-# INLINABLE fan #-}
1926− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1927− {-# INLINABLE switch #-}
1928− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
1929− {-# INLINABLE coincidence #-}
1930− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
1931− {-# INLINABLE current #-}
1932− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
1933− {-# INLINABLE updated #-}
1934− updated = SpiderEvent . fmap runIdentity . dynamicUpdated . unSpiderDynamic
1935− {-# INLINABLE unsafeBuildDynamic #-}
1936− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
1937− {-# INLINABLE unsafeBuildIncremental #-}
1938− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
1939− {-# INLINABLE mergeIncremental #-}
1940− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
1941− {-# INLINABLE currentIncremental #-}
1942− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
1943− {-# INLINABLE updatedIncremental #-}
1944− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
1945− {-# INLINABLE incrementalToDynamic #-}
1946− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
1947− c <- readBehaviorUntracked $ dynamicCurrent i
1948− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
1949− eventCoercion Coercion = Coercion
1950− behaviorCoercion Coercion = Coercion
1951− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
1954−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
1956−data SpiderEventHandle x a = SpiderEventHandle
1957− { spiderEventHandleSubscription :: EventSubscription x
1958− , spiderEventHandleValue :: IORef (Maybe a)
1961−instance MonadRef (EventM x) where
1962− type Ref (EventM x) = Ref IO
1963− {-# INLINABLE newRef #-}
1964− {-# INLINABLE readRef #-}
1965− {-# INLINABLE writeRef #-}
1966− newRef = liftIO . newRef
1967− readRef = liftIO . readRef
1968− writeRef r a = liftIO $ writeRef r a
1970−instance MonadAtomicRef (EventM x) where
1971− {-# INLINABLE atomicModifyRef #-}
1972− atomicModifyRef r f = liftIO $ atomicModifyRef r f
1974−-- | The monad for actions that manipulate a Spider timeline identified by @x@
1975−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
1977−instance Monad (SpiderHost x) where
1978− {-# INLINABLE (>>=) #-}
1979− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
1980− {-# INLINABLE (>>) #-}
1981− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
1982− {-# INLINABLE return #-}
1983− return x = SpiderHost $ return x
1984− {-# INLINABLE fail #-}
1985− fail s = SpiderHost $ fail s
1987−-- | Run an action affecting the global Spider timeline; this will be guarded by
1988−-- a mutex for that timeline
1989−runSpiderHost :: SpiderHost Global a -> IO a
1990−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
1992−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1993−-- | Run an action affecting a given Spider timeline; this will be guarded by a
1994−-- mutex for that timeline
1995−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
1996−runSpiderHostForTimeline (SpiderHost a) = runReaderT a
1999−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2001−instance Monad (SpiderHostFrame x) where
2002− {-# INLINABLE (>>=) #-}
2003− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2004− {-# INLINABLE (>>) #-}
2005− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2006− {-# INLINABLE return #-}
2007− return x = SpiderHostFrame $ return x
2008− {-# INLINABLE fail #-}
2009− fail s = SpiderHostFrame $ fail s
2011−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2012−newEventWithTriggerIO f = do
2013− es <- newFanEventWithTriggerIO $ \Refl -> f
2014− return $ select es Refl
2016−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2017−newFanEventWithTriggerIO f = do
2018− occRef <- newIORef DMap.empty
2019− subscribedRef <- newIORef DMap.empty
2021− { rootOccurrence = occRef
2022− , rootSubscribed = subscribedRef
2025− return $ EventSelector $ \k -> eventRoot k r
2027−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2029−instance MonadRef (SpiderHost x) where
2030− type Ref (SpiderHost x) = Ref IO
2031− newRef = SpiderHost . newRef
2032− readRef = SpiderHost . readRef
2033− writeRef r = SpiderHost . writeRef r
2035−instance MonadAtomicRef (SpiderHost x) where
2036− atomicModifyRef r = SpiderHost . atomicModifyRef r
2038−instance MonadRef (SpiderHostFrame x) where
2039− type Ref (SpiderHostFrame x) = Ref IO
2040− newRef = SpiderHostFrame . newRef
2041− readRef = SpiderHostFrame . readRef
2042− writeRef r = SpiderHostFrame . writeRef r
2044−instance MonadAtomicRef (SpiderHostFrame x) where
2045− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2047−instance PrimMonad (SpiderHostFrame x) where
2048− type PrimState (SpiderHostFrame x) = PrimState IO
2049− primitive = SpiderHostFrame . EventM . primitive