@@ -0,0 +1,2460 @@
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 (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
60+import Data.FastMutableIntMap (FastMutableIntMap, PatchIntMap (..))
61+import qualified Data.FastMutableIntMap as FastMutableIntMap
63+import GHC.IORef (IORef (..))
65+import Reflex.FastWeak
66+import Reflex.FunctorMaybe
67+import System.IO.Unsafe
68+import System.Mem.Weak
72+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
73+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
74+import qualified Data.List.NonEmpty as NonEmpty
75+import Data.Monoid (mempty)
76+import Data.Tree (Forest, Tree (..), drawForest)
79+import Data.FastWeakBag (FastWeakBag)
80+import qualified Data.FastWeakBag as FastWeakBag
81+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
82+import qualified Data.WeakBag as WeakBag
83+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
84+import Data.Reflection
85+import Data.Some (Some)
86+import qualified Data.Some as Some
87+import Data.Type.Coercion
88+import qualified Reflex.Class
89+import qualified Reflex.Class as R
90+import qualified Reflex.Host.Class
93+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
95+-- Note: must come last to silence warnings due to AMP on GHC < 7.10
96+import Prelude hiding (any, concat, mapM, mapM_, sequence)
98+#ifdef DEBUG_TRACE_EVENTS
99+import System.IO (stderr)
100+import qualified Data.ByteString.Char8 as BS8
103+#ifdef DEBUG_TRACE_EVENTS
105+withStackOneLine :: (BS8.ByteString -> a) -> a
106+withStackOneLine expr = unsafePerformIO $ do
107+ stack <- currentCallStack
108+ return (expr (BS8.pack (unwords (reverse stack))))
112+debugPropagate :: Bool
114+debugInvalidateHeight :: Bool
116+debugInvalidate :: Bool
120+#define DEBUG_NODEIDS
122+debugPropagate = True
124+debugInvalidateHeight = False
126+debugInvalidate = True
128+class HasNodeId a where
129+ getNodeId :: a -> Int
131+instance HasNodeId (Hold x p a) where
132+ getNodeId = holdNodeId
134+instance HasNodeId (PushSubscribed x a b) where
135+ getNodeId = pushSubscribedNodeId
137+instance HasNodeId (SwitchSubscribed x a) where
138+ getNodeId = switchSubscribedNodeId
140+instance HasNodeId (FanSubscribed x a) where
141+ getNodeId = fanSubscribedNodeId
143+instance HasNodeId (CoincidenceSubscribed x a) where
144+ getNodeId = coincidenceSubscribedNodeId
146+instance HasNodeId (RootSubscribed x a) where
147+ getNodeId = rootSubscribedNodeId
149+instance HasNodeId (Pull x a) where
150+ getNodeId = pullNodeId
152+{-# INLINE showNodeId #-}
153+showNodeId :: HasNodeId a => a -> String
154+showNodeId = ("#"<>) . show . getNodeId
156+showSubscriberType :: Subscriber x a -> String
157+showSubscriberType = \case
158+ SubscriberPush _ _ -> "SubscriberPush"
159+ SubscriberMerge _ _ -> "SubscriberMerge"
160+ SubscriberFan _ -> "SubscriberFan"
161+ SubscriberMergeChange _ -> "SubscriberMergeChange"
162+ SubscriberHold _ -> "SubscriberHold"
163+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
164+ SubscriberSwitch _ -> "SubscriberSwitch"
165+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
166+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
167+ SubscriberHandle -> "SubscriberHandle"
169+showEventType :: Event x a -> String
170+showEventType = \case
171+ EventRoot _ _ -> "EventRoot"
172+ EventNever -> "EventNever"
173+ EventPush _ -> "EventPush"
174+ EventMerge _ -> "EventMerge"
175+ EventFan _ _ -> "EventFan"
176+ EventSwitch _ -> "EventSwitch"
177+ EventCoincidence _ -> "EventCoincidence"
178+ EventHold _ -> "EventHold"
179+ EventDyn _ -> "EventDyn"
180+ EventHoldIdentity _ -> "EventHoldIdentity"
181+ EventDynIdentity _ -> "EventDynIdentity"
185+debugPropagate = False
187+debugInvalidateHeight = False
189+debugInvalidate = False
191+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
192+{-# INLINE showNodeId #-}
193+showNodeId :: a -> String
199+{-# NOINLINE nextNodeIdRef #-}
200+nextNodeIdRef :: IORef Int
201+nextNodeIdRef = unsafePerformIO $ newIORef 1
204+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
206+{-# NOINLINE unsafeNodeId #-}
207+unsafeNodeId :: a -> Int
208+unsafeNodeId a = unsafePerformIO $ do
213+--------------------------------------------------------------------------------
215+--------------------------------------------------------------------------------
217+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
218+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
219+data EventSubscription x = EventSubscription
220+ { _eventSubscription_unsubscribe :: !(IO ())
221+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
224+unsubscribe :: EventSubscription x -> IO ()
225+unsubscribe (EventSubscription u _) = u
227+--------------------------------------------------------------------------------
229+--------------------------------------------------------------------------------
231+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
233+{-# INLINE subscribeAndRead #-}
234+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
235+subscribeAndRead = unEvent
238+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
239+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
240+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
243+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
244+-- caching; if the computation function is very cheap, this is (much) more
245+-- efficient than 'push'
246+{-# INLINE [1] pushCheap #-}
247+pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
248+pushCheap !f e = Event $ \sub -> do
249+ (subscription, occ) <- subscribeAndRead e $ sub
250+ { subscriberPropagate = \a -> do
252+ mapM_ (subscriberPropagate sub) mb
254+ occ' <- join <$> mapM f occ
255+ return (subscription, occ')
257+-- | A subscriber that never triggers other 'Event's
258+{-# INLINE terminalSubscriber #-}
259+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a
260+terminalSubscriber p = Subscriber
261+ { subscriberPropagate = p
262+ , subscriberInvalidateHeight = \_ -> return ()
263+ , subscriberRecalculateHeight = \_ -> return ()
266+-- | Subscribe to an Event only for the duration of one occurrence
267+{-# INLINE subscribeAndReadHead #-}
268+subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
269+subscribeAndReadHead e sub = do
270+ subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"
271+ (subscription, occ) <- subscribeAndRead e $ sub
272+ { subscriberPropagate = \a -> do
273+ liftIO $ unsubscribe =<< readIORef subscriptionRef
274+ subscriberPropagate sub a
276+ liftIO $ case occ of
277+ Nothing -> writeIORef subscriptionRef $! subscription
278+ Just _ -> unsubscribe subscription
279+ return (subscription, occ)
281+--TODO: Make this lazy in its input event
282+headE :: (MonadIO m, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
284+ parent <- liftIO $ newIORef $ Just originalE
285+ defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately
286+ let clearParent = liftIO $ writeIORef parent Nothing
287+ (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ \_ -> clearParent
288+ when (isJust occ) clearParent
289+ return $ Event $ \sub -> do
290+ liftIO (readIORef parent) >>= \case
291+ Nothing -> return (EventSubscription (return ()) $ EventSubscribed zeroRef $ toAny (), Nothing)
292+ Just e -> subscribeAndReadHead e sub
294+data CacheSubscribed x a
295+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))
296+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
297+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
300+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
303+--TODO: Try a caching strategy where we subscribe directly to the parent when
304+--there's only one subscriber, and then build our own FastWeakBag only when a second
306+{-# NOINLINE [0] cacheEvent #-}
307+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a
309+#ifdef DEBUG_TRACE_EVENTS
310+ withStackOneLine $ \callSite -> Event $
314+ let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
315+ !mSubscribedRef = unsafeNewIORef e emptyFastWeak
316+ in \sub -> {-# SCC "cacheEvent" #-} do
317+#ifdef DEBUG_TRACE_EVENTS
318+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
320+ subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case
321+ Just subscribedTicket -> return subscribedTicket
323+ subscribers <- liftIO FastWeakBag.empty
324+ occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below
325+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
326+ { subscriberPropagate = \a -> do
327+ liftIO $ writeIORef occRef $ Just a
328+ scheduleClear occRef
329+ propagateFast a subscribers
330+ , subscriberInvalidateHeight = \old -> do
331+ FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
332+ , subscriberRecalculateHeight = \new -> do
333+ FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
335+ when (isJust occ) $ do
336+ liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
337+ scheduleClear occRef
338+ let !subscribed = CacheSubscribed
339+ { _cacheSubscribed_subscribers = subscribers
340+ , _cacheSubscribed_parent = parentSub
341+ , _cacheSubscribed_occurrence = occRef
343+ subscribedTicket <- liftIO $ mkFastWeakTicket subscribed
344+ liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket
345+ return subscribedTicket
347+ subscribed <- getFastWeakTicketValue subscribedTicket
348+ ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed
349+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
350+ let es = EventSubscription
351+ { _eventSubscription_unsubscribe = do
352+ FastWeakBag.remove ticket
353+ isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed
355+ writeIORef mSubscribedRef emptyFastWeak
356+ unsubscribe $ _cacheSubscribed_parent subscribed
358+ touch subscribedTicket
359+ , _eventSubscription_subscribed = EventSubscribed
360+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
361+ , eventSubscribedRetained = toAny subscribedTicket
366+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
367+subscribe e s = fst <$> subscribeAndRead e s
370+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
371+wrap tag getSpecificSubscribed sub = do
372+ (sln, subd, occ) <- getSpecificSubscribed sub
374+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
376+eventRoot :: GCompare k => k a -> Root x k -> Event x a
377+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
379+eventNever :: Event x a
380+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
382+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
383+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
385+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
386+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
388+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
389+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
391+eventHold :: HasSpiderTimeline x => Hold x p -> Event x p
392+eventHold !h = Event $ subscribeHoldEvent h
394+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
395+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
397+{-# INLINE subscribeCoincidenceInner #-}
398+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
399+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
400+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
401+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
402+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
403+ let height = max innerHeight outerHeight
404+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
405+ return (innerOcc, height, innerSubd)
407+--------------------------------------------------------------------------------
409+--------------------------------------------------------------------------------
411+data Subscriber x a = Subscriber
412+ { subscriberPropagate :: !(a -> EventM x ())
413+ , subscriberInvalidateHeight :: !(Height -> IO ())
414+ , subscriberRecalculateHeight :: !(Height -> IO ())
417+--TODO: Move this comment to WeakBag
418+-- These function are constructor functions that are marked NOINLINE so they are
419+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
420+-- so any weak references that are attached to the constructors will have their
421+-- finalizer run. Using the opaque constructor, does not see the
422+-- constructor application, so it behaves like an IORef and cannot be fused away.
424+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
425+-- the weak pointer to it in some cases.
427+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
428+newSubscriberHold h = return $ Subscriber
429+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
430+ , subscriberInvalidateHeight = \_ -> return ()
431+ , subscriberRecalculateHeight = \_ -> return ()
434+newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
435+newSubscriberFan subscribed = return $ Subscriber
436+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
437+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
438+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
439+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
440+ scheduleClear $ fanSubscribedOccurrence subscribed
441+ let f _ (Pair (Identity v) subsubs) = do
442+ propagate v $ _fanSubscribedChildren_list subsubs
443+ return $ Constant ()
444+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
446+ , subscriberInvalidateHeight = \old -> do
447+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
448+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
449+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
450+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
451+ , subscriberRecalculateHeight = \new -> do
452+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
453+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
454+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
455+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
458+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
459+newSubscriberSwitch subscribed = return $ Subscriber
460+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
461+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
462+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
463+ scheduleClear $ switchSubscribedOccurrence subscribed
464+ propagate a $ switchSubscribedSubscribers subscribed
465+ , subscriberInvalidateHeight = \_ -> do
466+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
467+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
468+ when (oldHeight /= invalidHeight) $ do
469+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
470+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
471+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
472+ , subscriberRecalculateHeight = \new -> do
473+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
474+ updateSwitchHeight new subscribed
475+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
478+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
479+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
480+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
481+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
482+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
483+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
484+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
485+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
486+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
487+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
488+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
491+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
492+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
493+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
494+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
495+ Just o -> do -- Since it's already firing, no need to adjust height
496+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
497+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
498+ propagate o $ coincidenceSubscribedSubscribers subscribed
499+ , subscriberInvalidateHeight = \_ -> do
500+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
501+ invalidateCoincidenceHeight subscribed
502+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
503+ , subscriberRecalculateHeight = \_ -> do
504+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
505+ recalculateCoincidenceHeight subscribed
506+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
509+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
510+newSubscriberCoincidenceInner subscribed = return $ Subscriber
511+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
512+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
513+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
515+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
517+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
518+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
519+ propagate a $ coincidenceSubscribedSubscribers subscribed
520+ , subscriberInvalidateHeight = \_ -> do
521+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
522+ invalidateCoincidenceHeight subscribed
523+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
524+ , subscriberRecalculateHeight = \_ -> do
525+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
526+ recalculateCoincidenceHeight subscribed
527+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
530+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
531+invalidateSubscriberHeight = flip subscriberInvalidateHeight
533+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
534+recalculateSubscriberHeight = flip subscriberRecalculateHeight
536+-- | Propagate everything at the current height
537+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
538+propagate a subscribers = withIncreasedDepth $ do
539+ -- 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
540+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
541+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
543+-- | Propagate everything at the current height
544+propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
545+propagateFast a subscribers = withIncreasedDepth $ do
546+ -- 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
547+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
548+ FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
550+--------------------------------------------------------------------------------
552+--------------------------------------------------------------------------------
557+data EventSubscribed x = EventSubscribed
558+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
559+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
561+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
562+ , eventSubscribedHasOwnHeightRef :: !Bool
563+ , eventSubscribedWhoCreated :: !(IO [String])
567+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
568+eventSubscribedRoot !r = EventSubscribed
569+ { eventSubscribedHeightRef = zeroRef
570+ , eventSubscribedRetained = toAny r
572+ , eventSubscribedGetParents = return []
573+ , eventSubscribedHasOwnHeightRef = False
574+ , eventSubscribedWhoCreated = return ["root"]
578+eventSubscribedNever :: EventSubscribed x
579+eventSubscribedNever = EventSubscribed
580+ { eventSubscribedHeightRef = zeroRef
581+ , eventSubscribedRetained = toAny ()
583+ , eventSubscribedGetParents = return []
584+ , eventSubscribedHasOwnHeightRef = False
585+ , eventSubscribedWhoCreated = return ["never"]
589+eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
590+eventSubscribedFan !subscribed = EventSubscribed
591+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
592+ , eventSubscribedRetained = toAny subscribed
594+ , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
595+ , eventSubscribedHasOwnHeightRef = False
596+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
600+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
601+eventSubscribedSwitch !subscribed = EventSubscribed
602+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
603+ , eventSubscribedRetained = toAny subscribed
605+ , eventSubscribedGetParents = do
606+ s <- readIORef $ switchSubscribedCurrentParent subscribed
607+ return [Some.This $ _eventSubscription_subscribed s]
608+ , eventSubscribedHasOwnHeightRef = True
609+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
613+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
614+eventSubscribedCoincidence !subscribed = EventSubscribed
615+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
616+ , eventSubscribedRetained = toAny subscribed
618+ , eventSubscribedGetParents = do
619+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
620+ let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
621+ innerParents = maybeToList $ fmap Some.This innerSubscription
622+ return $ outerParent : innerParents
623+ , eventSubscribedHasOwnHeightRef = True
624+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
628+getEventSubscribedHeight :: EventSubscribed x -> IO Height
629+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
632+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
633+whoCreatedEventSubscribed = eventSubscribedWhoCreated
635+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
636+walkInvalidHeightParents s0 = do
637+ subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
638+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
639+ when (h == invalidHeight) $ do
640+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
641+ modify (Some.This s :)
642+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
643+ forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
647+{-# INLINE subscribeHoldEvent #-}
648+subscribeHoldEvent :: HasSpiderTimeline x => Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
649+subscribeHoldEvent = subscribeAndRead . holdEvent
651+--------------------------------------------------------------------------------
653+--------------------------------------------------------------------------------
655+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
657+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
658+behaviorHold !h = Behavior $ readHoldTracked h
660+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
661+behaviorHoldIdentity = behaviorHold
663+behaviorConst :: a -> Behavior x a
664+behaviorConst !a = Behavior $ return a
666+behaviorPull :: Pull x a -> Behavior x a
667+behaviorPull !p = Behavior $ do
668+ val <- liftIO $ readIORef $ pullValue p
670+ Just subscribed -> do
671+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
672+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
673+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
674+ return $ pullSubscribedValue subscribed
676+ i <- liftIO $ newInvalidatorPull p
677+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
678+ parentsRef <- liftIO $ newIORef []
679+ holdInits <- askBehaviorHoldInits
680+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
681+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
682+ parents <- liftIO $ readIORef parentsRef
683+ let subscribed = PullSubscribed
684+ { pullSubscribedValue = a
685+ , pullSubscribedInvalidators = invsRef
686+ , pullSubscribedOwnInvalidator = i
687+ , pullSubscribedParents = parents
689+ liftIO $ writeIORef (pullValue p) $ Just subscribed
690+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
693+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
694+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
696+{-# INLINE readHoldTracked #-}
697+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
698+readHoldTracked h = do
699+ result <- liftIO $ readIORef $ holdValue h
700+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
701+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
702+ liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
705+{-# INLINABLE readBehaviorUntracked #-}
706+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
707+readBehaviorUntracked b = do
708+ holdInits <- getDeferralQueue
709+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
711+--------------------------------------------------------------------------------
713+--------------------------------------------------------------------------------
715+data Dynamic x p = Dynamic
716+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
717+ , dynamicUpdated :: !(Event x p)
720+dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
721+dynamicHold !h = Dynamic
722+ { dynamicCurrent = behaviorHold h
723+ , dynamicUpdated = eventHold h
726+dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
727+dynamicHoldIdentity = dynamicHold
729+dynamicConst :: PatchTarget p -> Dynamic x p
730+dynamicConst !a = Dynamic
731+ { dynamicCurrent = behaviorConst a
732+ , dynamicUpdated = eventNever
735+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
736+dynamicDyn !d = Dynamic
737+ { dynamicCurrent = behaviorDyn d
738+ , dynamicUpdated = eventDyn d
741+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
742+dynamicDynIdentity = dynamicDyn
744+--------------------------------------------------------------------------------
746+--------------------------------------------------------------------------------
748+--TODO: Figure out why certain things are not 'representational', then make them
749+--representational so we can use coerce
751+--type role Hold representational
753+ = Hold { holdValue :: !(IORef (PatchTarget p))
754+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
755+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
756+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
762+-- | A statically allocated 'SpiderTimeline'; this is the only instance of
763+-- 'SpiderTimeline' that can used when using
764+-- -fspecialize-to-spidertimeline-global.
767+{-# NOINLINE globalSpiderTimelineEnv #-}
768+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
769+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
771+-- | Stores all global data relevant to a particular Spider timeline; only one
772+-- value should exist for each type @x@
773+data SpiderTimelineEnv x = SpiderTimelineEnv
774+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
775+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
777+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
780+type role SpiderTimelineEnv nominal
782+instance Eq (SpiderTimelineEnv x) where
783+ _ == _ = True -- Since only one exists of each type
785+instance GEq SpiderTimelineEnv where
786+#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
788+ geqUnify (a :: SpiderTimelineEnv a) (b :: SpiderTimelineEnv b) different same = if _spiderTimeline_lock a == _spiderTimeline_lock b
789+ then case unsafeCoerce Refl :: a :~: b of
790+ Refl -> same -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
793+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
794+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
799+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
800+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
801+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
802+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
803+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
804+ , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
805+ , eventEnvIntClears :: !(IORef [SomeIntClear])
806+ , eventEnvRootClears :: !(IORef [SomeRootClear])
807+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
808+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
809+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
812+{-# INLINE runEventM #-}
813+runEventM :: EventM x a -> IO a
816+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
817+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
819+class MonadIO m => Defer a m where
820+ getDeferralQueue :: m (IORef [a])
823+defer :: Defer a m => a -> m ()
825+ q <- getDeferralQueue
826+ liftIO $ modifyIORef' q (a:)
828+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
829+ {-# INLINE getDeferralQueue #-}
830+ getDeferralQueue = asksEventEnv eventEnvAssignments
832+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
833+ {-# INLINE getDeferralQueue #-}
834+ getDeferralQueue = asksEventEnv eventEnvHoldInits
836+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
837+ {-# INLINE getDeferralQueue #-}
838+ getDeferralQueue = asksEventEnv eventEnvDynInits
840+instance Defer (SomeHoldInit x) (BehaviorM x) where
841+ {-# INLINE getDeferralQueue #-}
842+ getDeferralQueue = BehaviorM $ asks snd
844+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
845+ {-# INLINE getDeferralQueue #-}
846+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
848+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
849+ {-# INLINE getDeferralQueue #-}
850+ getDeferralQueue = asksEventEnv eventEnvMergeInits
852+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
853+ getCurrentHeight :: m Height
854+ scheduleMerge :: Height -> EventM x () -> m ()
856+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
857+ {-# INLINE getCurrentHeight #-}
858+ getCurrentHeight = do
859+ heightRef <- asksEventEnv eventEnvCurrentHeight
860+ liftIO $ readIORef heightRef
861+ {-# INLINE scheduleMerge #-}
862+ scheduleMerge height subscribed = do
863+ delayedRef <- asksEventEnv eventEnvDelayedMerges
864+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
866+#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
867+class x ~ Global => HasSpiderTimeline x where
869+class HasSpiderTimeline x where
871+ -- | Retrieve the current SpiderTimelineEnv
872+ spiderTimeline :: SpiderTimelineEnv x
874+instance HasSpiderTimeline Global where
875+ spiderTimeline = globalSpiderTimelineEnv
877+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
878+putCurrentHeight h = do
879+ heightRef <- asksEventEnv eventEnvCurrentHeight
880+ liftIO $ writeIORef heightRef $! h
882+instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
883+ {-# INLINE getDeferralQueue #-}
884+ getDeferralQueue = asksEventEnv eventEnvClears
886+{-# INLINE scheduleClear #-}
887+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
888+scheduleClear r = defer $ SomeClear r
890+instance HasSpiderTimeline x => Defer SomeIntClear (EventM x) where
891+ {-# INLINE getDeferralQueue #-}
892+ getDeferralQueue = asksEventEnv eventEnvIntClears
894+{-# INLINE scheduleIntClear #-}
895+scheduleIntClear :: Defer SomeIntClear m => IORef (IntMap a) -> m ()
896+scheduleIntClear r = defer $ SomeIntClear r
898+instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
899+ {-# INLINE getDeferralQueue #-}
900+ getDeferralQueue = asksEventEnv eventEnvRootClears
902+{-# INLINE scheduleRootClear #-}
903+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
904+scheduleRootClear r = defer $ SomeRootClear r
906+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
907+ {-# INLINE getDeferralQueue #-}
908+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
910+-- Note: hold cannot examine its event until after the phase is over
911+{-# INLINE [1] hold #-}
912+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
914+ valRef <- liftIO $ newIORef v0
915+ invsRef <- liftIO $ newIORef []
916+ parentRef <- liftIO $ newIORef Nothing
918+ nodeId <- liftIO newNodeId
921+ { holdValue = valRef
922+ , holdInvalidators = invsRef
924+ , holdParent = parentRef
926+ , holdNodeId = nodeId
929+ defer $ SomeHoldInit h
932+{-# INLINE getHoldEventSubscription #-}
933+getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
934+getHoldEventSubscription h = do
935+ ep <- liftIO $ readIORef $ holdParent h
937+ Just subd -> return subd
940+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
941+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
942+ liftIO $ writeIORef subscriptionRef $! subscription
944+ Nothing -> return ()
946+ old <- liftIO $ readIORef $ holdValue h
948+ Nothing -> return ()
950+ -- Need to evaluate these so that we don't retain the Hold itself
951+ v <- liftIO $ evaluate $ holdValue h
952+ i <- liftIO $ evaluate $ holdInvalidators h
953+ defer $ SomeAssignment v i new
954+ liftIO $ writeIORef (holdParent h) $ Just subscription
957+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
959+--type role BehaviorM representational
960+-- BehaviorM can sample behaviors
961+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
963+instance Monad (BehaviorM x) where
964+ {-# INLINE (>>=) #-}
965+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
967+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
968+ {-# INLINE return #-}
969+ return x = BehaviorM $ return x
971+ fail s = BehaviorM $ fail s
973+data BehaviorSubscribed x a
974+ = forall p. BehaviorSubscribedHold (Hold x p)
975+ | BehaviorSubscribedPull (PullSubscribed x a)
977+data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
979+--type role PullSubscribed representational
980+data PullSubscribed x a
981+ = PullSubscribed { pullSubscribedValue :: !a
982+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
983+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
984+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
987+--type role Pull representational
989+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
990+ , pullCompute :: !(BehaviorM x a)
997+ = forall a. InvalidatorPull (Pull x a)
998+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
1000+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1001+ { rootSubscribedKey :: !(k a)
1002+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1003+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1004+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1005+ , rootSubscribedUninit :: IO ()
1006+ , 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?
1007+#ifdef DEBUG_NODEIDS
1008+ , rootSubscribedNodeId :: Int
1012+data Root x (k :: * -> *)
1013+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1014+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1015+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1018+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1020+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1022+data SomeMergeUpdate x = SomeMergeUpdate
1023+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1024+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1025+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1028+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1030+-- EventM can do everything BehaviorM can, plus create holds
1031+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
1033+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1035+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1036+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1037+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1040+data HeightBag = HeightBag
1041+ { _heightBag_size :: {-# UNPACK #-} !Int
1042+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1044+ deriving (Show, Read, Eq, Ord)
1046+heightBagEmpty :: HeightBag
1047+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1049+heightBagSize :: HeightBag -> Int
1050+heightBagSize = _heightBag_size
1052+heightBagFromList :: [Height] -> HeightBag
1053+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1055+heightBagAdd :: Height -> HeightBag -> HeightBag
1056+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1058+heightBagRemove :: Height -> HeightBag -> HeightBag
1059+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1060+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1061+ Just old -> HeightBag (pred s) $ case old of
1062+ 0 -> IntMap.delete h c
1063+ _ -> IntMap.insert h (pred old) c
1065+heightBagMax :: HeightBag -> Height
1066+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1067+ Just ((h, _), _) -> Height h
1068+ Nothing -> zeroHeight
1070+heightBagVerify :: HeightBag -> HeightBag
1072+heightBagVerify b@(HeightBag s c) = if
1073+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1074+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1075+ | unHeight invalidHeight `IntMap.member` c
1076+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1079+heightBagVerify = id
1082+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1083+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1084+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1085+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1088+data FanSubscribed (x :: *) k
1089+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1090+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1091+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1092+ , fanSubscribedParent :: !(EventSubscription x)
1093+#ifdef DEBUG_NODEIDS
1094+ , fanSubscribedNodeId :: Int
1099+ = Fan { fanParent :: !(Event x (DMap k Identity))
1100+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1103+data SwitchSubscribed x a
1104+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1105+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1106+ , switchSubscribedHeight :: !(IORef Height)
1107+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1108+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1109+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1110+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1111+ , switchSubscribedParent :: !(Behavior x (Event x a))
1112+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1113+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1114+#ifdef DEBUG_NODEIDS
1115+ , switchSubscribedNodeId :: Int
1120+ = Switch { switchParent :: !(Behavior x (Event x a))
1121+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1124+#ifdef USE_TEMPLATE_HASKELL
1125+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1127+data CoincidenceSubscribed x a
1128+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1129+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1130+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1131+ , coincidenceSubscribedHeight :: !(IORef Height)
1132+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1133+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1134+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1135+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1136+#ifdef DEBUG_NODEIDS
1137+ , coincidenceSubscribedNodeId :: Int
1141+data Coincidence x a
1142+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1143+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1146+{-# NOINLINE newInvalidatorSwitch #-}
1147+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1148+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1150+{-# NOINLINE newInvalidatorPull #-}
1151+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1152+newInvalidatorPull p = return $! InvalidatorPull p
1154+instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1155+ fmapMaybe f = push $ return . f
1157+instance HasSpiderTimeline x => Align (Event x) where
1159+ align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1161+newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1163+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1164+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1166+--TODO: Avoid the duplication between this and R.zipDynWith
1167+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1168+zipDynWith f da db =
1169+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1170+ ec = flip push eab $ \o -> do
1171+ (a, b) <- case o of
1172+ This (Identity a) -> do
1173+ b <- readBehaviorUntracked $ dynamicCurrent db
1175+ That (Identity b) -> do
1176+ a <- readBehaviorUntracked $ dynamicCurrent da
1178+ These (Identity a) (Identity b) -> return (a, b)
1179+ return $ Just $ Identity $ f a b
1180+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1182+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => BehaviorM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1183+buildDynamic readV0 v' = do
1184+ result <- liftIO $ newIORef $ Left (readV0, v')
1185+ let !d = Dyn result
1186+ defer $ SomeDynInit d
1189+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1190+unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1191+ where x = (readV0, v')
1193+-- ResultM can read behaviors and events
1194+type ResultM = EventM
1196+{-# NOINLINE unsafeNewIORef #-}
1197+unsafeNewIORef :: a -> b -> IORef b
1198+unsafeNewIORef a b = unsafePerformIO $ do
1202+instance HasSpiderTimeline x => Functor (Event x) where
1203+ fmap f = push $ return . Just . f
1205+instance Functor (Behavior x) where
1206+ fmap f = pull . fmap f . readBehaviorTracked
1209+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1210+push f e = cacheEvent (pushCheap f e)
1212+{-# INLINABLE pull #-}
1213+pull :: BehaviorM x a -> Behavior x a
1214+pull a = behaviorPull $ Pull
1216+ , pullValue = unsafeNewIORef a Nothing
1217+#ifdef DEBUG_NODEIDS
1218+ , pullNodeId = unsafeNodeId a
1222+{-# INLINABLE switch #-}
1223+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1224+switch a = eventSwitch $ Switch
1226+ , switchSubscribed = unsafeNewIORef a Nothing
1229+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1230+coincidence a = eventCoincidence $ Coincidence
1231+ { coincidenceParent = a
1232+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1235+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1236+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1237+run roots after = do
1238+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1239+ t <- SpiderHost ask
1240+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1241+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1242+ occBefore <- liftIO $ do
1243+ occBefore <- readIORef occRef
1244+ writeIORef occRef $! DMap.insert k a occBefore
1246+ if DMap.null occBefore
1247+ then do scheduleRootClear occRef
1249+ else return Nothing
1250+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1251+ propagate a subscribersRef
1252+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1254+ delayed <- liftIO $ readIORef delayedRef
1255+ case IntMap.minViewWithKey delayed of
1256+ Nothing -> return ()
1257+ Just ((currentHeight, cur), future) -> do
1258+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1259+ putCurrentHeight $ Height currentHeight
1260+ liftIO $ writeIORef delayedRef $! future
1264+ putCurrentHeight maxBound
1266+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1269+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1270+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1271+ height <- liftIO $ readIORef heightRef
1272+ currentHeight <- getCurrentHeight
1273+ case height `compare` currentHeight of
1274+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1275+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1278+data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1280+data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1282+data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1284+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1286+debugFinalize :: Bool
1287+debugFinalize = False
1289+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1290+mkWeakPtrWithDebug x debugNote = do
1294+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1297+type WeakList a = [Weak a]
1299+{-# INLINE withIncreasedDepth #-}
1301+withIncreasedDepth :: CanTrace x m => m a -> m a
1302+withIncreasedDepth a = do
1303+ spiderTimeline <- askSpiderTimelineEnv
1304+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1306+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1309+withIncreasedDepth :: m a -> m a
1310+withIncreasedDepth = id
1313+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1315+{-# INLINE tracePropagate #-}
1316+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1317+tracePropagate p = traceWhen p debugPropagate
1319+{-# INLINE traceInvalidate #-}
1320+traceInvalidate :: String -> IO ()
1321+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1323+{-# INLINE traceWhen #-}
1324+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1325+traceWhen p b message = traceMWhen p b $ return message
1327+{-# INLINE traceMWhen #-}
1328+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1329+traceMWhen _ b getMessage = when b $ do
1330+ message <- getMessage
1332+ spiderTimeline <- askSpiderTimelineEnv
1333+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1337+ liftIO $ putStrLn $ replicate d ' ' <> message
1339+whoCreatedIORef :: IORef a -> IO [String]
1340+whoCreatedIORef (IORef a) = whoCreated $! a
1343+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1346+ (x :| xs) : t -> case groupByHead t of
1347+ [] -> [(x, xs :| [])]
1349+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1350+ | otherwise -> (x, xs :| []) : l
1352+listsToForest :: Eq a => [[a]] -> Forest a
1353+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1356+{-# INLINE propagateSubscriberHold #-}
1357+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1358+propagateSubscriberHold h a = do
1359+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1360+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1361+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1362+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1363+ case {-# SCC "apply" #-} apply a v of
1364+ Nothing -> return ()
1366+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1367+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1368+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1369+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1371+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1373+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1374+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1376+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1378+ (!m, _) <- BehaviorM ask
1380+ Nothing -> return Nothing
1381+ Just (!wi, _) -> return $ Just wi
1383+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1385+ (!m, _) <- BehaviorM ask
1387+ Nothing -> return Nothing
1388+ Just (_, !p) -> return $ Just p
1390+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1391+askBehaviorHoldInits = do
1392+ (_, !his) <- BehaviorM ask
1395+{-# INLINE getDynHold #-}
1396+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1398+ mh <- liftIO $ readIORef $ unDyn d
1400+ Right h -> return h
1401+ Left (readV0, v') -> do
1402+ holdInits <- getDeferralQueue
1403+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1405+ liftIO $ writeIORef (unDyn d) $ Right h
1408+-- Always refers to 0
1409+{-# NOINLINE zeroRef #-}
1410+zeroRef :: IORef Height
1411+zeroRef = unsafePerformIO $ newIORef zeroHeight
1413+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1414+getRootSubscribed k r sub = do
1415+ mSubscribed <- readIORef $ rootSubscribed r
1416+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1417+ case DMap.lookup k mSubscribed of
1418+ Just subscribed -> {-# SCC "hitRoot" #-} do
1419+ sln <- subscribeRootSubscribed subscribed sub
1421+ return (sln, subscribed, occ)
1422+ Nothing -> {-# SCC "missRoot" #-} do
1423+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1424+ let !cached = rootSubscribed r
1425+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1426+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1427+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1428+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1429+ writeIORef uninitRef $! uninit
1430+ let !subscribed = RootSubscribed
1431+ { rootSubscribedKey = k
1432+ , rootSubscribedCachedSubscribed = cached
1433+ , rootSubscribedOccurrence = getOcc
1434+ , rootSubscribedSubscribers = subs
1435+ , rootSubscribedUninit = uninit
1436+ , rootSubscribedWeakSelf = weakSelf
1437+#ifdef DEBUG_NODEIDS
1438+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1441+ -- If we die at the same moment that all our children die, they will
1442+ -- try to clean us up but will fail because their Weak reference to us
1443+ -- will also be dead. So, if we are dying, check if there are any
1444+ -- children; since children don't bother cleaning themselves up if
1445+ -- their parents are already dead, I don't think there's a race
1446+ -- condition here. However, if there are any children, then we can
1447+ -- infer that we need to clean ourselves up, so we do.
1449+ cs <- readIORef $ _weakBag_children subs
1450+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1451+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1452+ 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
1454+ return (sln, subscribed, occ)
1456+#ifdef USE_TEMPLATE_HASKELL
1457+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1459+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1460+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1461+ rootSubscribedUninit self
1462+ modifyIORef' cached $ DMap.delete k
1464+{-# INLINE subscribeRootSubscribed #-}
1465+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1466+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1468+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1470+data FanInt x a = FanInt
1471+ { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1472+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1473+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1476+newFanInt :: IO (FanInt x a)
1478+ subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty
1479+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1480+ occRef <- newIORef $ error "fanInt: no occurrence"
1482+ { _fanInt_subscribers = subscribers
1483+ , _fanInt_subscriptionRef = subscriptionRef
1484+ , _fanInt_occRef = occRef
1487+{-# NOINLINE unsafeNewFanInt #-}
1488+unsafeNewFanInt :: b -> FanInt x a
1489+unsafeNewFanInt b = unsafePerformIO $ do
1493+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1495+ let self = unsafeNewFanInt p
1496+ in EventSelectorInt $ \k -> Event $ \sub -> do
1497+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1498+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1499+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1500+ { subscriberPropagate = \m -> do
1501+ liftIO $ writeIORef (_fanInt_occRef self) m
1502+ scheduleIntClear $ _fanInt_occRef self
1503+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1504+ FastWeakBag.traverse b $ \s -> do
1505+ subscriberPropagate s v
1506+ , subscriberInvalidateHeight = \old -> do
1507+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1508+ FastWeakBag.traverse b $ \s -> do
1509+ subscriberInvalidateHeight s old
1510+ , subscriberRecalculateHeight = \new -> do
1511+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1512+ FastWeakBag.traverse b $ \s -> do
1513+ subscriberRecalculateHeight s new
1516+ writeIORef (_fanInt_subscriptionRef self) subscription
1517+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1518+ scheduleIntClear $ _fanInt_occRef self
1520+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1522+ b <- FastWeakBag.empty
1523+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1526+ t <- liftIO $ FastWeakBag.insert sub b
1527+ currentOcc <- readIORef (_fanInt_occRef self)
1528+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1529+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1531+{-# INLINABLE getFanSubscribed #-}
1532+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1533+getFanSubscribed k f sub = do
1534+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1535+ case mSubscribed of
1536+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1537+ sln <- subscribeFanSubscribed k subscribed sub
1538+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1539+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1540+ Nothing -> {-# SCC "missFan" #-} do
1541+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1542+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1543+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1544+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1545+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1546+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1547+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1548+ occRef <- liftIO $ newIORef parentOcc
1549+ when (isJust parentOcc) $ scheduleClear occRef
1550+ let subscribed = FanSubscribed
1551+ { fanSubscribedCachedSubscribed = fanSubscribed f
1552+ , fanSubscribedOccurrence = occRef
1553+ , fanSubscribedParent = subscription
1554+ , fanSubscribedSubscribers = subscribersRef
1555+#ifdef DEBUG_NODEIDS
1556+ , fanSubscribedNodeId = unsafeNodeId f
1559+ let !self = (k, subscribed)
1560+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1561+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1562+ liftIO $ writeIORef subscribedRef $! subscribed
1563+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1564+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1566+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1567+cleanupFanSubscribed (k, subscribed) = do
1568+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1569+ let reducedSubscribers = DMap.delete k subscribers
1570+ if DMap.null reducedSubscribers
1572+ unsubscribe $ fanSubscribedParent subscribed
1573+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1574+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1575+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1577+{-# INLINE subscribeFanSubscribed #-}
1578+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1579+subscribeFanSubscribed k subscribed sub = do
1580+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1581+ case DMap.lookup k subscribers of
1582+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1583+ let !self = (k, subscribed)
1584+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1585+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1586+ 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
1588+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1590+{-# INLINABLE getSwitchSubscribed #-}
1591+getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1592+getSwitchSubscribed s sub = do
1593+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1594+ case mSubscribed of
1595+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1596+ sln <- subscribeSwitchSubscribed subscribed sub
1597+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1598+ return (sln, subscribed, occ)
1599+ Nothing -> {-# SCC "missSwitch" #-} do
1600+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1601+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1602+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1603+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1604+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1605+ wiRef <- liftIO $ newIORef wi
1606+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1607+ holdInits <- getDeferralQueue
1608+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1609+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1610+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1611+ subscriptionRef <- liftIO $ newIORef subscription
1612+ occRef <- liftIO $ newIORef parentOcc
1613+ when (isJust parentOcc) $ scheduleClear occRef
1614+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1615+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1616+ let !subscribed = SwitchSubscribed
1617+ { switchSubscribedCachedSubscribed = switchSubscribed s
1618+ , switchSubscribedOccurrence = occRef
1619+ , switchSubscribedHeight = heightRef
1620+ , switchSubscribedSubscribers = subs
1621+ , switchSubscribedOwnInvalidator = i
1622+ , switchSubscribedOwnWeakInvalidator = wiRef
1623+ , switchSubscribedBehaviorParents = parentsRef
1624+ , switchSubscribedParent = switchParent s
1625+ , switchSubscribedCurrentParent = subscriptionRef
1626+ , switchSubscribedWeakSelf = weakSelf
1627+#ifdef DEBUG_NODEIDS
1628+ , switchSubscribedNodeId = unsafeNodeId s
1631+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1632+ liftIO $ writeIORef subscribedRef $! subscribed
1633+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1634+ return (slnForSub, subscribed, parentOcc)
1636+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1637+cleanupSwitchSubscribed subscribed = do
1638+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1639+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1640+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1642+{-# INLINE subscribeSwitchSubscribed #-}
1643+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1644+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1646+{-# INLINABLE getCoincidenceSubscribed #-}
1647+getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1648+getCoincidenceSubscribed c sub = do
1649+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1650+ case mSubscribed of
1651+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1652+ sln <- subscribeCoincidenceSubscribed subscribed sub
1653+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1654+ return (sln, subscribed, occ)
1655+ Nothing -> {-# SCC "missCoincidence" #-} do
1656+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1657+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1658+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1659+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1660+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1661+ (occ, height, mInnerSubd) <- case outerOcc of
1662+ Nothing -> return (Nothing, outerHeight, Nothing)
1664+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1665+ return (occ, height, Just innerSubd)
1666+ occRef <- liftIO $ newIORef occ
1667+ when (isJust occ) $ scheduleClear occRef
1668+ heightRef <- liftIO $ newIORef height
1669+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1670+ scheduleClear innerSubdRef
1671+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1672+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1673+ let subscribed = CoincidenceSubscribed
1674+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1675+ , coincidenceSubscribedOccurrence = occRef
1676+ , coincidenceSubscribedHeight = heightRef
1677+ , coincidenceSubscribedSubscribers = subs
1678+ , coincidenceSubscribedOuter = subOuter
1679+ , coincidenceSubscribedOuterParent = outerSubscription
1680+ , coincidenceSubscribedInnerParent = innerSubdRef
1681+ , coincidenceSubscribedWeakSelf = weakSelf
1682+#ifdef DEBUG_NODEIDS
1683+ , coincidenceSubscribedNodeId = unsafeNodeId c
1686+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1687+ liftIO $ writeIORef subscribedRef $! subscribed
1688+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1689+ return (slnForSub, subscribed, occ)
1691+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1692+cleanupCoincidenceSubscribed subscribed = do
1693+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1694+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1696+{-# INLINE subscribeCoincidenceSubscribed #-}
1697+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1698+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1700+{-# INLINE merge #-}
1701+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1702+merge d = cacheEvent (mergeCheap d)
1704+{-# INLINE mergeWithMove #-}
1705+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1706+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1708+{-# INLINE [1] mergeCheap #-}
1709+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1710+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1712+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1713+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1714+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1715+ (mOldSubd, newPs) <- case me of
1716+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1718+ let s = subscriber $ return k
1719+ subscription@(EventSubscription _ subd) <- subscribe e s
1720+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1721+ let newParent = MergeSubscribedParent subscription
1722+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1723+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1724+ forM_ mOldSubd $ \oldSubd -> do
1725+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1726+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1727+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1728+ foldM f ([], oldParents) $ DMap.toList p
1729+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1730+ getInitialSubscribers initialParents subscriber = do
1731+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1732+ let s = subscriber $ return k
1733+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1734+ height <- liftIO $ getEventSubscribedHeight parentSubd
1735+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1736+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1737+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1738+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1740+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1741+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1743+{-# INLINE [1] mergeCheapWithMove #-}
1744+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1745+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1747+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1748+ updateMe subscriber heightBagRef oldParents p = do
1749+ -- Prepare new parents for insertion
1750+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1751+ subscribeParent k e = do
1752+ keyRef <- liftIO $ newIORef k
1753+ let s = subscriber $ liftIO $ readIORef keyRef
1754+ subscription@(EventSubscription _ subd) <- subscribe e s
1756+ newParentHeight <- getEventSubscribedHeight subd
1757+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1758+ return $ MergeSubscribedParentWithMove subscription keyRef
1759+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1760+ -- Collect old parents for deletion and update the keys of moved parents
1761+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1762+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1764+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1765+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1766+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1768+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1770+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1771+ return (toDelete, applyAlways p' oldParents)
1772+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1773+ getInitialSubscribers initialParents subscriber = do
1774+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1775+ keyRef <- liftIO $ newIORef k
1776+ let s = subscriber $ liftIO $ readIORef keyRef
1777+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1778+ height <- liftIO $ getEventSubscribedHeight parentSubd
1779+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1780+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1781+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1782+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1784+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1785+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1787+type MergeUpdateFunc k x p s
1788+ = (forall a. EventM x (k a) -> Subscriber x a)
1792+ -> EventM x ([EventSubscription x], DMap k s)
1794+type MergeInitFunc k x s
1796+ -> (forall a. EventM x (k a) -> Subscriber x a)
1797+ -> EventM x (DMap k Identity, [Height], DMap k s)
1799+type MergeDestroyFunc k s
1803+data Merge x k s = Merge
1804+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1805+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1806+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1807+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1808+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1811+invalidateMergeHeight :: Merge x k s -> IO ()
1812+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1814+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1815+invalidateMergeHeight' heightRef sub = do
1816+ oldHeight <- readIORef heightRef
1817+ 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
1818+ writeIORef heightRef $! invalidHeight
1819+ subscriberInvalidateHeight sub oldHeight
1822+revalidateMergeHeight :: Merge x k s -> IO ()
1823+revalidateMergeHeight m = do
1824+ currentHeight <- readIORef $ _merge_heightRef m
1825+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1826+ heights <- readIORef $ _merge_heightBagRef m
1827+ parents <- readIORef $ _merge_parentsRef m
1828+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1829+ case heightBagSize heights `compare` DMap.size parents of
1832+ let height = succHeight $ heightBagMax heights
1833+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1834+ writeIORef (_merge_heightRef m) $! height
1835+ subscriberRecalculateHeight (_merge_sub m) height
1836+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1838+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1839+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1840+ vals <- liftIO $ readIORef $ _merge_accumRef m
1841+ liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
1842+ --TODO: Assert that m is not empty
1843+ subscriberPropagate (_merge_sub m) vals
1845+mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1846+mergeSubscriber m getKey = Subscriber
1847+ { subscriberPropagate = \a -> do
1848+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1850+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1851+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1852+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1853+ when (DMap.null oldM) $ do -- Only schedule the firing once
1854+ height <- liftIO $ readIORef $ _merge_heightRef m
1855+ --TODO: assertions about height
1856+ currentHeight <- getCurrentHeight
1857+ when (height <= currentHeight) $ do
1858+ if height /= invalidHeight
1860+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1861+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1864+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1865+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1866+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1870+ error $ "Causality loop found" <> cycleInfo
1871+ scheduleMergeSelf m height
1872+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1873+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1874+ invalidateMergeHeight m
1875+ , subscriberRecalculateHeight = \new -> do
1876+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1877+ revalidateMergeHeight m
1880+--TODO: Be able to run as much of this as possible promptly
1881+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1882+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1883+ where updateMe = do
1884+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1885+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1886+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1887+ return subscriptionsToKill
1889+{-# INLINE mergeCheap' #-}
1890+mergeCheap' :: forall k x p s. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k (Event x)) => MergeInitFunc k x s -> MergeUpdateFunc k x p s -> MergeDestroyFunc k s -> Dynamic x p -> Event x (DMap k Identity)
1891+mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1892+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1893+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1894+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1895+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1896+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1898+ { _merge_parentsRef = parentsRef
1899+ , _merge_heightBagRef = heightBagRef
1900+ , _merge_heightRef = heightRef
1902+ , _merge_accumRef = accumRef
1904+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1905+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1906+ myHeight = if invalidHeight `elem` heights
1908+ else succHeight $ heightBagMax myHeightBag
1909+ currentHeight <- getCurrentHeight
1910+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1911+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1913+ unless (DMap.null accum) $ do
1914+ scheduleMergeSelf m myHeight
1915+ liftIO $ writeIORef accumRef $! accum
1916+ liftIO $ writeIORef heightRef $! myHeight
1917+ liftIO $ writeIORef heightBagRef $! myHeightBag
1918+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1919+ liftIO $ writeIORef parentsRef $! initialParentState
1920+ defer $ SomeMergeInit $ do
1922+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1923+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1924+ defer $ updateMerge m updateFunc a
1925+ , subscriberInvalidateHeight = \_ -> return ()
1926+ , subscriberRecalculateHeight = \_ -> return ()
1928+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1929+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1930+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1931+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1932+ -- its subscription.
1933+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1934+ let unsubscribeAll = destroy =<< readIORef parentsRef
1935+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1939+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1940+mergeInt = cacheEvent . mergeIntCheap
1942+{-# INLINABLE mergeIntCheap #-}
1943+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1944+mergeIntCheap d = Event $ \sub -> do
1945+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1946+ accum <- liftIO $ FastMutableIntMap.newEmpty
1947+ heightRef <- liftIO $ newIORef zeroHeight
1948+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1949+ parents <- liftIO $ FastMutableIntMap.newEmpty
1950+ let scheduleSelf = do
1951+ height <- liftIO $ readIORef $ heightRef
1952+ scheduleMerge' height heightRef $ do
1953+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1954+ subscriberPropagate sub vals
1955+ invalidateMyHeight = do
1956+ invalidateMergeHeight' heightRef sub
1957+ recalculateMyHeight = do
1958+ currentHeight <- readIORef heightRef
1959+ when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?
1960+ heights <- readIORef heightBagRef
1961+ numParents <- FastMutableIntMap.size parents
1962+ case heightBagSize heights `compare` numParents of
1965+ let height = succHeight $ heightBagMax heights
1966+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1967+ writeIORef heightRef $! height
1968+ subscriberRecalculateHeight sub height
1969+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1970+ mySubscriber k = Subscriber
1971+ { subscriberPropagate = \a -> do
1972+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1973+ liftIO $ FastMutableIntMap.insert accum k a
1974+ when wasEmpty scheduleSelf
1975+ , subscriberInvalidateHeight = \old -> do
1976+ modifyIORef' heightBagRef $ heightBagRemove old
1978+ , subscriberRecalculateHeight = \new -> do
1979+ modifyIORef' heightBagRef $ heightBagAdd new
1980+ recalculateMyHeight
1982+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1983+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1985+ forM_ parentOcc $ FastMutableIntMap.insert accum k
1986+ FastMutableIntMap.insert parents k subscription
1987+ height <- getEventSubscribedHeight parentSubd
1988+ if height == invalidHeight
1989+ then writeIORef heightRef invalidHeight
1991+ modifyIORef' heightBagRef $ heightBagAdd height
1992+ modifyIORef' heightRef $ \oldHeight ->
1993+ if oldHeight == invalidHeight
1995+ else max (succHeight height) oldHeight
1996+ myHeight <- liftIO $ readIORef heightRef
1997+ currentHeight <- getCurrentHeight
1998+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1999+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2001+ then return Nothing
2002+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2003+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2005+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2006+ defer $ SomeMergeInit $ do
2007+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2010+ let f k newParent = do
2011+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2012+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2013+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2014+ return subscription
2015+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2016+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2017+ liftIO $ for_ oldParents $ \oldParent -> do
2018+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2019+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2020+ return $ IntMap.elems oldParents
2022+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2023+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2025+ , subscriberInvalidateHeight = \_ -> return ()
2026+ , subscriberRecalculateHeight = \_ -> return ()
2028+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2029+ forM_ change $ \c -> defer $ updateMe c
2030+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2031+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2032+ -- its subscription.
2033+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2034+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2035+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2039+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2041+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2045+ , fanSubscribed = unsafeNewIORef e Nothing
2047+ in EventSelector $ \k -> eventFan k f
2049+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2050+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2051+ holdInits <- liftIO $ readIORef holdInitRef
2052+ dynInits <- liftIO $ readIORef dynInitRef
2053+ mergeInits <- liftIO $ readIORef mergeInitRef
2054+ unless (null holdInits && null dynInits && null mergeInits) $ do
2055+ liftIO $ writeIORef holdInitRef []
2056+ liftIO $ writeIORef dynInitRef []
2057+ liftIO $ writeIORef mergeInitRef []
2058+ mapM_ initHold holdInits
2059+ mapM_ initDyn dynInits
2060+ mapM_ unSomeMergeInit mergeInits
2061+ runHoldInits holdInitRef dynInitRef mergeInitRef
2063+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2064+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2066+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2067+initDyn (SomeDynInit d) = void $ getDynHold d
2069+newEventEnv :: IO (EventEnv x)
2071+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2072+ holdInitRef <- newIORef []
2073+ dynInitRef <- newIORef []
2074+ mergeUpdateRef <- newIORef []
2075+ mergeInitRef <- newIORef []
2076+ heightRef <- newIORef zeroHeight
2077+ toClearRef <- newIORef []
2078+ toClearIntRef <- newIORef []
2079+ toClearRootRef <- newIORef []
2080+ coincidenceInfosRef <- newIORef []
2081+ delayedRef <- newIORef IntMap.empty
2082+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2084+clearEventEnv :: EventEnv x -> IO ()
2085+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2086+ writeIORef toAssignRef []
2087+ writeIORef holdInitRef []
2088+ writeIORef dynInitRef []
2089+ writeIORef mergeUpdateRef []
2090+ writeIORef mergeInitRef []
2091+ writeIORef heightRef zeroHeight
2092+ writeIORef toClearRef []
2093+ writeIORef toClearIntRef []
2094+ writeIORef toClearRootRef []
2095+ writeIORef coincidenceInfosRef []
2096+ writeIORef delayedRef IntMap.empty
2098+-- | Run an event action outside of a frame
2099+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2100+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
2101+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2104+ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits 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
2106+ result <- runEventM go
2107+ toClear <- readIORef $ eventEnvClears env
2108+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2109+ toClearInt <- readIORef $ eventEnvIntClears env
2110+ forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2111+ toClearRoot <- readIORef $ eventEnvRootClears env
2112+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2113+ toAssign <- readIORef $ eventEnvAssignments env
2114+ toReconnectRef <- newIORef []
2115+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2116+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2118+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2119+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2120+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2121+ writeIORef (eventEnvMergeUpdates env) []
2122+ when debugPropagate $ putStrLn "Updating merges"
2123+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2124+ when debugPropagate $ putStrLn "Updating merges done"
2125+ toReconnect <- readIORef toReconnectRef
2127+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2128+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2129+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2130+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2132+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2133+ wi' <- mkWeakPtrWithDebug i "wi'"
2134+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2135+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2136+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2137+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2138+ runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits 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
2139+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2140+ sub <- newSubscriberSwitch subscribed
2141+ 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
2143+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2144+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2145+ EventRoot _ -> "EventRoot"
2146+ EventNever -> "EventNever"
2147+ _ -> "something else"
2149+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2150+ return oldSubscription
2151+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2152+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2153+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2154+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2155+ parentHeight <- getEventSubscribedHeight subd'
2156+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2157+ when (parentHeight /= myHeight) $ do
2158+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2159+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2160+ 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
2161+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2162+ unsubscribe subscription
2163+ mapM_ invalidateCoincidenceHeight mcs
2164+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2165+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2166+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2167+ height <- calculateSwitchHeight subscribed
2168+ updateSwitchHeight height subscribed
2171+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2173+{-# INLINE zeroHeight #-}
2174+zeroHeight :: Height
2175+zeroHeight = Height 0
2177+{-# INLINE invalidHeight #-}
2178+invalidHeight :: Height
2179+invalidHeight = Height (-1000)
2182+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2183+{-# INLINE invalidHeightBeingTraversed #-}
2184+invalidHeightBeingTraversed :: Height
2185+invalidHeightBeingTraversed = Height (-1001)
2188+{-# INLINE succHeight #-}
2189+succHeight :: Height -> Height
2190+succHeight h@(Height a) =
2191+ if h == invalidHeight
2193+ else Height $ succ a
2195+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2196+invalidateCoincidenceHeight subscribed = do
2197+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2198+ when (oldHeight /= invalidHeight) $ do
2199+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2200+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2202+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2203+updateSwitchHeight new subscribed = do
2204+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2205+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2206+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2207+ writeIORef (switchSubscribedHeight subscribed) $! new
2208+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2210+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2211+recalculateCoincidenceHeight subscribed = do
2212+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2213+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2214+ height <- calculateCoincidenceHeight subscribed
2215+ when (height /= invalidHeight) $ do
2216+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2217+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2219+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2220+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2222+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2223+calculateCoincidenceHeight subscribed = do
2224+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2225+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2226+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2228+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2230+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2231+invalidate toReconnectRef wis = do
2232+ forM_ wis $ \wi -> do
2236+ traceInvalidate "invalidate Dead"
2237+ return () --TODO: Should we clean this up here?
2239+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2241+ InvalidatorPull p -> do
2242+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2243+ mVal <- readIORef $ pullValue p
2244+ forM_ mVal $ \val -> do
2245+ writeIORef (pullValue p) Nothing
2246+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2247+ InvalidatorSwitch subscribed -> do
2248+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2249+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2250+ 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
2252+--------------------------------------------------------------------------------
2253+-- Reflex integration
2254+--------------------------------------------------------------------------------
2256+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2257+-- When we're specializing, we include this from Reflex.Class instead, because
2258+-- it needs access to these types; when we're not, we want them here, so our
2259+-- instance isn't an orphan instance.
2260+#include "SpiderTimeline.include.hs"
2261+#include "SpiderTimelineHost.include.hs"
2264+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2265+unsafeNewSpiderTimelineEnv = do
2269+ depthRef <- newIORef 0
2271+ return $ SpiderTimelineEnv
2272+ { _spiderTimeline_lock = lock
2273+ , _spiderTimeline_eventEnv = env
2275+ , _spiderTimeline_depth = depthRef
2279+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2280+-- | Create a new SpiderTimelineEnv
2281+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2282+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2284+data LocalSpiderTimeline x s
2286+instance Reifies s (SpiderTimelineEnv x) =>
2287+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2288+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2292+ -> SpiderTimelineEnv x
2293+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2294+localSpiderTimeline _ = unsafeCoerce
2296+-- | Pass a new timeline to the given function.
2297+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2298+withSpiderTimeline k = do
2299+ env <- unsafeNewSpiderTimelineEnv
2300+ reify env $ \s -> k $ localSpiderTimeline s env
2303+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2305+type ComputeM = EventM
2307+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2309+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2310+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2311+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2312+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2313+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2314+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2315+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2316+ type PullM (SpiderTimeline x) = SpiderPullM x
2317+ type PushM (SpiderTimeline x) = SpiderPushM x
2318+ {-# INLINABLE never #-}
2319+ never = SpiderEvent eventNever
2320+ {-# INLINABLE constant #-}
2321+ constant = SpiderBehavior . behaviorConst
2322+ {-# INLINE push #-}
2323+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2324+ {-# INLINE pushCheap #-}
2325+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2326+ {-# INLINABLE pull #-}
2327+ pull = SpiderBehavior . pull . coerce
2328+ {-# INLINABLE merge #-}
2329+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2330+ {-# INLINABLE fan #-}
2331+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2332+ {-# INLINABLE switch #-}
2333+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2334+ {-# INLINABLE coincidence #-}
2335+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2336+ {-# INLINABLE current #-}
2337+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2338+ {-# INLINABLE updated #-}
2339+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2340+ {-# INLINABLE unsafeBuildDynamic #-}
2341+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2342+ {-# INLINABLE unsafeBuildIncremental #-}
2343+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2344+ {-# INLINABLE mergeIncremental #-}
2345+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2346+ {-# INLINABLE mergeIncrementalWithMove #-}
2347+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2348+ {-# INLINABLE currentIncremental #-}
2349+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2350+ {-# INLINABLE updatedIncremental #-}
2351+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2352+ {-# INLINABLE incrementalToDynamic #-}
2353+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2354+ c <- readBehaviorUntracked $ dynamicCurrent i
2355+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2356+ eventCoercion Coercion = Coercion
2357+ behaviorCoercion Coercion = Coercion
2358+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2359+ {-# INLINABLE mergeIntIncremental #-}
2360+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2361+ {-# INLINABLE fanInt #-}
2362+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2365+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2367+data SpiderEventHandle x a = SpiderEventHandle
2368+ { spiderEventHandleSubscription :: EventSubscription x
2369+ , spiderEventHandleValue :: IORef (Maybe a)
2372+instance MonadRef (EventM x) where
2373+ type Ref (EventM x) = Ref IO
2374+ {-# INLINABLE newRef #-}
2375+ {-# INLINABLE readRef #-}
2376+ {-# INLINABLE writeRef #-}
2377+ newRef = liftIO . newRef
2378+ readRef = liftIO . readRef
2379+ writeRef r a = liftIO $ writeRef r a
2381+instance MonadAtomicRef (EventM x) where
2382+ {-# INLINABLE atomicModifyRef #-}
2383+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2385+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2386+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2388+instance Monad (SpiderHost x) where
2389+ {-# INLINABLE (>>=) #-}
2390+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2391+ {-# INLINABLE (>>) #-}
2392+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2393+ {-# INLINABLE return #-}
2394+ return x = SpiderHost $ return x
2395+ {-# INLINABLE fail #-}
2396+ fail s = SpiderHost $ fail s
2398+-- | Run an action affecting the global Spider timeline; this will be guarded by
2399+-- a mutex for that timeline
2400+runSpiderHost :: SpiderHost Global a -> IO a
2401+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2403+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2404+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2405+-- mutex for that timeline
2406+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2407+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2410+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2412+instance Monad (SpiderHostFrame x) where
2413+ {-# INLINABLE (>>=) #-}
2414+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2415+ {-# INLINABLE (>>) #-}
2416+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2417+ {-# INLINABLE return #-}
2418+ return x = SpiderHostFrame $ return x
2419+ {-# INLINABLE fail #-}
2420+ fail s = SpiderHostFrame $ fail s
2422+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2423+newEventWithTriggerIO f = do
2424+ es <- newFanEventWithTriggerIO $ \Refl -> f
2425+ return $ select es Refl
2427+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2428+newFanEventWithTriggerIO f = do
2429+ occRef <- newIORef DMap.empty
2430+ subscribedRef <- newIORef DMap.empty
2432+ { rootOccurrence = occRef
2433+ , rootSubscribed = subscribedRef
2436+ return $ EventSelector $ \k -> eventRoot k r
2438+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2440+instance MonadRef (SpiderHost x) where
2441+ type Ref (SpiderHost x) = Ref IO
2442+ newRef = SpiderHost . newRef
2443+ readRef = SpiderHost . readRef
2444+ writeRef r = SpiderHost . writeRef r
2446+instance MonadAtomicRef (SpiderHost x) where
2447+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2449+instance MonadRef (SpiderHostFrame x) where
2450+ type Ref (SpiderHostFrame x) = Ref IO
2451+ newRef = SpiderHostFrame . newRef
2452+ readRef = SpiderHostFrame . readRef
2453+ writeRef r = SpiderHostFrame . writeRef r
2455+instance MonadAtomicRef (SpiderHostFrame x) where
2456+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2458+instance PrimMonad (SpiderHostFrame x) where
2459+ type PrimState (SpiderHostFrame x) = PrimState IO
2460+ primitive = SpiderHostFrame . EventM . primitive