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