@@ -0,0 +1,2471 @@
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 :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (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 :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (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) :))
704+{-# INLINABLE readBehaviorUntracked #-}
705+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
706+readBehaviorUntracked b = do
707+ holdInits <- getDeferralQueue
708+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
710+--------------------------------------------------------------------------------
712+--------------------------------------------------------------------------------
714+data Dynamic x p = Dynamic
715+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
716+ , dynamicUpdated :: !(Event x p)
719+dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
720+dynamicHold !h = Dynamic
721+ { dynamicCurrent = behaviorHold h
722+ , dynamicUpdated = eventHold h
725+dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
726+dynamicHoldIdentity = dynamicHold
728+dynamicConst :: PatchTarget p -> Dynamic x p
729+dynamicConst !a = Dynamic
730+ { dynamicCurrent = behaviorConst a
731+ , dynamicUpdated = eventNever
734+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
735+dynamicDyn !d = Dynamic
736+ { dynamicCurrent = behaviorDyn d
737+ , dynamicUpdated = eventDyn d
740+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
741+dynamicDynIdentity = dynamicDyn
743+--------------------------------------------------------------------------------
745+--------------------------------------------------------------------------------
747+--TODO: Figure out why certain things are not 'representational', then make them
748+--representational so we can use coerce
750+--type role Hold representational
752+ = Hold { holdValue :: !(IORef (PatchTarget p))
753+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
754+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
755+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
761+-- | A statically allocated 'SpiderTimeline'; this is the only instance of
762+-- 'SpiderTimeline' that can used when using
763+-- -fspecialize-to-spidertimeline-global.
766+{-# NOINLINE globalSpiderTimelineEnv #-}
767+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
768+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
770+-- | Stores all global data relevant to a particular Spider timeline; only one
771+-- value should exist for each type @x@
772+data SpiderTimelineEnv x = SpiderTimelineEnv
773+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
774+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
776+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
779+type role SpiderTimelineEnv nominal
781+instance Eq (SpiderTimelineEnv x) where
782+ _ == _ = True -- Since only one exists of each type
784+instance GEq SpiderTimelineEnv where
785+#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
787+ geqUnify (a :: SpiderTimelineEnv a) (b :: SpiderTimelineEnv b) different same = if _spiderTimeline_lock a == _spiderTimeline_lock b
788+ then case unsafeCoerce Refl :: a :~: b of
789+ Refl -> same -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
792+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
793+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
798+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
799+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
800+ , eventEnvDynInits :: !(IORef [SomeDynInit x])
801+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
802+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
803+ , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
804+ , eventEnvIntClears :: !(IORef [SomeIntClear])
805+ , eventEnvRootClears :: !(IORef [SomeRootClear])
806+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
807+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
808+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
811+{-# INLINE runEventM #-}
812+runEventM :: EventM x a -> IO a
815+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
816+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
818+class MonadIO m => Defer a m where
819+ getDeferralQueue :: m (IORef [a])
822+defer :: Defer a m => a -> m ()
824+ q <- getDeferralQueue
825+ liftIO $ modifyIORef' q (a:)
827+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
828+ {-# INLINE getDeferralQueue #-}
829+ getDeferralQueue = asksEventEnv eventEnvAssignments
831+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
832+ {-# INLINE getDeferralQueue #-}
833+ getDeferralQueue = asksEventEnv eventEnvHoldInits
835+instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where
836+ {-# INLINE getDeferralQueue #-}
837+ getDeferralQueue = asksEventEnv eventEnvDynInits
839+instance Defer (SomeHoldInit x) (BehaviorM x) where
840+ {-# INLINE getDeferralQueue #-}
841+ getDeferralQueue = BehaviorM $ asks snd
843+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
844+ {-# INLINE getDeferralQueue #-}
845+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
847+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
848+ {-# INLINE getDeferralQueue #-}
849+ getDeferralQueue = asksEventEnv eventEnvMergeInits
851+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
852+ getCurrentHeight :: m Height
853+ scheduleMerge :: Height -> EventM x () -> m ()
855+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
856+ {-# INLINE getCurrentHeight #-}
857+ getCurrentHeight = do
858+ heightRef <- asksEventEnv eventEnvCurrentHeight
859+ liftIO $ readIORef heightRef
860+ {-# INLINE scheduleMerge #-}
861+ scheduleMerge height subscribed = do
862+ delayedRef <- asksEventEnv eventEnvDelayedMerges
863+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
865+#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
866+class x ~ Global => HasSpiderTimeline x where
868+class HasSpiderTimeline x where
870+ -- | Retrieve the current SpiderTimelineEnv
871+ spiderTimeline :: SpiderTimelineEnv x
873+instance HasSpiderTimeline Global where
874+ spiderTimeline = globalSpiderTimelineEnv
876+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
877+putCurrentHeight h = do
878+ heightRef <- asksEventEnv eventEnvCurrentHeight
879+ liftIO $ writeIORef heightRef $! h
881+instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
882+ {-# INLINE getDeferralQueue #-}
883+ getDeferralQueue = asksEventEnv eventEnvClears
885+{-# INLINE scheduleClear #-}
886+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
887+scheduleClear r = defer $ SomeClear r
889+instance HasSpiderTimeline x => Defer SomeIntClear (EventM x) where
890+ {-# INLINE getDeferralQueue #-}
891+ getDeferralQueue = asksEventEnv eventEnvIntClears
893+{-# INLINE scheduleIntClear #-}
894+scheduleIntClear :: Defer SomeIntClear m => IORef (IntMap a) -> m ()
895+scheduleIntClear r = defer $ SomeIntClear r
897+instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
898+ {-# INLINE getDeferralQueue #-}
899+ getDeferralQueue = asksEventEnv eventEnvRootClears
901+{-# INLINE scheduleRootClear #-}
902+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
903+scheduleRootClear r = defer $ SomeRootClear r
905+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
906+ {-# INLINE getDeferralQueue #-}
907+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
909+-- Note: hold cannot examine its event until after the phase is over
910+{-# INLINE [1] hold #-}
911+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
913+ valRef <- liftIO $ newIORef v0
914+ invsRef <- liftIO $ newIORef []
915+ parentRef <- liftIO $ newIORef Nothing
917+ nodeId <- liftIO newNodeId
920+ { holdValue = valRef
921+ , holdInvalidators = invsRef
923+ , holdParent = parentRef
925+ , holdNodeId = nodeId
928+ defer $ SomeHoldInit h
931+{-# INLINE getHoldEventSubscription #-}
932+getHoldEventSubscription :: forall m p x. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer SomeClear m, Patch p, HasCurrentHeight x m, Defer (SomeMergeInit x) m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Hold x p -> m (EventSubscription x)
933+getHoldEventSubscription h = do
934+ ep <- liftIO $ readIORef $ holdParent h
936+ Just subd -> return subd
939+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
940+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
941+ liftIO $ writeIORef subscriptionRef $! subscription
943+ Nothing -> return ()
945+ old <- liftIO $ readIORef $ holdValue h
947+ Nothing -> return ()
949+ -- Need to evaluate these so that we don't retain the Hold itself
950+ v <- liftIO $ evaluate $ holdValue h
951+ i <- liftIO $ evaluate $ holdInvalidators h
952+ defer $ SomeAssignment v i new
953+ liftIO $ writeIORef (holdParent h) $ Just subscription
956+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
958+--type role BehaviorM representational
959+-- BehaviorM can sample behaviors
960+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
962+instance Monad (BehaviorM x) where
963+ {-# INLINE (>>=) #-}
964+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
966+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
967+ {-# INLINE return #-}
968+ return x = BehaviorM $ return x
970+ fail s = BehaviorM $ fail s
972+data BehaviorSubscribed x a
973+ = forall p. BehaviorSubscribedHold (Hold x p)
974+ | BehaviorSubscribedPull (PullSubscribed x a)
976+data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
978+--type role PullSubscribed representational
979+data PullSubscribed x a
980+ = PullSubscribed { pullSubscribedValue :: !a
981+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
982+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
983+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
986+--type role Pull representational
988+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
989+ , pullCompute :: !(BehaviorM x a)
996+ = forall a. InvalidatorPull (Pull x a)
997+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
999+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
1000+ { rootSubscribedKey :: !(k a)
1001+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
1002+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1003+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
1004+ , rootSubscribedUninit :: IO ()
1005+ , 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?
1006+#ifdef DEBUG_NODEIDS
1007+ , rootSubscribedNodeId :: Int
1011+data Root x (k :: * -> *)
1012+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
1013+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
1014+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
1017+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
1019+data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)
1021+data SomeMergeUpdate x = SomeMergeUpdate
1022+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
1023+ , _someMergeUpdate_invalidateHeight :: !(IO ())
1024+ , _someMergeUpdate_recalculateHeight :: !(IO ())
1027+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
1029+-- EventM can do everything BehaviorM can, plus create holds
1030+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
1032+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
1034+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
1035+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
1036+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
1039+data HeightBag = HeightBag
1040+ { _heightBag_size :: {-# UNPACK #-} !Int
1041+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
1043+ deriving (Show, Read, Eq, Ord)
1045+heightBagEmpty :: HeightBag
1046+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
1048+heightBagSize :: HeightBag -> Int
1049+heightBagSize = _heightBag_size
1051+heightBagFromList :: [Height] -> HeightBag
1052+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
1054+heightBagAdd :: Height -> HeightBag -> HeightBag
1055+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1057+heightBagRemove :: Height -> HeightBag -> HeightBag
1058+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1059+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1060+ Just old -> HeightBag (pred s) $ case old of
1061+ 0 -> IntMap.delete h c
1062+ _ -> IntMap.insert h (pred old) c
1064+heightBagMax :: HeightBag -> Height
1065+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1066+ Just ((h, _), _) -> Height h
1067+ Nothing -> zeroHeight
1069+heightBagVerify :: HeightBag -> HeightBag
1071+heightBagVerify b@(HeightBag s c) = if
1072+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1073+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1074+ | unHeight invalidHeight `IntMap.member` c
1075+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1078+heightBagVerify = id
1081+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1082+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1083+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1084+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1087+data FanSubscribed (x :: *) k
1088+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1089+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1090+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1091+ , fanSubscribedParent :: !(EventSubscription x)
1092+#ifdef DEBUG_NODEIDS
1093+ , fanSubscribedNodeId :: Int
1098+ = Fan { fanParent :: !(Event x (DMap k Identity))
1099+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1102+data SwitchSubscribed x a
1103+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1104+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1105+ , switchSubscribedHeight :: !(IORef Height)
1106+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1107+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1108+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1109+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1110+ , switchSubscribedParent :: !(Behavior x (Event x a))
1111+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1112+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1113+#ifdef DEBUG_NODEIDS
1114+ , switchSubscribedNodeId :: Int
1119+ = Switch { switchParent :: !(Behavior x (Event x a))
1120+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1123+#ifdef USE_TEMPLATE_HASKELL
1124+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1126+data CoincidenceSubscribed x a
1127+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1128+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1129+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1130+ , coincidenceSubscribedHeight :: !(IORef Height)
1131+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1132+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1133+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1134+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1135+#ifdef DEBUG_NODEIDS
1136+ , coincidenceSubscribedNodeId :: Int
1140+data Coincidence x a
1141+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1142+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1145+{-# NOINLINE newInvalidatorSwitch #-}
1146+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1147+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1149+{-# NOINLINE newInvalidatorPull #-}
1150+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1151+newInvalidatorPull p = return $! InvalidatorPull p
1153+instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1154+ fmapMaybe f = push $ return . f
1156+instance HasSpiderTimeline x => Align (Event x) where
1158+ align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1160+newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1162+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1163+newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1165+--TODO: Avoid the duplication between this and R.zipDynWith
1166+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1167+zipDynWith f da db =
1168+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1169+ ec = flip push eab $ \o -> do
1170+ (a, b) <- case o of
1171+ This (Identity a) -> do
1172+ b <- readBehaviorUntracked $ dynamicCurrent db
1174+ That (Identity b) -> do
1175+ a <- readBehaviorUntracked $ dynamicCurrent da
1177+ These (Identity a) (Identity b) -> return (a, b)
1178+ return $ Just $ Identity $ f a b
1179+ in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1181+buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => BehaviorM x (PatchTarget p) -> Event x p -> m (Dyn x p)
1182+buildDynamic readV0 v' = do
1183+ result <- liftIO $ newIORef $ Left (readV0, v')
1184+ let !d = Dyn result
1185+ defer $ SomeDynInit d
1188+unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1189+unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1190+ where x = (readV0, v')
1192+-- ResultM can read behaviors and events
1193+type ResultM = EventM
1195+{-# NOINLINE unsafeNewIORef #-}
1196+unsafeNewIORef :: a -> b -> IORef b
1197+unsafeNewIORef a b = unsafePerformIO $ do
1201+instance HasSpiderTimeline x => Functor (Event x) where
1202+ fmap f = push $ return . Just . f
1204+instance Functor (Behavior x) where
1205+ fmap f = pull . fmap f . readBehaviorTracked
1208+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1209+push f e = cacheEvent (pushCheap f e)
1211+{-# INLINABLE pull #-}
1212+pull :: BehaviorM x a -> Behavior x a
1213+pull a = behaviorPull $ Pull
1215+ , pullValue = unsafeNewIORef a Nothing
1216+#ifdef DEBUG_NODEIDS
1217+ , pullNodeId = unsafeNodeId a
1221+{-# INLINABLE switch #-}
1222+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1223+switch a = eventSwitch $ Switch
1225+ , switchSubscribed = unsafeNewIORef a Nothing
1228+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1229+coincidence a = eventCoincidence $ Coincidence
1230+ { coincidenceParent = a
1231+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1234+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1235+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1236+run roots after = do
1237+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1238+ t <- SpiderHost ask
1239+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1240+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1241+ occBefore <- liftIO $ do
1242+ occBefore <- readIORef occRef
1243+ writeIORef occRef $! DMap.insert k a occBefore
1245+ if DMap.null occBefore
1246+ then do scheduleRootClear occRef
1248+ else return Nothing
1249+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1250+ propagate a subscribersRef
1251+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1253+ delayed <- liftIO $ readIORef delayedRef
1254+ case IntMap.minViewWithKey delayed of
1255+ Nothing -> return ()
1256+ Just ((currentHeight, cur), future) -> do
1257+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1258+ putCurrentHeight $ Height currentHeight
1259+ liftIO $ writeIORef delayedRef $! future
1263+ putCurrentHeight maxBound
1265+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1268+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1269+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1270+ height <- liftIO $ readIORef heightRef
1271+ currentHeight <- getCurrentHeight
1272+ case height `compare` currentHeight of
1273+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1274+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1277+data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1279+data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1281+data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1283+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1285+debugFinalize :: Bool
1286+debugFinalize = False
1288+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1289+mkWeakPtrWithDebug x debugNote = do
1293+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1296+type WeakList a = [Weak a]
1298+{-# INLINE withIncreasedDepth #-}
1300+withIncreasedDepth :: CanTrace x m => m a -> m a
1301+withIncreasedDepth a = do
1302+ spiderTimeline <- askSpiderTimelineEnv
1303+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1305+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1308+withIncreasedDepth :: m a -> m a
1309+withIncreasedDepth = id
1312+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1314+{-# INLINE tracePropagate #-}
1315+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1316+tracePropagate p = traceWhen p debugPropagate
1318+{-# INLINE traceInvalidate #-}
1319+traceInvalidate :: String -> IO ()
1320+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1322+{-# INLINE traceWhen #-}
1323+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1324+traceWhen p b message = traceMWhen p b $ return message
1326+{-# INLINE traceMWhen #-}
1327+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1328+traceMWhen _ b getMessage = when b $ do
1329+ message <- getMessage
1331+ spiderTimeline <- askSpiderTimelineEnv
1332+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1336+ liftIO $ putStrLn $ replicate d ' ' <> message
1338+whoCreatedIORef :: IORef a -> IO [String]
1339+whoCreatedIORef (IORef a) = whoCreated $! a
1342+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1345+ (x :| xs) : t -> case groupByHead t of
1346+ [] -> [(x, xs :| [])]
1348+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1349+ | otherwise -> (x, xs :| []) : l
1351+listsToForest :: Eq a => [[a]] -> Forest a
1352+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1355+{-# INLINE propagateSubscriberHold #-}
1356+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1357+propagateSubscriberHold h a = do
1358+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1359+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1360+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1361+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1362+ case {-# SCC "apply" #-} apply a v of
1363+ Nothing -> return ()
1365+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1366+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1367+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1368+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1370+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1372+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1373+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1375+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1377+ (!m, _) <- BehaviorM ask
1379+ Nothing -> return Nothing
1380+ Just (!wi, _) -> return $ Just wi
1382+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1384+ (!m, _) <- BehaviorM ask
1386+ Nothing -> return Nothing
1387+ Just (_, !p) -> return $ Just p
1389+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1390+askBehaviorHoldInits = do
1391+ (_, !his) <- BehaviorM ask
1394+{-# INLINE getDynHold #-}
1395+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1397+ mh <- liftIO $ readIORef $ unDyn d
1399+ Right h -> return h
1400+ Left (readV0, v') -> do
1401+ holdInits <- getDeferralQueue
1402+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1404+ liftIO $ writeIORef (unDyn d) $ Right h
1407+-- Always refers to 0
1408+{-# NOINLINE zeroRef #-}
1409+zeroRef :: IORef Height
1410+zeroRef = unsafePerformIO $ newIORef zeroHeight
1412+type CanSubscribe x m =
1413+ ( HasSpiderTimeline x
1414+ , HasCurrentHeight x m
1415+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1416+ , Defer SomeClear m -- Wiping out event firings
1417+ , Defer SomeIntClear m
1418+ , Defer (SomeAssignment x) m -- Updating state
1419+ , Defer (SomeResetCoincidence x) m
1423+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1424+getRootSubscribed k r sub = do
1425+ mSubscribed <- readIORef $ rootSubscribed r
1426+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1427+ case DMap.lookup k mSubscribed of
1428+ Just subscribed -> {-# SCC "hitRoot" #-} do
1429+ sln <- subscribeRootSubscribed subscribed sub
1431+ return (sln, subscribed, occ)
1432+ Nothing -> {-# SCC "missRoot" #-} do
1433+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1434+ let !cached = rootSubscribed r
1435+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1436+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1437+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1438+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1439+ writeIORef uninitRef $! uninit
1440+ let !subscribed = RootSubscribed
1441+ { rootSubscribedKey = k
1442+ , rootSubscribedCachedSubscribed = cached
1443+ , rootSubscribedOccurrence = getOcc
1444+ , rootSubscribedSubscribers = subs
1445+ , rootSubscribedUninit = uninit
1446+ , rootSubscribedWeakSelf = weakSelf
1447+#ifdef DEBUG_NODEIDS
1448+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1451+ -- If we die at the same moment that all our children die, they will
1452+ -- try to clean us up but will fail because their Weak reference to us
1453+ -- will also be dead. So, if we are dying, check if there are any
1454+ -- children; since children don't bother cleaning themselves up if
1455+ -- their parents are already dead, I don't think there's a race
1456+ -- condition here. However, if there are any children, then we can
1457+ -- infer that we need to clean ourselves up, so we do.
1459+ cs <- readIORef $ _weakBag_children subs
1460+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1461+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1462+ 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
1464+ return (sln, subscribed, occ)
1466+#ifdef USE_TEMPLATE_HASKELL
1467+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1469+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1470+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1471+ rootSubscribedUninit self
1472+ modifyIORef' cached $ DMap.delete k
1474+{-# INLINE subscribeRootSubscribed #-}
1475+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1476+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1478+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1480+data FanInt x a = FanInt
1481+ { _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
1482+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1483+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1486+newFanInt :: IO (FanInt x a)
1488+ 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
1489+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1490+ occRef <- newIORef $ error "fanInt: no occurrence"
1492+ { _fanInt_subscribers = subscribers
1493+ , _fanInt_subscriptionRef = subscriptionRef
1494+ , _fanInt_occRef = occRef
1497+{-# NOINLINE unsafeNewFanInt #-}
1498+unsafeNewFanInt :: b -> FanInt x a
1499+unsafeNewFanInt b = unsafePerformIO $ do
1503+{-# NOINLINE fanInt #-}
1504+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1506+ let self = unsafeNewFanInt p
1507+ in EventSelectorInt $ \k -> Event $ \sub -> do
1508+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1509+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1510+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1511+ { subscriberPropagate = \m -> do
1512+ liftIO $ writeIORef (_fanInt_occRef self) m
1513+ scheduleIntClear $ _fanInt_occRef self
1514+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do
1515+ FastWeakBag.traverse b $ \s -> do
1516+ subscriberPropagate s v
1517+ , subscriberInvalidateHeight = \old -> do
1518+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1519+ FastWeakBag.traverse b $ \s -> do
1520+ subscriberInvalidateHeight s old
1521+ , subscriberRecalculateHeight = \new -> do
1522+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1523+ FastWeakBag.traverse b $ \s -> do
1524+ subscriberRecalculateHeight s new
1527+ writeIORef (_fanInt_subscriptionRef self) subscription
1528+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1529+ scheduleIntClear $ _fanInt_occRef self
1531+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1533+ b <- FastWeakBag.empty
1534+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1537+ t <- liftIO $ FastWeakBag.insert sub b
1538+ currentOcc <- readIORef (_fanInt_occRef self)
1539+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1540+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
1542+{-# INLINABLE getFanSubscribed #-}
1543+getFanSubscribed :: (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x, GCompare k) => k a -> Fan x k -> Subscriber x a -> m (WeakBagTicket, FanSubscribed x k, Maybe a)
1544+getFanSubscribed k f sub = do
1545+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1546+ case mSubscribed of
1547+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1548+ sln <- subscribeFanSubscribed k subscribed sub
1549+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1550+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1551+ Nothing -> {-# SCC "missFan" #-} do
1552+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1553+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1554+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1555+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1556+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1557+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1558+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1559+ occRef <- liftIO $ newIORef parentOcc
1560+ when (isJust parentOcc) $ scheduleClear occRef
1561+ let subscribed = FanSubscribed
1562+ { fanSubscribedCachedSubscribed = fanSubscribed f
1563+ , fanSubscribedOccurrence = occRef
1564+ , fanSubscribedParent = subscription
1565+ , fanSubscribedSubscribers = subscribersRef
1566+#ifdef DEBUG_NODEIDS
1567+ , fanSubscribedNodeId = unsafeNodeId f
1570+ let !self = (k, subscribed)
1571+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1572+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1573+ liftIO $ writeIORef subscribedRef $! subscribed
1574+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1575+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1577+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1578+cleanupFanSubscribed (k, subscribed) = do
1579+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1580+ let reducedSubscribers = DMap.delete k subscribers
1581+ if DMap.null reducedSubscribers
1583+ unsubscribe $ fanSubscribedParent subscribed
1584+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1585+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1586+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1588+{-# INLINE subscribeFanSubscribed #-}
1589+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1590+subscribeFanSubscribed k subscribed sub = do
1591+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1592+ case DMap.lookup k subscribers of
1593+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1594+ let !self = (k, subscribed)
1595+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1596+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1597+ 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
1599+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1601+{-# INLINABLE getSwitchSubscribed #-}
1602+getSwitchSubscribed :: (Defer (SomeHoldInit x) m, Defer (SomeAssignment x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, Defer (SomeResetCoincidence x) m, HasCurrentHeight x m, HasSpiderTimeline x, m ~ EventM x) => Switch x a -> Subscriber x a -> m (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1603+getSwitchSubscribed s sub = do
1604+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1605+ case mSubscribed of
1606+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1607+ sln <- subscribeSwitchSubscribed subscribed sub
1608+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1609+ return (sln, subscribed, occ)
1610+ Nothing -> {-# SCC "missSwitch" #-} do
1611+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1612+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1613+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1614+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1615+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1616+ wiRef <- liftIO $ newIORef wi
1617+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1618+ holdInits <- getDeferralQueue
1619+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1620+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1621+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1622+ subscriptionRef <- liftIO $ newIORef subscription
1623+ occRef <- liftIO $ newIORef parentOcc
1624+ when (isJust parentOcc) $ scheduleClear occRef
1625+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1626+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1627+ let !subscribed = SwitchSubscribed
1628+ { switchSubscribedCachedSubscribed = switchSubscribed s
1629+ , switchSubscribedOccurrence = occRef
1630+ , switchSubscribedHeight = heightRef
1631+ , switchSubscribedSubscribers = subs
1632+ , switchSubscribedOwnInvalidator = i
1633+ , switchSubscribedOwnWeakInvalidator = wiRef
1634+ , switchSubscribedBehaviorParents = parentsRef
1635+ , switchSubscribedParent = switchParent s
1636+ , switchSubscribedCurrentParent = subscriptionRef
1637+ , switchSubscribedWeakSelf = weakSelf
1638+#ifdef DEBUG_NODEIDS
1639+ , switchSubscribedNodeId = unsafeNodeId s
1642+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1643+ liftIO $ writeIORef subscribedRef $! subscribed
1644+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1645+ return (slnForSub, subscribed, parentOcc)
1647+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1648+cleanupSwitchSubscribed subscribed = do
1649+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1650+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1651+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1653+{-# INLINE subscribeSwitchSubscribed #-}
1654+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1655+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1657+{-# INLINABLE getCoincidenceSubscribed #-}
1658+getCoincidenceSubscribed :: forall x a m. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x, m ~ EventM x) => Coincidence x a -> Subscriber x a -> m (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1659+getCoincidenceSubscribed c sub = do
1660+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1661+ case mSubscribed of
1662+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1663+ sln <- subscribeCoincidenceSubscribed subscribed sub
1664+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1665+ return (sln, subscribed, occ)
1666+ Nothing -> {-# SCC "missCoincidence" #-} do
1667+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1668+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1669+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1670+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1671+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1672+ (occ, height, mInnerSubd) <- case outerOcc of
1673+ Nothing -> return (Nothing, outerHeight, Nothing)
1675+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1676+ return (occ, height, Just innerSubd)
1677+ occRef <- liftIO $ newIORef occ
1678+ when (isJust occ) $ scheduleClear occRef
1679+ heightRef <- liftIO $ newIORef height
1680+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1681+ scheduleClear innerSubdRef
1682+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1683+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1684+ let subscribed = CoincidenceSubscribed
1685+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1686+ , coincidenceSubscribedOccurrence = occRef
1687+ , coincidenceSubscribedHeight = heightRef
1688+ , coincidenceSubscribedSubscribers = subs
1689+ , coincidenceSubscribedOuter = subOuter
1690+ , coincidenceSubscribedOuterParent = outerSubscription
1691+ , coincidenceSubscribedInnerParent = innerSubdRef
1692+ , coincidenceSubscribedWeakSelf = weakSelf
1693+#ifdef DEBUG_NODEIDS
1694+ , coincidenceSubscribedNodeId = unsafeNodeId c
1697+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1698+ liftIO $ writeIORef subscribedRef $! subscribed
1699+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1700+ return (slnForSub, subscribed, occ)
1702+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1703+cleanupCoincidenceSubscribed subscribed = do
1704+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1705+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1707+{-# INLINE subscribeCoincidenceSubscribed #-}
1708+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1709+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1711+{-# INLINE merge #-}
1712+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1713+merge d = cacheEvent (mergeCheap d)
1715+{-# INLINE mergeWithMove #-}
1716+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1717+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1719+{-# INLINE [1] mergeCheap #-}
1720+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1721+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1723+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1724+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1725+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1726+ (mOldSubd, newPs) <- case me of
1727+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1729+ let s = subscriber $ return k
1730+ subscription@(EventSubscription _ subd) <- subscribe e s
1731+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1732+ let newParent = MergeSubscribedParent subscription
1733+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1734+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1735+ forM_ mOldSubd $ \oldSubd -> do
1736+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1737+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1738+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1739+ foldM f ([], oldParents) $ DMap.toList p
1740+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1741+ getInitialSubscribers initialParents subscriber = do
1742+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1743+ let s = subscriber $ return k
1744+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1745+ height <- liftIO $ getEventSubscribedHeight parentSubd
1746+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1747+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1748+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1749+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1751+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1752+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1754+{-# INLINE [1] mergeCheapWithMove #-}
1755+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1756+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1758+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1759+ updateMe subscriber heightBagRef oldParents p = do
1760+ -- Prepare new parents for insertion
1761+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1762+ subscribeParent k e = do
1763+ keyRef <- liftIO $ newIORef k
1764+ let s = subscriber $ liftIO $ readIORef keyRef
1765+ subscription@(EventSubscription _ subd) <- subscribe e s
1767+ newParentHeight <- getEventSubscribedHeight subd
1768+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1769+ return $ MergeSubscribedParentWithMove subscription keyRef
1770+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1771+ -- Collect old parents for deletion and update the keys of moved parents
1772+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1773+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1775+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1776+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1777+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1779+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1781+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1782+ return (toDelete, applyAlways p' oldParents)
1783+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1784+ getInitialSubscribers initialParents subscriber = do
1785+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1786+ keyRef <- liftIO $ newIORef k
1787+ let s = subscriber $ liftIO $ readIORef keyRef
1788+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1789+ height <- liftIO $ getEventSubscribedHeight parentSubd
1790+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1791+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1792+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1793+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1795+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1796+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1798+type MergeUpdateFunc k x p s
1799+ = (forall a. EventM x (k a) -> Subscriber x a)
1803+ -> EventM x ([EventSubscription x], DMap k s)
1805+type MergeInitFunc k x s
1807+ -> (forall a. EventM x (k a) -> Subscriber x a)
1808+ -> EventM x (DMap k Identity, [Height], DMap k s)
1810+type MergeDestroyFunc k s
1814+data Merge x k s = Merge
1815+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1816+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1817+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1818+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1819+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1822+invalidateMergeHeight :: Merge x k s -> IO ()
1823+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1825+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1826+invalidateMergeHeight' heightRef sub = do
1827+ oldHeight <- readIORef heightRef
1828+ 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
1829+ writeIORef heightRef $! invalidHeight
1830+ subscriberInvalidateHeight sub oldHeight
1833+revalidateMergeHeight :: Merge x k s -> IO ()
1834+revalidateMergeHeight m = do
1835+ currentHeight <- readIORef $ _merge_heightRef m
1836+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1837+ heights <- readIORef $ _merge_heightBagRef m
1838+ parents <- readIORef $ _merge_parentsRef m
1839+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1840+ case heightBagSize heights `compare` DMap.size parents of
1843+ let height = succHeight $ heightBagMax heights
1844+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1845+ writeIORef (_merge_heightRef m) $! height
1846+ subscriberRecalculateHeight (_merge_sub m) height
1847+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1849+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1850+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1851+ vals <- liftIO $ readIORef $ _merge_accumRef m
1852+ 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
1853+ --TODO: Assert that m is not empty
1854+ subscriberPropagate (_merge_sub m) vals
1856+mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1857+mergeSubscriber m getKey = Subscriber
1858+ { subscriberPropagate = \a -> do
1859+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1861+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1862+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1863+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1864+ when (DMap.null oldM) $ do -- Only schedule the firing once
1865+ height <- liftIO $ readIORef $ _merge_heightRef m
1866+ --TODO: assertions about height
1867+ currentHeight <- getCurrentHeight
1868+ when (height <= currentHeight) $ do
1869+ if height /= invalidHeight
1871+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1872+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1875+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1876+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1877+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1881+ error $ "Causality loop found" <> cycleInfo
1882+ scheduleMergeSelf m height
1883+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1884+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1885+ invalidateMergeHeight m
1886+ , subscriberRecalculateHeight = \new -> do
1887+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1888+ revalidateMergeHeight m
1891+--TODO: Be able to run as much of this as possible promptly
1892+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1893+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1894+ where updateMe = do
1895+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1896+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1897+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1898+ return subscriptionsToKill
1900+{-# INLINE mergeCheap' #-}
1901+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)
1902+mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1903+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1904+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1905+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1906+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1907+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1909+ { _merge_parentsRef = parentsRef
1910+ , _merge_heightBagRef = heightBagRef
1911+ , _merge_heightRef = heightRef
1913+ , _merge_accumRef = accumRef
1915+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1916+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1917+ myHeight = if invalidHeight `elem` heights
1919+ else succHeight $ heightBagMax myHeightBag
1920+ currentHeight <- getCurrentHeight
1921+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1922+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1924+ unless (DMap.null accum) $ do
1925+ scheduleMergeSelf m myHeight
1926+ liftIO $ writeIORef accumRef $! accum
1927+ liftIO $ writeIORef heightRef $! myHeight
1928+ liftIO $ writeIORef heightBagRef $! myHeightBag
1929+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1930+ liftIO $ writeIORef parentsRef $! initialParentState
1931+ defer $ SomeMergeInit $ do
1933+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1934+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1935+ defer $ updateMerge m updateFunc a
1936+ , subscriberInvalidateHeight = \_ -> return ()
1937+ , subscriberRecalculateHeight = \_ -> return ()
1939+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1940+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1941+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1942+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1943+ -- its subscription.
1944+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1945+ let unsubscribeAll = destroy =<< readIORef parentsRef
1946+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1950+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1951+mergeInt = cacheEvent . mergeIntCheap
1953+{-# INLINABLE mergeIntCheap #-}
1954+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1955+mergeIntCheap d = Event $ \sub -> do
1956+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1957+ accum <- liftIO $ FastMutableIntMap.newEmpty
1958+ heightRef <- liftIO $ newIORef zeroHeight
1959+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1960+ parents <- liftIO $ FastMutableIntMap.newEmpty
1961+ let scheduleSelf = do
1962+ height <- liftIO $ readIORef $ heightRef
1963+ scheduleMerge' height heightRef $ do
1964+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1965+ subscriberPropagate sub vals
1966+ invalidateMyHeight = do
1967+ invalidateMergeHeight' heightRef sub
1968+ recalculateMyHeight = do
1969+ currentHeight <- readIORef heightRef
1970+ 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?
1971+ heights <- readIORef heightBagRef
1972+ numParents <- FastMutableIntMap.size parents
1973+ case heightBagSize heights `compare` numParents of
1976+ let height = succHeight $ heightBagMax heights
1977+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1978+ writeIORef heightRef $! height
1979+ subscriberRecalculateHeight sub height
1980+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1981+ mySubscriber k = Subscriber
1982+ { subscriberPropagate = \a -> do
1983+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1984+ liftIO $ FastMutableIntMap.insert accum k a
1985+ when wasEmpty scheduleSelf
1986+ , subscriberInvalidateHeight = \old -> do
1987+ modifyIORef' heightBagRef $ heightBagRemove old
1989+ , subscriberRecalculateHeight = \new -> do
1990+ modifyIORef' heightBagRef $ heightBagAdd new
1991+ recalculateMyHeight
1993+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1994+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1996+ forM_ parentOcc $ FastMutableIntMap.insert accum k
1997+ FastMutableIntMap.insert parents k subscription
1998+ height <- getEventSubscribedHeight parentSubd
1999+ if height == invalidHeight
2000+ then writeIORef heightRef invalidHeight
2002+ modifyIORef' heightBagRef $ heightBagAdd height
2003+ modifyIORef' heightRef $ \oldHeight ->
2004+ if oldHeight == invalidHeight
2006+ else max (succHeight height) oldHeight
2007+ myHeight <- liftIO $ readIORef heightRef
2008+ currentHeight <- getCurrentHeight
2009+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
2010+ occ <- if currentHeight >= myHeight -- If we should have fired by now
2012+ then return Nothing
2013+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
2014+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
2016+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
2017+ defer $ SomeMergeInit $ do
2018+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
2021+ let f k newParent = do
2022+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
2023+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
2024+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
2025+ return subscription
2026+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
2027+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
2028+ liftIO $ for_ oldParents $ \oldParent -> do
2029+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
2030+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
2031+ return $ IntMap.elems oldParents
2033+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
2034+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
2036+ , subscriberInvalidateHeight = \_ -> return ()
2037+ , subscriberRecalculateHeight = \_ -> return ()
2039+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
2040+ forM_ change $ \c -> defer $ updateMe c
2041+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2042+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2043+ -- its subscription.
2044+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2045+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2046+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2050+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2052+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2056+ , fanSubscribed = unsafeNewIORef e Nothing
2058+ in EventSelector $ \k -> eventFan k f
2060+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2061+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2062+ holdInits <- liftIO $ readIORef holdInitRef
2063+ dynInits <- liftIO $ readIORef dynInitRef
2064+ mergeInits <- liftIO $ readIORef mergeInitRef
2065+ unless (null holdInits && null dynInits && null mergeInits) $ do
2066+ liftIO $ writeIORef holdInitRef []
2067+ liftIO $ writeIORef dynInitRef []
2068+ liftIO $ writeIORef mergeInitRef []
2069+ mapM_ initHold holdInits
2070+ mapM_ initDyn dynInits
2071+ mapM_ unSomeMergeInit mergeInits
2072+ runHoldInits holdInitRef dynInitRef mergeInitRef
2074+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2075+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2077+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2078+initDyn (SomeDynInit d) = void $ getDynHold d
2080+newEventEnv :: IO (EventEnv x)
2082+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2083+ holdInitRef <- newIORef []
2084+ dynInitRef <- newIORef []
2085+ mergeUpdateRef <- newIORef []
2086+ mergeInitRef <- newIORef []
2087+ heightRef <- newIORef zeroHeight
2088+ toClearRef <- newIORef []
2089+ toClearIntRef <- newIORef []
2090+ toClearRootRef <- newIORef []
2091+ coincidenceInfosRef <- newIORef []
2092+ delayedRef <- newIORef IntMap.empty
2093+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2095+clearEventEnv :: EventEnv x -> IO ()
2096+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2097+ writeIORef toAssignRef []
2098+ writeIORef holdInitRef []
2099+ writeIORef dynInitRef []
2100+ writeIORef mergeUpdateRef []
2101+ writeIORef mergeInitRef []
2102+ writeIORef heightRef zeroHeight
2103+ writeIORef toClearRef []
2104+ writeIORef toClearIntRef []
2105+ writeIORef toClearRootRef []
2106+ writeIORef coincidenceInfosRef []
2107+ writeIORef delayedRef IntMap.empty
2109+-- | Run an event action outside of a frame
2110+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2111+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
2112+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2115+ 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
2117+ result <- runEventM go
2118+ toClear <- readIORef $ eventEnvClears env
2119+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2120+ toClearInt <- readIORef $ eventEnvIntClears env
2121+ forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2122+ toClearRoot <- readIORef $ eventEnvRootClears env
2123+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2124+ toAssign <- readIORef $ eventEnvAssignments env
2125+ toReconnectRef <- newIORef []
2126+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2127+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2129+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2130+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2131+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2132+ writeIORef (eventEnvMergeUpdates env) []
2133+ when debugPropagate $ putStrLn "Updating merges"
2134+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2135+ when debugPropagate $ putStrLn "Updating merges done"
2136+ toReconnect <- readIORef toReconnectRef
2138+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2139+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2140+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2141+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2143+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2144+ wi' <- mkWeakPtrWithDebug i "wi'"
2145+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2146+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2147+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2148+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2149+ 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
2150+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2151+ sub <- newSubscriberSwitch subscribed
2152+ 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
2154+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2155+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2156+ EventRoot _ -> "EventRoot"
2157+ EventNever -> "EventNever"
2158+ _ -> "something else"
2160+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2161+ return oldSubscription
2162+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2163+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2164+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2165+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2166+ parentHeight <- getEventSubscribedHeight subd'
2167+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2168+ when (parentHeight /= myHeight) $ do
2169+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2170+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2171+ 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
2172+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2173+ unsubscribe subscription
2174+ mapM_ invalidateCoincidenceHeight mcs
2175+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2176+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2177+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2178+ height <- calculateSwitchHeight subscribed
2179+ updateSwitchHeight height subscribed
2182+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2184+{-# INLINE zeroHeight #-}
2185+zeroHeight :: Height
2186+zeroHeight = Height 0
2188+{-# INLINE invalidHeight #-}
2189+invalidHeight :: Height
2190+invalidHeight = Height (-1000)
2193+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2194+{-# INLINE invalidHeightBeingTraversed #-}
2195+invalidHeightBeingTraversed :: Height
2196+invalidHeightBeingTraversed = Height (-1001)
2199+{-# INLINE succHeight #-}
2200+succHeight :: Height -> Height
2201+succHeight h@(Height a) =
2202+ if h == invalidHeight
2204+ else Height $ succ a
2206+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2207+invalidateCoincidenceHeight subscribed = do
2208+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2209+ when (oldHeight /= invalidHeight) $ do
2210+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2211+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2213+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2214+updateSwitchHeight new subscribed = do
2215+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2216+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2217+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2218+ writeIORef (switchSubscribedHeight subscribed) $! new
2219+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2221+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2222+recalculateCoincidenceHeight subscribed = do
2223+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2224+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2225+ height <- calculateCoincidenceHeight subscribed
2226+ when (height /= invalidHeight) $ do
2227+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2228+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2230+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2231+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2233+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2234+calculateCoincidenceHeight subscribed = do
2235+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2236+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2237+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2239+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2241+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2242+invalidate toReconnectRef wis = do
2243+ forM_ wis $ \wi -> do
2247+ traceInvalidate "invalidate Dead"
2248+ return () --TODO: Should we clean this up here?
2250+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2252+ InvalidatorPull p -> do
2253+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2254+ mVal <- readIORef $ pullValue p
2255+ forM_ mVal $ \val -> do
2256+ writeIORef (pullValue p) Nothing
2257+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2258+ InvalidatorSwitch subscribed -> do
2259+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2260+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2261+ 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
2263+--------------------------------------------------------------------------------
2264+-- Reflex integration
2265+--------------------------------------------------------------------------------
2267+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2268+-- When we're specializing, we include this from Reflex.Class instead, because
2269+-- it needs access to these types; when we're not, we want them here, so our
2270+-- instance isn't an orphan instance.
2271+#include "SpiderTimeline.include.hs"
2272+#include "SpiderTimelineHost.include.hs"
2275+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2276+unsafeNewSpiderTimelineEnv = do
2280+ depthRef <- newIORef 0
2282+ return $ SpiderTimelineEnv
2283+ { _spiderTimeline_lock = lock
2284+ , _spiderTimeline_eventEnv = env
2286+ , _spiderTimeline_depth = depthRef
2290+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2291+-- | Create a new SpiderTimelineEnv
2292+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2293+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2295+data LocalSpiderTimeline x s
2297+instance Reifies s (SpiderTimelineEnv x) =>
2298+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2299+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2303+ -> SpiderTimelineEnv x
2304+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2305+localSpiderTimeline _ = unsafeCoerce
2307+-- | Pass a new timeline to the given function.
2308+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2309+withSpiderTimeline k = do
2310+ env <- unsafeNewSpiderTimelineEnv
2311+ reify env $ \s -> k $ localSpiderTimeline s env
2314+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2316+type ComputeM = EventM
2318+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2320+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2321+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2322+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2323+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2324+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2325+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2326+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2327+ type PullM (SpiderTimeline x) = SpiderPullM x
2328+ type PushM (SpiderTimeline x) = SpiderPushM x
2329+ {-# INLINABLE never #-}
2330+ never = SpiderEvent eventNever
2331+ {-# INLINABLE constant #-}
2332+ constant = SpiderBehavior . behaviorConst
2333+ {-# INLINE push #-}
2334+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2335+ {-# INLINE pushCheap #-}
2336+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2337+ {-# INLINABLE pull #-}
2338+ pull = SpiderBehavior . pull . coerce
2339+ {-# INLINABLE merge #-}
2340+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2341+ {-# INLINABLE fan #-}
2342+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2343+ {-# INLINABLE switch #-}
2344+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2345+ {-# INLINABLE coincidence #-}
2346+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2347+ {-# INLINABLE current #-}
2348+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2349+ {-# INLINABLE updated #-}
2350+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2351+ {-# INLINABLE unsafeBuildDynamic #-}
2352+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2353+ {-# INLINABLE unsafeBuildIncremental #-}
2354+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2355+ {-# INLINABLE mergeIncremental #-}
2356+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2357+ {-# INLINABLE mergeIncrementalWithMove #-}
2358+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2359+ {-# INLINABLE currentIncremental #-}
2360+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2361+ {-# INLINABLE updatedIncremental #-}
2362+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2363+ {-# INLINABLE incrementalToDynamic #-}
2364+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2365+ c <- readBehaviorUntracked $ dynamicCurrent i
2366+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2367+ eventCoercion Coercion = Coercion
2368+ behaviorCoercion Coercion = Coercion
2369+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2370+ {-# INLINABLE mergeIntIncremental #-}
2371+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2372+ {-# INLINABLE fanInt #-}
2373+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2376+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2378+data SpiderEventHandle x a = SpiderEventHandle
2379+ { spiderEventHandleSubscription :: EventSubscription x
2380+ , spiderEventHandleValue :: IORef (Maybe a)
2383+instance MonadRef (EventM x) where
2384+ type Ref (EventM x) = Ref IO
2385+ {-# INLINABLE newRef #-}
2386+ {-# INLINABLE readRef #-}
2387+ {-# INLINABLE writeRef #-}
2388+ newRef = liftIO . newRef
2389+ readRef = liftIO . readRef
2390+ writeRef r a = liftIO $ writeRef r a
2392+instance MonadAtomicRef (EventM x) where
2393+ {-# INLINABLE atomicModifyRef #-}
2394+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2396+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2397+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2399+instance Monad (SpiderHost x) where
2400+ {-# INLINABLE (>>=) #-}
2401+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2402+ {-# INLINABLE (>>) #-}
2403+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2404+ {-# INLINABLE return #-}
2405+ return x = SpiderHost $ return x
2406+ {-# INLINABLE fail #-}
2407+ fail s = SpiderHost $ fail s
2409+-- | Run an action affecting the global Spider timeline; this will be guarded by
2410+-- a mutex for that timeline
2411+runSpiderHost :: SpiderHost Global a -> IO a
2412+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2414+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2415+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2416+-- mutex for that timeline
2417+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2418+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2421+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2423+instance Monad (SpiderHostFrame x) where
2424+ {-# INLINABLE (>>=) #-}
2425+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2426+ {-# INLINABLE (>>) #-}
2427+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2428+ {-# INLINABLE return #-}
2429+ return x = SpiderHostFrame $ return x
2430+ {-# INLINABLE fail #-}
2431+ fail s = SpiderHostFrame $ fail s
2433+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2434+newEventWithTriggerIO f = do
2435+ es <- newFanEventWithTriggerIO $ \Refl -> f
2436+ return $ select es Refl
2438+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2439+newFanEventWithTriggerIO f = do
2440+ occRef <- newIORef DMap.empty
2441+ subscribedRef <- newIORef DMap.empty
2443+ { rootOccurrence = occRef
2444+ , rootSubscribed = subscribedRef
2447+ return $ EventSelector $ \k -> eventRoot k r
2449+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2451+instance MonadRef (SpiderHost x) where
2452+ type Ref (SpiderHost x) = Ref IO
2453+ newRef = SpiderHost . newRef
2454+ readRef = SpiderHost . readRef
2455+ writeRef r = SpiderHost . writeRef r
2457+instance MonadAtomicRef (SpiderHost x) where
2458+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2460+instance MonadRef (SpiderHostFrame x) where
2461+ type Ref (SpiderHostFrame x) = Ref IO
2462+ newRef = SpiderHostFrame . newRef
2463+ readRef = SpiderHostFrame . readRef
2464+ writeRef r = SpiderHostFrame . writeRef r
2466+instance MonadAtomicRef (SpiderHostFrame x) where
2467+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2469+instance PrimMonad (SpiderHostFrame x) where
2470+ type PrimState (SpiderHostFrame x) = PrimState IO
2471+ primitive = SpiderHostFrame . EventM . primitive