@@ -0,0 +1,2428 @@
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 _ b = unsafePerformIO $ newIORef b
1161+
1162+instance HasSpiderTimeline x => Functor (Event x) where
1163+ fmap f = push $ return . Just . f
1164+
1165+instance Functor (Behavior x) where
1166+ fmap f = pull . fmap f . readBehaviorTracked
1167+
1168+{-# INLINE push #-}
1169+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1170+push f e = cacheEvent (pushCheap f e)
1171+
1172+{-# INLINABLE pull #-}
1173+pull :: BehaviorM x a -> Behavior x a
1174+pull a = behaviorPull $ Pull
1175+ { pullCompute = a
1176+ , pullValue = unsafeNewIORef a Nothing
1177+#ifdef DEBUG_NODEIDS
1178+ , pullNodeId = unsafeNodeId a
1179+#endif
1180+ }
1181+
1182+{-# INLINABLE switch #-}
1183+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1184+switch a = eventSwitch $ Switch
1185+ { switchParent = a
1186+ , switchSubscribed = unsafeNewIORef a Nothing
1187+ }
1188+
1189+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1190+coincidence a = eventCoincidence $ Coincidence
1191+ { coincidenceParent = a
1192+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1193+ }
1194+
1195+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1196+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1197+run roots after = do
1198+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1199+ t <- SpiderHost ask
1200+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1201+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1202+ occBefore <- liftIO $ do
1203+ occBefore <- readIORef occRef
1204+ writeIORef occRef $! DMap.insert k a occBefore
1205+ return occBefore
1206+ if DMap.null occBefore
1207+ then do scheduleRootClear occRef
1208+ return $ Just r
1209+ else return Nothing
1210+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1211+ propagate a subscribersRef
1212+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1213+ let go = do
1214+ delayed <- liftIO $ readIORef delayedRef
1215+ case IntMap.minViewWithKey delayed of
1216+ Nothing -> return ()
1217+ Just ((currentHeight, cur), future) -> do
1218+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1219+ putCurrentHeight $ Height currentHeight
1220+ liftIO $ writeIORef delayedRef $! future
1221+ sequence_ cur
1222+ go
1223+ go
1224+ putCurrentHeight maxBound
1225+ after
1226+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1227+ return result
1228+
1229+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1230+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1231+ height <- liftIO $ readIORef heightRef
1232+ currentHeight <- getCurrentHeight
1233+ case height `compare` currentHeight of
1234+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1235+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1236+ EQ -> a
1237+
1238+data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1239+
1240+data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1241+
1242+data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1243+
1244+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1245+
1246+debugFinalize :: Bool
1247+debugFinalize = False
1248+
1249+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1250+mkWeakPtrWithDebug x debugNote = do
1251+ x' <- evaluate x
1252+ mkWeakPtr x' $
1253+ if debugFinalize
1254+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1255+ else Nothing
1256+
1257+type WeakList a = [Weak a]
1258+
1259+{-# INLINE withIncreasedDepth #-}
1260+#ifdef DEBUG
1261+withIncreasedDepth :: CanTrace x m => m a -> m a
1262+withIncreasedDepth a = do
1263+ spiderTimeline <- askSpiderTimelineEnv
1264+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1265+ result <- a
1266+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1267+ return result
1268+#else
1269+withIncreasedDepth :: m a -> m a
1270+withIncreasedDepth = id
1271+#endif
1272+
1273+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1274+
1275+{-# INLINE tracePropagate #-}
1276+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1277+tracePropagate p = traceWhen p debugPropagate
1278+
1279+{-# INLINE traceInvalidate #-}
1280+traceInvalidate :: String -> IO ()
1281+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1282+
1283+{-# INLINE traceWhen #-}
1284+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1285+traceWhen p b message = traceMWhen p b $ return message
1286+
1287+{-# INLINE traceMWhen #-}
1288+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1289+traceMWhen _ b getMessage = when b $ do
1290+ message <- getMessage
1291+#ifdef DEBUG
1292+ spiderTimeline <- askSpiderTimelineEnv
1293+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1294+#else
1295+ let d = 0
1296+#endif
1297+ liftIO $ putStrLn $ replicate d ' ' <> message
1298+
1299+whoCreatedIORef :: IORef a -> IO [String]
1300+whoCreatedIORef (IORef a) = whoCreated $! a
1301+
1302+#ifdef DEBUG_CYCLES
1303+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1304+groupByHead = \case
1305+ [] -> []
1306+ (x :| xs) : t -> case groupByHead t of
1307+ [] -> [(x, xs :| [])]
1308+ l@((y, yss) : t')
1309+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1310+ | otherwise -> (x, xs :| []) : l
1311+
1312+listsToForest :: Eq a => [[a]] -> Forest a
1313+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1314+#endif
1315+
1316+{-# INLINE propagateSubscriberHold #-}
1317+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1318+propagateSubscriberHold h a = do
1319+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1320+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1321+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1322+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1323+ case {-# SCC "apply" #-} apply a v of
1324+ Nothing -> return ()
1325+ Just v' -> do
1326+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1327+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1328+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1329+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1330+
1331+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1332+
1333+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1334+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1335+
1336+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1337+askInvalidator = do
1338+ (!m, _) <- BehaviorM ask
1339+ case m of
1340+ Nothing -> return Nothing
1341+ Just (!wi, _) -> return $ Just wi
1342+
1343+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1344+askParentsRef = do
1345+ (!m, _) <- BehaviorM ask
1346+ case m of
1347+ Nothing -> return Nothing
1348+ Just (_, !p) -> return $ Just p
1349+
1350+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1351+askBehaviorHoldInits = do
1352+ (_, !his) <- BehaviorM ask
1353+ return his
1354+
1355+{-# INLINE getDynHold #-}
1356+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1357+getDynHold d = do
1358+ mh <- liftIO $ readIORef $ unDyn d
1359+ case mh of
1360+ Right h -> return h
1361+ Left (readV0, v') -> do
1362+ holdInits <- getDeferralQueue
1363+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1364+ h <- hold v0 v'
1365+ liftIO $ writeIORef (unDyn d) $ Right h
1366+ return h
1367+
1368+-- Always refers to 0
1369+{-# NOINLINE zeroRef #-}
1370+zeroRef :: IORef Height
1371+zeroRef = unsafePerformIO $ newIORef zeroHeight
1372+
1373+type CanSubscribe x m =
1374+ ( HasSpiderTimeline x
1375+ , HasCurrentHeight x m
1376+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1377+ , Defer SomeClear m -- Wiping out event firings
1378+ , Defer SomeIntClear m
1379+ , Defer (SomeAssignment x) m -- Updating state
1380+ , Defer (SomeResetCoincidence x) m
1381+ , m ~ EventM x
1382+ )
1383+
1384+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1385+getRootSubscribed k r sub = do
1386+ mSubscribed <- readIORef $ rootSubscribed r
1387+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1388+ case DMap.lookup k mSubscribed of
1389+ Just subscribed -> {-# SCC "hitRoot" #-} do
1390+ sln <- subscribeRootSubscribed subscribed sub
1391+ occ <- getOcc
1392+ return (sln, subscribed, occ)
1393+ Nothing -> {-# SCC "missRoot" #-} do
1394+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1395+ let !cached = rootSubscribed r
1396+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1397+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1398+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1399+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1400+ writeIORef uninitRef $! uninit
1401+ let !subscribed = RootSubscribed
1402+ { rootSubscribedKey = k
1403+ , rootSubscribedCachedSubscribed = cached
1404+ , rootSubscribedOccurrence = getOcc
1405+ , rootSubscribedSubscribers = subs
1406+ , rootSubscribedUninit = uninit
1407+ , rootSubscribedWeakSelf = weakSelf
1408+#ifdef DEBUG_NODEIDS
1409+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1410+#endif
1411+ }
1412+ -- If we die at the same moment that all our children die, they will
1413+ -- try to clean us up but will fail because their Weak reference to us
1414+ -- will also be dead. So, if we are dying, check if there are any
1415+ -- children; since children don't bother cleaning themselves up if
1416+ -- their parents are already dead, I don't think there's a race
1417+ -- condition here. However, if there are any children, then we can
1418+ -- infer that we need to clean ourselves up, so we do.
1419+ finalCleanup = do
1420+ cs <- readIORef $ _weakBag_children subs
1421+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1422+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1423+ 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
1424+ occ <- getOcc
1425+ return (sln, subscribed, occ)
1426+
1427+#ifdef USE_TEMPLATE_HASKELL
1428+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1429+#endif
1430+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1431+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1432+ rootSubscribedUninit self
1433+ modifyIORef' cached $ DMap.delete k
1434+
1435+{-# INLINE subscribeRootSubscribed #-}
1436+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1437+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1438+
1439+newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }
1440+
1441+data FanInt x a = FanInt
1442+ { _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
1443+ , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty
1444+ , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))
1445+ }
1446+
1447+newFanInt :: IO (FanInt x a)
1448+newFanInt = do
1449+ 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
1450+ subscriptionRef <- newIORef $ error "fanInt: no subscription"
1451+ occRef <- newIORef $ error "fanInt: no occurrence"
1452+ return $ FanInt
1453+ { _fanInt_subscribers = subscribers
1454+ , _fanInt_subscriptionRef = subscriptionRef
1455+ , _fanInt_occRef = occRef
1456+ }
1457+
1458+{-# NOINLINE unsafeNewFanInt #-}
1459+unsafeNewFanInt :: b -> FanInt x a
1460+unsafeNewFanInt _ = unsafePerformIO newFanInt
1461+
1462+{-# NOINLINE fanInt #-}
1463+fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1464+fanInt p =
1465+ let self = unsafeNewFanInt p
1466+ in EventSelectorInt $ \k -> Event $ \sub -> do
1467+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
1468+ when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
1469+ (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
1470+ { subscriberPropagate = \m -> do
1471+ liftIO $ writeIORef (_fanInt_occRef self) m
1472+ scheduleIntClear $ _fanInt_occRef self
1473+ FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do
1474+ FastWeakBag.traverse b $ \s -> do
1475+ subscriberPropagate s v
1476+ , subscriberInvalidateHeight = \old -> do
1477+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1478+ FastWeakBag.traverse b $ \s -> do
1479+ subscriberInvalidateHeight s old
1480+ , subscriberRecalculateHeight = \new -> do
1481+ FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1482+ FastWeakBag.traverse b $ \s -> do
1483+ subscriberRecalculateHeight s new
1484+ }
1485+ liftIO $ do
1486+ writeIORef (_fanInt_subscriptionRef self) subscription
1487+ writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc
1488+ scheduleIntClear $ _fanInt_occRef self
1489+ liftIO $ do
1490+ b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case
1491+ Nothing -> do
1492+ b <- FastWeakBag.empty
1493+ FastMutableIntMap.insert (_fanInt_subscribers self) k b
1494+ return b
1495+ Just b -> return b
1496+ t <- liftIO $ FastWeakBag.insert sub b
1497+ currentOcc <- readIORef (_fanInt_occRef self)
1498+ (EventSubscription _ (EventSubscribed !heightRef _)) <- readIORef (_fanInt_subscriptionRef self)
1499+ return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny $! _fanInt_subscriptionRef self, IntMap.lookup k currentOcc)
1500+
1501+{-# INLINABLE getFanSubscribed #-}
1502+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)
1503+getFanSubscribed k f sub = do
1504+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1505+ case mSubscribed of
1506+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1507+ sln <- subscribeFanSubscribed k subscribed sub
1508+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1509+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1510+ Nothing -> {-# SCC "missFan" #-} do
1511+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1512+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1513+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1514+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1515+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1516+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1517+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1518+ occRef <- liftIO $ newIORef parentOcc
1519+ when (isJust parentOcc) $ scheduleClear occRef
1520+ let subscribed = FanSubscribed
1521+ { fanSubscribedCachedSubscribed = fanSubscribed f
1522+ , fanSubscribedOccurrence = occRef
1523+ , fanSubscribedParent = subscription
1524+ , fanSubscribedSubscribers = subscribersRef
1525+#ifdef DEBUG_NODEIDS
1526+ , fanSubscribedNodeId = unsafeNodeId f
1527+#endif
1528+ }
1529+ let !self = (k, subscribed)
1530+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1531+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1532+ liftIO $ writeIORef subscribedRef $! subscribed
1533+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1534+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1535+
1536+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1537+cleanupFanSubscribed (k, subscribed) = do
1538+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1539+ let reducedSubscribers = DMap.delete k subscribers
1540+ if DMap.null reducedSubscribers
1541+ then do
1542+ unsubscribe $ fanSubscribedParent subscribed
1543+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1544+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1545+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1546+
1547+{-# INLINE subscribeFanSubscribed #-}
1548+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1549+subscribeFanSubscribed k subscribed sub = do
1550+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1551+ case DMap.lookup k subscribers of
1552+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1553+ let !self = (k, subscribed)
1554+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1555+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1556+ 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
1557+ return sln
1558+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1559+
1560+{-# INLINABLE getSwitchSubscribed #-}
1561+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)
1562+getSwitchSubscribed s sub = do
1563+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1564+ case mSubscribed of
1565+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1566+ sln <- subscribeSwitchSubscribed subscribed sub
1567+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1568+ return (sln, subscribed, occ)
1569+ Nothing -> {-# SCC "missSwitch" #-} do
1570+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1571+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1572+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1573+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1574+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1575+ wiRef <- liftIO $ newIORef wi
1576+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1577+ holdInits <- getDeferralQueue
1578+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1579+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1580+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1581+ subscriptionRef <- liftIO $ newIORef subscription
1582+ occRef <- liftIO $ newIORef parentOcc
1583+ when (isJust parentOcc) $ scheduleClear occRef
1584+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1585+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1586+ let !subscribed = SwitchSubscribed
1587+ { switchSubscribedCachedSubscribed = switchSubscribed s
1588+ , switchSubscribedOccurrence = occRef
1589+ , switchSubscribedHeight = heightRef
1590+ , switchSubscribedSubscribers = subs
1591+ , switchSubscribedOwnInvalidator = i
1592+ , switchSubscribedOwnWeakInvalidator = wiRef
1593+ , switchSubscribedBehaviorParents = parentsRef
1594+ , switchSubscribedParent = switchParent s
1595+ , switchSubscribedCurrentParent = subscriptionRef
1596+ , switchSubscribedWeakSelf = weakSelf
1597+#ifdef DEBUG_NODEIDS
1598+ , switchSubscribedNodeId = unsafeNodeId s
1599+#endif
1600+ }
1601+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1602+ liftIO $ writeIORef subscribedRef $! subscribed
1603+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1604+ return (slnForSub, subscribed, parentOcc)
1605+
1606+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1607+cleanupSwitchSubscribed subscribed = do
1608+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1609+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1610+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1611+
1612+{-# INLINE subscribeSwitchSubscribed #-}
1613+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1614+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1615+
1616+{-# INLINABLE getCoincidenceSubscribed #-}
1617+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)
1618+getCoincidenceSubscribed c sub = do
1619+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1620+ case mSubscribed of
1621+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1622+ sln <- subscribeCoincidenceSubscribed subscribed sub
1623+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1624+ return (sln, subscribed, occ)
1625+ Nothing -> {-# SCC "missCoincidence" #-} do
1626+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1627+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1628+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1629+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1630+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1631+ (occ, height, mInnerSubd) <- case outerOcc of
1632+ Nothing -> return (Nothing, outerHeight, Nothing)
1633+ Just o -> do
1634+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1635+ return (occ, height, Just innerSubd)
1636+ occRef <- liftIO $ newIORef occ
1637+ when (isJust occ) $ scheduleClear occRef
1638+ heightRef <- liftIO $ newIORef height
1639+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1640+ scheduleClear innerSubdRef
1641+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1642+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1643+ let subscribed = CoincidenceSubscribed
1644+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1645+ , coincidenceSubscribedOccurrence = occRef
1646+ , coincidenceSubscribedHeight = heightRef
1647+ , coincidenceSubscribedSubscribers = subs
1648+ , coincidenceSubscribedOuter = subOuter
1649+ , coincidenceSubscribedOuterParent = outerSubscription
1650+ , coincidenceSubscribedInnerParent = innerSubdRef
1651+ , coincidenceSubscribedWeakSelf = weakSelf
1652+#ifdef DEBUG_NODEIDS
1653+ , coincidenceSubscribedNodeId = unsafeNodeId c
1654+#endif
1655+ }
1656+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1657+ liftIO $ writeIORef subscribedRef $! subscribed
1658+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1659+ return (slnForSub, subscribed, occ)
1660+
1661+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1662+cleanupCoincidenceSubscribed subscribed = do
1663+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1664+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1665+
1666+{-# INLINE subscribeCoincidenceSubscribed #-}
1667+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1668+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1669+
1670+{-# INLINE merge #-}
1671+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1672+merge d = cacheEvent (mergeCheap d)
1673+
1674+{-# INLINE mergeWithMove #-}
1675+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1676+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1677+
1678+{-# INLINE [1] mergeCheap #-}
1679+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1680+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1681+ where
1682+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1683+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1684+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1685+ (mOldSubd, newPs) <- case me of
1686+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1687+ Just e -> do
1688+ let s = subscriber $ return k
1689+ subscription@(EventSubscription _ subd) <- subscribe e s
1690+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1691+ let newParent = MergeSubscribedParent subscription
1692+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1693+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1694+ forM_ mOldSubd $ \oldSubd -> do
1695+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1696+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1697+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1698+ foldM f ([], oldParents) $ DMap.toList p
1699+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1700+ getInitialSubscribers initialParents subscriber = do
1701+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1702+ let s = subscriber $ return k
1703+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1704+ height <- liftIO $ getEventSubscribedHeight parentSubd
1705+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1706+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1707+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1708+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1709+ )
1710+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1711+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1712+
1713+{-# INLINE [1] mergeCheapWithMove #-}
1714+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1715+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1716+ where
1717+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1718+ updateMe subscriber heightBagRef oldParents p = do
1719+ -- Prepare new parents for insertion
1720+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1721+ subscribeParent k e = do
1722+ keyRef <- liftIO $ newIORef k
1723+ let s = subscriber $ liftIO $ readIORef keyRef
1724+ subscription@(EventSubscription _ subd) <- subscribe e s
1725+ liftIO $ do
1726+ newParentHeight <- getEventSubscribedHeight subd
1727+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1728+ return $ MergeSubscribedParentWithMove subscription keyRef
1729+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1730+ -- Collect old parents for deletion and update the keys of moved parents
1731+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1732+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1733+ Nothing -> do
1734+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1735+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1736+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1737+ Just toKey -> do
1738+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1739+ return Nothing
1740+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1741+ return (toDelete, applyAlways p' oldParents)
1742+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1743+ getInitialSubscribers initialParents subscriber = do
1744+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1745+ keyRef <- liftIO $ newIORef k
1746+ let s = subscriber $ liftIO $ readIORef keyRef
1747+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1748+ height <- liftIO $ getEventSubscribedHeight parentSubd
1749+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1750+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1751+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1752+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1753+ )
1754+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1755+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1756+
1757+type MergeUpdateFunc k x p s
1758+ = (forall a. EventM x (k a) -> Subscriber x a)
1759+ -> IORef HeightBag
1760+ -> DMap k s
1761+ -> p
1762+ -> EventM x ([EventSubscription x], DMap k s)
1763+
1764+type MergeInitFunc k x s
1765+ = DMap k (Event x)
1766+ -> (forall a. EventM x (k a) -> Subscriber x a)
1767+ -> EventM x (DMap k Identity, [Height], DMap k s)
1768+
1769+type MergeDestroyFunc k s
1770+ = DMap k s
1771+ -> IO ()
1772+
1773+data Merge x k s = Merge
1774+ { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
1775+ , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
1776+ , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1777+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1778+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1779+ }
1780+
1781+invalidateMergeHeight :: Merge x k s -> IO ()
1782+invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
1783+
1784+invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
1785+invalidateMergeHeight' heightRef sub = do
1786+ oldHeight <- readIORef heightRef
1787+ 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
1788+ writeIORef heightRef $! invalidHeight
1789+ subscriberInvalidateHeight sub oldHeight
1790+
1791+
1792+revalidateMergeHeight :: Merge x k s -> IO ()
1793+revalidateMergeHeight m = do
1794+ currentHeight <- readIORef $ _merge_heightRef m
1795+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1796+ heights <- readIORef $ _merge_heightBagRef m
1797+ parents <- readIORef $ _merge_parentsRef m
1798+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1799+ case heightBagSize heights `compare` DMap.size parents of
1800+ LT -> return ()
1801+ EQ -> do
1802+ let height = succHeight $ heightBagMax heights
1803+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1804+ writeIORef (_merge_heightRef m) $! height
1805+ subscriberRecalculateHeight (_merge_sub m) height
1806+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
1807+
1808+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1809+scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
1810+ vals <- liftIO $ readIORef $ _merge_accumRef m
1811+ 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
1812+ --TODO: Assert that m is not empty
1813+ subscriberPropagate (_merge_sub m) vals
1814+
1815+mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1816+mergeSubscriber m getKey = Subscriber
1817+ { subscriberPropagate = \a -> do
1818+ oldM <- liftIO $ readIORef $ _merge_accumRef m
1819+ k <- getKey
1820+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1821+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1822+ liftIO $ writeIORef (_merge_accumRef m) $! newM
1823+ when (DMap.null oldM) $ do -- Only schedule the firing once
1824+ height <- liftIO $ readIORef $ _merge_heightRef m
1825+ --TODO: assertions about height
1826+ currentHeight <- getCurrentHeight
1827+ when (height <= currentHeight) $ do
1828+ if height /= invalidHeight
1829+ then do
1830+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1831+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1832+ else liftIO $ do
1833+#ifdef DEBUG_CYCLES
1834+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1835+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1836+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1837+#else
1838+ let cycleInfo = ""
1839+#endif
1840+ error $ "Causality loop found" <> cycleInfo
1841+ scheduleMergeSelf m height
1842+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1843+ modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old
1844+ invalidateMergeHeight m
1845+ , subscriberRecalculateHeight = \new -> do
1846+ modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new
1847+ revalidateMergeHeight m
1848+ }
1849+
1850+--TODO: Be able to run as much of this as possible promptly
1851+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1852+updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
1853+ where updateMe = do
1854+ oldParents <- liftIO $ readIORef $ _merge_parentsRef m
1855+ (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber m) (_merge_heightBagRef m) oldParents p
1856+ liftIO $ writeIORef (_merge_parentsRef m) $! newParents
1857+ return subscriptionsToKill
1858+
1859+{-# INLINE mergeCheap' #-}
1860+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)
1861+mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1862+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1863+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1864+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1865+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1866+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1867+ let m = Merge
1868+ { _merge_parentsRef = parentsRef
1869+ , _merge_heightBagRef = heightBagRef
1870+ , _merge_heightRef = heightRef
1871+ , _merge_sub = sub
1872+ , _merge_accumRef = accumRef
1873+ }
1874+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber m
1875+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1876+ myHeight = if invalidHeight `elem` heights
1877+ then invalidHeight
1878+ else succHeight $ heightBagMax myHeightBag
1879+ currentHeight <- getCurrentHeight
1880+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1881+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1882+ else (Nothing, dm)
1883+ unless (DMap.null accum) $ do
1884+ scheduleMergeSelf m myHeight
1885+ liftIO $ writeIORef accumRef $! accum
1886+ liftIO $ writeIORef heightRef $! myHeight
1887+ liftIO $ writeIORef heightBagRef $! myHeightBag
1888+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1889+ liftIO $ writeIORef parentsRef $! initialParentState
1890+ defer $ SomeMergeInit $ do
1891+ let s = Subscriber
1892+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1893+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1894+ defer $ updateMerge m updateFunc a
1895+ , subscriberInvalidateHeight = \_ -> return ()
1896+ , subscriberRecalculateHeight = \_ -> return ()
1897+ }
1898+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1899+ forM_ change $ \c -> defer $ updateMerge m updateFunc c
1900+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1901+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1902+ -- its subscription.
1903+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1904+ let unsubscribeAll = destroy =<< readIORef parentsRef
1905+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1906+ , occ
1907+ )
1908+
1909+mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1910+mergeInt = cacheEvent . mergeIntCheap
1911+
1912+{-# INLINABLE mergeIntCheap #-}
1913+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1914+mergeIntCheap d = Event $ \sub -> do
1915+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1916+ accum <- liftIO $ FastMutableIntMap.newEmpty
1917+ heightRef <- liftIO $ newIORef zeroHeight
1918+ heightBagRef <- liftIO $ newIORef heightBagEmpty
1919+ parents <- liftIO $ FastMutableIntMap.newEmpty
1920+ let scheduleSelf = do
1921+ height <- liftIO $ readIORef $ heightRef
1922+ scheduleMerge' height heightRef $ do
1923+ vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum
1924+ subscriberPropagate sub vals
1925+ invalidateMyHeight = do
1926+ invalidateMergeHeight' heightRef sub
1927+ recalculateMyHeight = do
1928+ currentHeight <- readIORef heightRef
1929+ 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?
1930+ heights <- readIORef heightBagRef
1931+ numParents <- FastMutableIntMap.size parents
1932+ case heightBagSize heights `compare` numParents of
1933+ LT -> return ()
1934+ EQ -> do
1935+ let height = succHeight $ heightBagMax heights
1936+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1937+ writeIORef heightRef $! height
1938+ subscriberRecalculateHeight sub height
1939+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"
1940+ mySubscriber k = Subscriber
1941+ { subscriberPropagate = \a -> do
1942+ wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1943+ liftIO $ FastMutableIntMap.insert accum k a
1944+ when wasEmpty scheduleSelf
1945+ , subscriberInvalidateHeight = \old -> do
1946+ modifyIORef' heightBagRef $ heightBagRemove old
1947+ invalidateMyHeight
1948+ , subscriberRecalculateHeight = \new -> do
1949+ modifyIORef' heightBagRef $ heightBagAdd new
1950+ recalculateMyHeight
1951+ }
1952+ forM_ (IntMap.toList initialParents) $ \(k, p) -> do
1953+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k
1954+ liftIO $ do
1955+ forM_ parentOcc $ FastMutableIntMap.insert accum k
1956+ FastMutableIntMap.insert parents k subscription
1957+ height <- getEventSubscribedHeight parentSubd
1958+ if height == invalidHeight
1959+ then writeIORef heightRef invalidHeight
1960+ else do
1961+ modifyIORef' heightBagRef $ heightBagAdd height
1962+ modifyIORef' heightRef $ \oldHeight ->
1963+ if oldHeight == invalidHeight
1964+ then invalidHeight
1965+ else max (succHeight height) oldHeight
1966+ myHeight <- liftIO $ readIORef heightRef
1967+ currentHeight <- getCurrentHeight
1968+ isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum
1969+ occ <- if currentHeight >= myHeight -- If we should have fired by now
1970+ then if isEmpty
1971+ then return Nothing
1972+ else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum
1973+ else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet
1974+ return Nothing
1975+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1976+ defer $ SomeMergeInit $ do
1977+ let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight
1978+ where
1979+ u = do
1980+ let f k newParent = do
1981+ subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k
1982+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1983+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1984+ return subscription
1985+ newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a
1986+ oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions
1987+ liftIO $ for_ oldParents $ \oldParent -> do
1988+ oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent
1989+ modifyIORef' heightBagRef $ heightBagRemove oldParentHeight
1990+ return $ IntMap.elems oldParents
1991+ let s = Subscriber
1992+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1993+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"
1994+ defer $ updateMe a
1995+ , subscriberInvalidateHeight = \_ -> return ()
1996+ , subscriberRecalculateHeight = \_ -> return ()
1997+ }
1998+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1999+ forM_ change $ \c -> defer $ updateMe c
2000+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
2001+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
2002+ -- its subscription.
2003+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
2004+ let unsubscribeAll = traverse_ unsubscribe =<< FastMutableIntMap.getFrozenAndClear parents
2005+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parents, changeSubdRef)
2006+ , occ
2007+ )
2008+
2009+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2010+
2011+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2012+fan e =
2013+ let f = Fan
2014+ { fanParent = e
2015+ , fanSubscribed = unsafeNewIORef e Nothing
2016+ }
2017+ in EventSelector $ \k -> eventFan k f
2018+
2019+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
2020+runHoldInits holdInitRef dynInitRef mergeInitRef = do
2021+ holdInits <- liftIO $ readIORef holdInitRef
2022+ dynInits <- liftIO $ readIORef dynInitRef
2023+ mergeInits <- liftIO $ readIORef mergeInitRef
2024+ unless (null holdInits && null dynInits && null mergeInits) $ do
2025+ liftIO $ writeIORef holdInitRef []
2026+ liftIO $ writeIORef dynInitRef []
2027+ liftIO $ writeIORef mergeInitRef []
2028+ mapM_ initHold holdInits
2029+ mapM_ initDyn dynInits
2030+ mapM_ unSomeMergeInit mergeInits
2031+ runHoldInits holdInitRef dynInitRef mergeInitRef
2032+
2033+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
2034+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
2035+
2036+initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()
2037+initDyn (SomeDynInit d) = void $ getDynHold d
2038+
2039+newEventEnv :: IO (EventEnv x)
2040+newEventEnv = do
2041+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
2042+ holdInitRef <- newIORef []
2043+ dynInitRef <- newIORef []
2044+ mergeUpdateRef <- newIORef []
2045+ mergeInitRef <- newIORef []
2046+ heightRef <- newIORef zeroHeight
2047+ toClearRef <- newIORef []
2048+ toClearIntRef <- newIORef []
2049+ toClearRootRef <- newIORef []
2050+ coincidenceInfosRef <- newIORef []
2051+ delayedRef <- newIORef IntMap.empty
2052+ return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef
2053+
2054+clearEventEnv :: EventEnv x -> IO ()
2055+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
2056+ writeIORef toAssignRef []
2057+ writeIORef holdInitRef []
2058+ writeIORef dynInitRef []
2059+ writeIORef mergeUpdateRef []
2060+ writeIORef mergeInitRef []
2061+ writeIORef heightRef zeroHeight
2062+ writeIORef toClearRef []
2063+ writeIORef toClearIntRef []
2064+ writeIORef toClearRootRef []
2065+ writeIORef coincidenceInfosRef []
2066+ writeIORef delayedRef IntMap.empty
2067+
2068+-- | Run an event action outside of a frame
2069+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
2070+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
2071+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2072+ let go = do
2073+ result <- a
2074+ 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
2075+ return result
2076+ result <- runEventM go
2077+ toClear <- readIORef $ eventEnvClears env
2078+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2079+ toClearInt <- readIORef $ eventEnvIntClears env
2080+ forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2081+ toClearRoot <- readIORef $ eventEnvRootClears env
2082+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2083+ toAssign <- readIORef $ eventEnvAssignments env
2084+ toReconnectRef <- newIORef []
2085+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
2086+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
2087+ writeIORef vRef v
2088+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
2089+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
2090+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
2091+ writeIORef (eventEnvMergeUpdates env) []
2092+ when debugPropagate $ putStrLn "Updating merges"
2093+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
2094+ when debugPropagate $ putStrLn "Updating merges done"
2095+ toReconnect <- readIORef toReconnectRef
2096+ clearEventEnv env
2097+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2098+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
2099+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
2100+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
2101+ finalize wi
2102+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
2103+ wi' <- mkWeakPtrWithDebug i "wi'"
2104+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
2105+ writeIORef (switchSubscribedBehaviorParents subscribed) []
2106+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
2107+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
2108+ 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
2109+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
2110+ sub <- newSubscriberSwitch subscribed
2111+ 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
2112+ {-
2113+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
2114+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
2115+ EventRoot _ -> "EventRoot"
2116+ EventNever -> "EventNever"
2117+ _ -> "something else"
2118+ -}
2119+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
2120+ return oldSubscription
2121+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
2122+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
2123+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
2124+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
2125+ parentHeight <- getEventSubscribedHeight subd'
2126+ myHeight <- readIORef $ switchSubscribedHeight subscribed
2127+ when (parentHeight /= myHeight) $ do
2128+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2129+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2130+ 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
2131+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
2132+ unsubscribe subscription
2133+ mapM_ invalidateCoincidenceHeight mcs
2134+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
2135+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
2136+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
2137+ height <- calculateSwitchHeight subscribed
2138+ updateSwitchHeight height subscribed
2139+ return result
2140+
2141+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
2142+
2143+{-# INLINE zeroHeight #-}
2144+zeroHeight :: Height
2145+zeroHeight = Height 0
2146+
2147+{-# INLINE invalidHeight #-}
2148+invalidHeight :: Height
2149+invalidHeight = Height (-1000)
2150+
2151+#ifdef DEBUG_CYCLES
2152+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
2153+{-# INLINE invalidHeightBeingTraversed #-}
2154+invalidHeightBeingTraversed :: Height
2155+invalidHeightBeingTraversed = Height (-1001)
2156+#endif
2157+
2158+{-# INLINE succHeight #-}
2159+succHeight :: Height -> Height
2160+succHeight h@(Height a) =
2161+ if h == invalidHeight
2162+ then invalidHeight
2163+ else Height $ succ a
2164+
2165+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2166+invalidateCoincidenceHeight subscribed = do
2167+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2168+ when (oldHeight /= invalidHeight) $ do
2169+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2170+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2171+
2172+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
2173+updateSwitchHeight new subscribed = do
2174+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
2175+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2176+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2177+ writeIORef (switchSubscribedHeight subscribed) $! new
2178+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2179+
2180+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
2181+recalculateCoincidenceHeight subscribed = do
2182+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
2183+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
2184+ height <- calculateCoincidenceHeight subscribed
2185+ when (height /= invalidHeight) $ do
2186+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
2187+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2188+
2189+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
2190+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
2191+
2192+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
2193+calculateCoincidenceHeight subscribed = do
2194+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
2195+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
2196+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
2197+
2198+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
2199+
2200+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
2201+invalidate toReconnectRef wis = do
2202+ forM_ wis $ \wi -> do
2203+ mi <- deRefWeak wi
2204+ case mi of
2205+ Nothing -> do
2206+ traceInvalidate "invalidate Dead"
2207+ return () --TODO: Should we clean this up here?
2208+ Just i -> do
2209+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
2210+ case i of
2211+ InvalidatorPull p -> do
2212+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
2213+ mVal <- readIORef $ pullValue p
2214+ forM_ mVal $ \val -> do
2215+ writeIORef (pullValue p) Nothing
2216+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
2217+ InvalidatorSwitch subscribed -> do
2218+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
2219+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
2220+ 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
2221+
2222+--------------------------------------------------------------------------------
2223+-- Reflex integration
2224+--------------------------------------------------------------------------------
2225+
2226+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2227+-- When we're specializing, we include this from Reflex.Class instead, because
2228+-- it needs access to these types; when we're not, we want them here, so our
2229+-- instance isn't an orphan instance.
2230+#include "SpiderTimeline.include.hs"
2231+#include "SpiderTimelineHost.include.hs"
2232+#endif
2233+
2234+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2235+unsafeNewSpiderTimelineEnv = do
2236+ lock <- newMVar ()
2237+ env <- newEventEnv
2238+#ifdef DEBUG
2239+ depthRef <- newIORef 0
2240+#endif
2241+ return $ SpiderTimelineEnv
2242+ { _spiderTimeline_lock = lock
2243+ , _spiderTimeline_eventEnv = env
2244+#ifdef DEBUG
2245+ , _spiderTimeline_depth = depthRef
2246+#endif
2247+ }
2248+
2249+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2250+-- | Create a new SpiderTimelineEnv
2251+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2252+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2253+
2254+data LocalSpiderTimeline x s
2255+
2256+instance Reifies s (SpiderTimelineEnv x) =>
2257+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2258+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2259+
2260+localSpiderTimeline
2261+ :: Proxy s
2262+ -> SpiderTimelineEnv x
2263+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2264+localSpiderTimeline _ = unsafeCoerce
2265+
2266+-- | Pass a new timeline to the given function.
2267+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2268+withSpiderTimeline k = do
2269+ env <- unsafeNewSpiderTimelineEnv
2270+ reify env $ \s -> k $ localSpiderTimeline s env
2271+#endif
2272+
2273+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2274+
2275+type ComputeM = EventM
2276+
2277+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2278+
2279+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2280+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2281+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2282+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2283+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2284+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2285+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2286+ type PullM (SpiderTimeline x) = SpiderPullM x
2287+ type PushM (SpiderTimeline x) = SpiderPushM x
2288+ {-# INLINABLE never #-}
2289+ never = SpiderEvent eventNever
2290+ {-# INLINABLE constant #-}
2291+ constant = SpiderBehavior . behaviorConst
2292+ {-# INLINE push #-}
2293+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2294+ {-# INLINE pushCheap #-}
2295+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2296+ {-# INLINABLE pull #-}
2297+ pull = SpiderBehavior . pull . coerce
2298+ {-# INLINABLE merge #-}
2299+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2300+ {-# INLINABLE fan #-}
2301+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2302+ {-# INLINABLE switch #-}
2303+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2304+ {-# INLINABLE coincidence #-}
2305+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2306+ {-# INLINABLE current #-}
2307+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2308+ {-# INLINABLE updated #-}
2309+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2310+ {-# INLINABLE unsafeBuildDynamic #-}
2311+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
2312+ {-# INLINABLE unsafeBuildIncremental #-}
2313+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2314+ {-# INLINABLE mergeIncremental #-}
2315+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2316+ {-# INLINABLE mergeIncrementalWithMove #-}
2317+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2318+ {-# INLINABLE currentIncremental #-}
2319+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2320+ {-# INLINABLE updatedIncremental #-}
2321+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2322+ {-# INLINABLE incrementalToDynamic #-}
2323+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2324+ c <- readBehaviorUntracked $ dynamicCurrent i
2325+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2326+ eventCoercion Coercion = Coercion
2327+ behaviorCoercion Coercion = Coercion
2328+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2329+ mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2330+ fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
2331+#endif
2332+
2333+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2334+
2335+data SpiderEventHandle x a = SpiderEventHandle
2336+ { spiderEventHandleSubscription :: EventSubscription x
2337+ , spiderEventHandleValue :: IORef (Maybe a)
2338+ }
2339+
2340+instance MonadRef (EventM x) where
2341+ type Ref (EventM x) = Ref IO
2342+ {-# INLINABLE newRef #-}
2343+ {-# INLINABLE readRef #-}
2344+ {-# INLINABLE writeRef #-}
2345+ newRef = liftIO . newRef
2346+ readRef = liftIO . readRef
2347+ writeRef r a = liftIO $ writeRef r a
2348+
2349+instance MonadAtomicRef (EventM x) where
2350+ {-# INLINABLE atomicModifyRef #-}
2351+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2352+
2353+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2354+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2355+
2356+instance Monad (SpiderHost x) where
2357+ {-# INLINABLE (>>=) #-}
2358+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2359+ {-# INLINABLE (>>) #-}
2360+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2361+ {-# INLINABLE return #-}
2362+ return x = SpiderHost $ return x
2363+ {-# INLINABLE fail #-}
2364+ fail s = SpiderHost $ fail s
2365+
2366+-- | Run an action affecting the global Spider timeline; this will be guarded by
2367+-- a mutex for that timeline
2368+runSpiderHost :: SpiderHost Global a -> IO a
2369+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2370+
2371+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2372+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2373+-- mutex for that timeline
2374+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2375+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2376+#endif
2377+
2378+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2379+
2380+instance Monad (SpiderHostFrame x) where
2381+ {-# INLINABLE (>>=) #-}
2382+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2383+ {-# INLINABLE (>>) #-}
2384+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2385+ {-# INLINABLE return #-}
2386+ return x = SpiderHostFrame $ return x
2387+ {-# INLINABLE fail #-}
2388+ fail s = SpiderHostFrame $ fail s
2389+
2390+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2391+newEventWithTriggerIO f = do
2392+ es <- newFanEventWithTriggerIO $ \Refl -> f
2393+ return $ select es Refl
2394+
2395+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2396+newFanEventWithTriggerIO f = do
2397+ occRef <- newIORef DMap.empty
2398+ subscribedRef <- newIORef DMap.empty
2399+ let !r = Root
2400+ { rootOccurrence = occRef
2401+ , rootSubscribed = subscribedRef
2402+ , rootInit = f
2403+ }
2404+ return $ EventSelector $ \k -> eventRoot k r
2405+
2406+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2407+
2408+instance MonadRef (SpiderHost x) where
2409+ type Ref (SpiderHost x) = Ref IO
2410+ newRef = SpiderHost . newRef
2411+ readRef = SpiderHost . readRef
2412+ writeRef r = SpiderHost . writeRef r
2413+
2414+instance MonadAtomicRef (SpiderHost x) where
2415+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2416+
2417+instance MonadRef (SpiderHostFrame x) where
2418+ type Ref (SpiderHostFrame x) = Ref IO
2419+ newRef = SpiderHostFrame . newRef
2420+ readRef = SpiderHostFrame . readRef
2421+ writeRef r = SpiderHostFrame . writeRef r
2422+
2423+instance MonadAtomicRef (SpiderHostFrame x) where
2424+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2425+
2426+instance PrimMonad (SpiderHostFrame x) where
2427+ type PrimState (SpiderHostFrame x) = PrimState IO
2428+ primitive = SpiderHostFrame . EventM . primitive