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