@@ -0,0 +1,2192 @@
1+{-# LANGUAGE BangPatterns #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE EmptyDataDecls #-}
5+{-# LANGUAGE ExistentialQuantification #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE FunctionalDependencies #-}
10+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11+#if defined(DEBUG) || defined(DEBUG_CYCLES)
12+{-# LANGUAGE LambdaCase #-}
14+{-# LANGUAGE MagicHash #-}
15+{-# LANGUAGE MultiParamTypeClasses #-}
16+{-# LANGUAGE MultiWayIf #-}
17+{-# LANGUAGE RankNTypes #-}
18+{-# LANGUAGE RoleAnnotations #-}
19+{-# LANGUAGE ScopedTypeVariables #-}
20+{-# LANGUAGE TypeFamilies #-}
21+{-# LANGUAGE TypeOperators #-}
22+{-# LANGUAGE UndecidableInstances #-}
23+#ifdef USE_REFLEX_OPTIMIZER
24+{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
26+#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
27+{-# OPTIONS_GHC -fno-warn-orphans #-}
29+-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
30+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
31+module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
33+import Control.Applicative
34+import Control.Concurrent
35+import Control.Exception
36+import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
37+import Control.Monad.Exception
38+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
39+import Control.Monad.Primitive
40+import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
41+import Control.Monad.Ref
44+import Data.Dependent.Map (DMap, DSum (..))
45+import qualified Data.Dependent.Map as DMap
46+import Data.Foldable hiding (concat, elem, sequence_)
48+import Data.Functor.Constant
49+import Data.Functor.Misc
50+import Data.Functor.Product
51+import Data.GADT.Compare
52+import Data.IntMap.Strict (IntMap)
53+import qualified Data.IntMap.Strict as IntMap
55+import Data.List hiding (foldl')
57+import Data.Monoid ((<>))
60+import Data.Traversable
63+import GHC.IORef (IORef (..))
65+import Reflex.FunctorMaybe
66+import System.IO.Unsafe
67+import System.Mem.Weak
71+import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
72+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
73+import qualified Data.List.NonEmpty as NonEmpty
74+import Data.Monoid (mempty)
75+import Data.Tree (Forest, Tree (..), drawForest)
78+import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
79+import qualified Data.WeakBag as WeakBag
80+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
81+import Data.Reflection
82+import Data.Some (Some)
83+import qualified Data.Some as Some
84+import Data.Type.Coercion
85+import qualified Reflex.Class
86+import qualified Reflex.Class as R
87+import qualified Reflex.Host.Class
90+import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
92+-- Note: must come last to silence warnings due to AMP on GHC < 7.10
93+import Prelude hiding (any, concat, mapM, mapM_, sequence)
95+#ifdef DEBUG_TRACE_EVENTS
96+import System.IO (stderr)
97+import qualified Data.ByteString.Char8 as BS8
100+#ifdef DEBUG_TRACE_EVENTS
102+withStackOneLine :: (BS8.ByteString -> a) -> a
103+withStackOneLine expr = unsafePerformIO $ do
104+ stack <- currentCallStack
105+ return (expr (BS8.pack (unwords (reverse stack))))
109+debugPropagate :: Bool
111+debugInvalidateHeight :: Bool
113+debugInvalidate :: Bool
117+#define DEBUG_NODEIDS
119+debugPropagate = True
121+debugInvalidateHeight = False
123+debugInvalidate = True
125+class HasNodeId a where
126+ getNodeId :: a -> Int
128+instance HasNodeId (Hold x p a) where
129+ getNodeId = holdNodeId
131+instance HasNodeId (PushSubscribed x a b) where
132+ getNodeId = pushSubscribedNodeId
134+instance HasNodeId (SwitchSubscribed x a) where
135+ getNodeId = switchSubscribedNodeId
137+instance HasNodeId (FanSubscribed x a) where
138+ getNodeId = fanSubscribedNodeId
140+instance HasNodeId (CoincidenceSubscribed x a) where
141+ getNodeId = coincidenceSubscribedNodeId
143+instance HasNodeId (RootSubscribed x a) where
144+ getNodeId = rootSubscribedNodeId
146+instance HasNodeId (Pull x a) where
147+ getNodeId = pullNodeId
149+{-# INLINE showNodeId #-}
150+showNodeId :: HasNodeId a => a -> String
151+showNodeId = ("#"<>) . show . getNodeId
153+showSubscriberType :: Subscriber x a -> String
154+showSubscriberType = \case
155+ SubscriberPush _ _ -> "SubscriberPush"
156+ SubscriberMerge _ _ -> "SubscriberMerge"
157+ SubscriberFan _ -> "SubscriberFan"
158+ SubscriberMergeChange _ -> "SubscriberMergeChange"
159+ SubscriberHold _ -> "SubscriberHold"
160+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
161+ SubscriberSwitch _ -> "SubscriberSwitch"
162+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
163+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
164+ SubscriberHandle -> "SubscriberHandle"
166+showEventType :: Event x a -> String
167+showEventType = \case
168+ EventRoot _ _ -> "EventRoot"
169+ EventNever -> "EventNever"
170+ EventPush _ -> "EventPush"
171+ EventMerge _ -> "EventMerge"
172+ EventFan _ _ -> "EventFan"
173+ EventSwitch _ -> "EventSwitch"
174+ EventCoincidence _ -> "EventCoincidence"
175+ EventHold _ -> "EventHold"
176+ EventDyn _ -> "EventDyn"
177+ EventHoldIdentity _ -> "EventHoldIdentity"
178+ EventDynIdentity _ -> "EventDynIdentity"
182+debugPropagate = False
184+debugInvalidateHeight = False
186+debugInvalidate = False
188+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
189+{-# INLINE showNodeId #-}
190+showNodeId :: a -> String
196+{-# NOINLINE nextNodeIdRef #-}
197+nextNodeIdRef :: IORef Int
198+nextNodeIdRef = unsafePerformIO $ newIORef 1
201+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
203+{-# NOINLINE unsafeNodeId #-}
204+unsafeNodeId :: a -> Int
205+unsafeNodeId a = unsafePerformIO $ do
210+--------------------------------------------------------------------------------
212+--------------------------------------------------------------------------------
214+--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
215+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
216+data EventSubscription x = EventSubscription
217+ { _eventSubscription_unsubscribe :: !(IO ())
218+ , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
221+unsubscribe :: EventSubscription x -> IO ()
222+unsubscribe (EventSubscription u _) = u
224+--------------------------------------------------------------------------------
226+--------------------------------------------------------------------------------
228+newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
230+{-# INLINE subscribeAndRead #-}
231+subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
232+subscribeAndRead = unEvent
235+"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
236+"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
237+"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
240+-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
241+-- caching; if the computation function is very cheap, this is (much) more
242+-- efficient than 'push'
243+{-# NOINLINE pushCheap #-}
244+pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
245+pushCheap f e = Event $ \sub -> do
246+ (subscription, occ) <- subscribeAndRead e $ sub
247+ { subscriberPropagate = \a -> do
248+ mb <- runComputeM $ f a
249+ mapM_ (subscriberPropagate sub) mb
251+ occ' <- join <$> mapM (runComputeM . f) occ
252+ return (subscription, occ')
254+data CacheSubscribed x a
255+ = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))
256+ , _cacheSubscribed_weakSelf :: {-# UNPACK #-} !(IORef (Weak (CacheSubscribed x a)))
257+ , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
258+ , _cacheSubscribed_cached :: {-# UNPACK #-} !(IORef (Maybe (CacheSubscribed x a)))
259+ , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
262+-- | Construct an 'Event' whose value is guaranteed not to be recomputed
265+--TODO: Try a caching strategy where we subscribe directly to the parent when
266+--there's only one subscriber, and then build our own WeakBag only when a second
268+{-# NOINLINE cacheEvent #-}
269+cacheEvent :: HasSpiderTimeline x => Event x a -> Event x a
271+#ifdef DEBUG_TRACE_EVENTS
272+ withStackOneLine $ \callSite -> Event $
276+ let !mSubscribedRef = unsafeNewIORef e Nothing
277+ in \sub -> {-# SCC "cacheEvent" #-} do
278+#ifdef DEBUG_TRACE_EVENTS
279+ unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
281+ mSubscribed <- liftIO $ readIORef mSubscribedRef
283+ Just subscribed -> liftIO $ do
284+ ticket <- WeakBag.insert sub (_cacheSubscribed_subscribers subscribed) (_cacheSubscribed_weakSelf subscribed) cleanupCacheSubscribed
285+ occ <- readIORef $ _cacheSubscribed_occurrence subscribed
286+ let es = EventSubscribed
287+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
288+ , eventSubscribedRetained = toAny subscribed
290+ return (EventSubscription (WeakBag.remove ticket >> touch ticket) es, occ)
292+ weakSelf <- liftIO $ newIORef $ error "cacheEvent: weakSelf not yet intialized"
293+ (subscribers, ticket) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCacheSubscribed
294+ occRef <- liftIO $ newIORef undefined
295+ (parentSub, occ) <- subscribeAndRead e $ Subscriber
296+ { subscriberPropagate = \a -> do
297+ liftIO $ writeIORef occRef $ Just a
298+ scheduleClear occRef
299+ propagate a subscribers
300+ , subscriberInvalidateHeight = \old -> do
301+ WeakBag.traverse subscribers $ invalidateSubscriberHeight old
302+ , subscriberRecalculateHeight = \new -> do
303+ WeakBag.traverse subscribers $ recalculateSubscriberHeight new
305+ liftIO $ writeIORef occRef occ
306+ when (isJust occ) $ scheduleClear occRef
307+ let !subscribed = CacheSubscribed
308+ { _cacheSubscribed_subscribers = subscribers
309+ , _cacheSubscribed_weakSelf = weakSelf
310+ , _cacheSubscribed_parent = parentSub
311+ , _cacheSubscribed_cached = mSubscribedRef
312+ , _cacheSubscribed_occurrence = occRef
314+ liftIO $ writeIORef mSubscribedRef $ Just subscribed
315+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
316+ return (EventSubscription (WeakBag.remove ticket >> touch ticket) (EventSubscribed (eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub) (toAny subscribed)), occ)
318+cleanupCacheSubscribed :: CacheSubscribed x a -> IO ()
319+cleanupCacheSubscribed self = do
320+ unsubscribe $ _cacheSubscribed_parent self
321+ writeIORef (_cacheSubscribed_cached self) Nothing
323+subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
324+subscribe e s = fst <$> subscribeAndRead e s
327+wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
328+wrap tag getSpecificSubscribed sub = do
329+ (sln, subd, occ) <- getSpecificSubscribed sub
331+ return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
333+eventRoot :: GCompare k => k a -> Root x k -> Event x a
334+eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
336+eventNever :: Event x a
337+eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
339+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
340+eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
342+eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
343+eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
345+eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
346+eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
348+eventHold :: HasSpiderTimeline x => Hold x p -> Event x p
349+eventHold !h = Event $ subscribeHoldEvent h
351+eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
352+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
354+{-# INLINE subscribeCoincidenceInner #-}
355+subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x)
356+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
357+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
358+ (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
359+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
360+ let height = max innerHeight outerHeight
361+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
362+ return (innerOcc, height, innerSubd)
364+--------------------------------------------------------------------------------
366+--------------------------------------------------------------------------------
368+data Subscriber x a = Subscriber
369+ { subscriberPropagate :: !(a -> EventM x ())
370+ , subscriberInvalidateHeight :: !(Height -> IO ())
371+ , subscriberRecalculateHeight :: !(Height -> IO ())
374+--TODO: Move this comment to WeakBag
375+-- These function are constructor functions that are marked NOINLINE so they are
376+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
377+-- so any weak references that are attached to the constructors will have their
378+-- finalizer run. Using the opaque constructor, does not see the
379+-- constructor application, so it behaves like an IORef and cannot be fused away.
381+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
382+-- the weak pointer to it in some cases.
384+newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
385+newSubscriberHold h = return $ Subscriber
386+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
387+ , subscriberInvalidateHeight = \_ -> return ()
388+ , subscriberRecalculateHeight = \_ -> return ()
391+newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
392+newSubscriberFan subscribed = return $ Subscriber
393+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
394+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
395+ tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
396+ liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
397+ scheduleClear $ fanSubscribedOccurrence subscribed
398+ let f _ (Pair (Identity v) subsubs) = do
399+ propagate v $ _fanSubscribedChildren_list subsubs
400+ return $ Constant ()
401+ _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
403+ , subscriberInvalidateHeight = \old -> do
404+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
405+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
406+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
407+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
408+ , subscriberRecalculateHeight = \new -> do
409+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
410+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
411+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
412+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
415+newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
416+newSubscriberSwitch subscribed = return $ Subscriber
417+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
418+ tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
419+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
420+ scheduleClear $ switchSubscribedOccurrence subscribed
421+ propagate a $ switchSubscribedSubscribers subscribed
422+ , subscriberInvalidateHeight = \_ -> do
423+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
424+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
425+ when (oldHeight /= invalidHeight) $ do
426+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
427+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
428+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
429+ , subscriberRecalculateHeight = \new -> do
430+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
431+ updateSwitchHeight new subscribed
432+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
435+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
436+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
437+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
438+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
439+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
440+ tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
441+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
442+ tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
443+ tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
444+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
445+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
448+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
449+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
450+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
451+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
452+ Just o -> do -- Since it's already firing, no need to adjust height
453+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
454+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
455+ propagate o $ coincidenceSubscribedSubscribers subscribed
456+ , subscriberInvalidateHeight = \_ -> do
457+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
458+ invalidateCoincidenceHeight subscribed
459+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
460+ , subscriberRecalculateHeight = \_ -> do
461+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
462+ recalculateCoincidenceHeight subscribed
463+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
466+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
467+newSubscriberCoincidenceInner subscribed = return $ Subscriber
468+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
469+ tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
470+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
472+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
474+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
475+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
476+ propagate a $ coincidenceSubscribedSubscribers subscribed
477+ , subscriberInvalidateHeight = \_ -> do
478+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
479+ invalidateCoincidenceHeight subscribed
480+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
481+ , subscriberRecalculateHeight = \_ -> do
482+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
483+ recalculateCoincidenceHeight subscribed
484+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
487+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
488+invalidateSubscriberHeight = flip subscriberInvalidateHeight
490+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
491+recalculateSubscriberHeight = flip subscriberRecalculateHeight
493+-- | Propagate everything at the current height
494+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
495+propagate a subscribers = withIncreasedDepth $ do
496+ -- 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
497+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
498+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
500+--------------------------------------------------------------------------------
502+--------------------------------------------------------------------------------
507+data EventSubscribed x = EventSubscribed
508+ { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
509+ , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
511+ , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
512+ , eventSubscribedHasOwnHeightRef :: !Bool
513+ , eventSubscribedWhoCreated :: !(IO [String])
517+eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
518+eventSubscribedRoot !r = EventSubscribed
519+ { eventSubscribedHeightRef = zeroRef
520+ , eventSubscribedRetained = toAny r
522+ , eventSubscribedGetParents = return []
523+ , eventSubscribedHasOwnHeightRef = False
524+ , eventSubscribedWhoCreated = return ["root"]
528+eventSubscribedNever :: EventSubscribed x
529+eventSubscribedNever = EventSubscribed
530+ { eventSubscribedHeightRef = zeroRef
531+ , eventSubscribedRetained = toAny ()
533+ , eventSubscribedGetParents = return []
534+ , eventSubscribedHasOwnHeightRef = False
535+ , eventSubscribedWhoCreated = return ["never"]
539+eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
540+eventSubscribedFan !subscribed = EventSubscribed
541+ { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
542+ , eventSubscribedRetained = toAny subscribed
544+ , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
545+ , eventSubscribedHasOwnHeightRef = False
546+ , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
550+eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
551+eventSubscribedSwitch !subscribed = EventSubscribed
552+ { eventSubscribedHeightRef = switchSubscribedHeight subscribed
553+ , eventSubscribedRetained = toAny subscribed
555+ , eventSubscribedGetParents = do
556+ s <- readIORef $ switchSubscribedCurrentParent subscribed
557+ return [Some.This $ _eventSubscription_subscribed s]
558+ , eventSubscribedHasOwnHeightRef = True
559+ , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
563+eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
564+eventSubscribedCoincidence !subscribed = EventSubscribed
565+ { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
566+ , eventSubscribedRetained = toAny subscribed
568+ , eventSubscribedGetParents = do
569+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
570+ let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
571+ innerParents = maybeToList $ fmap Some.This innerSubscription
572+ return $ outerParent : innerParents
573+ , eventSubscribedHasOwnHeightRef = True
574+ , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
578+getEventSubscribedHeight :: EventSubscribed x -> IO Height
579+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
582+whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
583+whoCreatedEventSubscribed = eventSubscribedWhoCreated
585+walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
586+walkInvalidHeightParents s0 = do
587+ subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
588+ h <- liftIO $ readIORef $ eventSubscribedHeightRef s
589+ when (h == invalidHeight) $ do
590+ when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
591+ modify (Some.This s :)
592+ mapM_ loop =<< liftIO (eventSubscribedGetParents s)
593+ forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
597+{-# INLINE subscribeHoldEvent #-}
598+subscribeHoldEvent :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (EventSubscription x, Maybe p)
599+subscribeHoldEvent = subscribeAndRead . holdEvent
601+--------------------------------------------------------------------------------
603+--------------------------------------------------------------------------------
605+newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
607+behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
608+behaviorHold !h = Behavior $ readHoldTracked h
610+behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
611+behaviorHoldIdentity = behaviorHold
613+behaviorConst :: a -> Behavior x a
614+behaviorConst !a = Behavior $ return a
616+behaviorPull :: Pull x a -> Behavior x a
617+behaviorPull !p = Behavior $ do
618+ val <- liftIO $ readIORef $ pullValue p
620+ Just subscribed -> do
621+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
622+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
623+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
624+ return $ pullSubscribedValue subscribed
626+ i <- liftIO $ newInvalidatorPull p
627+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
628+ parentsRef <- liftIO $ newIORef []
629+ holdInits <- askBehaviorHoldInits
630+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
631+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
632+ parents <- liftIO $ readIORef parentsRef
633+ let subscribed = PullSubscribed
634+ { pullSubscribedValue = a
635+ , pullSubscribedInvalidators = invsRef
636+ , pullSubscribedOwnInvalidator = i
637+ , pullSubscribedParents = parents
639+ liftIO $ writeIORef (pullValue p) $ Just subscribed
640+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
643+behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
644+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
646+{-# INLINE readHoldTracked #-}
647+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
648+readHoldTracked h = do
649+ result <- liftIO $ readIORef $ holdValue h
650+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
651+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
654+{-# INLINABLE readBehaviorUntracked #-}
655+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
656+readBehaviorUntracked b = do
657+ holdInits <- getDeferralQueue
658+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
660+--------------------------------------------------------------------------------
662+--------------------------------------------------------------------------------
664+data Dynamic x p = Dynamic
665+ { dynamicCurrent :: !(Behavior x (PatchTarget p))
666+ , dynamicUpdated :: !(Event x p)
669+dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
670+dynamicHold !h = Dynamic
671+ { dynamicCurrent = behaviorHold h
672+ , dynamicUpdated = eventHold h
675+dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
676+dynamicHoldIdentity = dynamicHold
678+dynamicConst :: PatchTarget p -> Dynamic x p
679+dynamicConst !a = Dynamic
680+ { dynamicCurrent = behaviorConst a
681+ , dynamicUpdated = eventNever
684+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
685+dynamicDyn !d = Dynamic
686+ { dynamicCurrent = behaviorDyn d
687+ , dynamicUpdated = eventDyn d
690+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
691+dynamicDynIdentity = dynamicDyn
693+--------------------------------------------------------------------------------
695+--------------------------------------------------------------------------------
697+--TODO: Figure out why certain things are not 'representational', then make them
698+--representational so we can use coerce
700+--type role Hold representational
702+ = Hold { holdValue :: !(IORef (PatchTarget p))
703+ , holdInvalidators :: !(IORef [Weak (Invalidator x)])
704+ , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
705+ , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
711+-- | A statically allocated 'SpiderTimeline'; this is the only instance of
712+-- 'SpiderTimeline' that can used when using
713+-- -fspecialize-to-spidertimeline-global.
716+{-# NOINLINE globalSpiderTimelineEnv #-}
717+globalSpiderTimelineEnv :: SpiderTimelineEnv Global
718+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
720+-- | Stores all global data relevant to a particular Spider timeline; only one
721+-- value should exist for each type @x@
722+data SpiderTimelineEnv x = SpiderTimelineEnv
723+ { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
724+ , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
726+ , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
729+type role SpiderTimelineEnv nominal
731+instance Eq (SpiderTimelineEnv x) where
732+ _ == _ = True -- Since only one exists of each type
734+instance GEq SpiderTimelineEnv where
735+#ifdef EXPERIMENTAL_DEPENDENT_SUM_INSTANCES
737+ geqUnify (a :: SpiderTimelineEnv a) (b :: SpiderTimelineEnv b) different same = if _spiderTimeline_lock a == _spiderTimeline_lock b
738+ then case unsafeCoerce Refl :: a :~: b of
739+ Refl -> same -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
742+ a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
743+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
748+ = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
749+ , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
750+ , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
751+ , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
752+ , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
753+ , eventEnvRootClears :: !(IORef [SomeRootClear])
754+ , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
755+ , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
756+ , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
759+{-# INLINE runEventM #-}
760+runEventM :: EventM x a -> IO a
763+asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
764+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
766+class MonadIO m => Defer a m where
767+ getDeferralQueue :: m (IORef [a])
770+defer :: Defer a m => a -> m ()
772+ q <- getDeferralQueue
773+ liftIO $ modifyIORef' q (a:)
775+instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
776+ {-# INLINE getDeferralQueue #-}
777+ getDeferralQueue = asksEventEnv eventEnvAssignments
779+instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
780+ {-# INLINE getDeferralQueue #-}
781+ getDeferralQueue = asksEventEnv eventEnvHoldInits
783+instance Defer (SomeHoldInit x) (BehaviorM x) where
784+ {-# INLINE getDeferralQueue #-}
785+ getDeferralQueue = BehaviorM $ asks snd
787+instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
788+ {-# INLINE getDeferralQueue #-}
789+ getDeferralQueue = asksEventEnv eventEnvMergeUpdates
791+instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
792+ {-# INLINE getDeferralQueue #-}
793+ getDeferralQueue = asksEventEnv eventEnvMergeInits
795+class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
796+ getCurrentHeight :: m Height
797+ scheduleMerge :: Height -> EventM x () -> m ()
799+instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
800+ {-# INLINE getCurrentHeight #-}
801+ getCurrentHeight = do
802+ heightRef <- asksEventEnv eventEnvCurrentHeight
803+ liftIO $ readIORef heightRef
804+ {-# INLINE scheduleMerge #-}
805+ scheduleMerge height subscribed = do
806+ delayedRef <- asksEventEnv eventEnvDelayedMerges
807+ liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
809+#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
810+class x ~ Global => HasSpiderTimeline x where
812+class HasSpiderTimeline x where
814+ -- | Retrieve the current SpiderTimelineEnv
815+ spiderTimeline :: SpiderTimelineEnv x
817+instance HasSpiderTimeline Global where
818+ spiderTimeline = globalSpiderTimelineEnv
820+putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
821+putCurrentHeight h = do
822+ heightRef <- asksEventEnv eventEnvCurrentHeight
823+ liftIO $ writeIORef heightRef $! h
825+instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
826+ {-# INLINE getDeferralQueue #-}
827+ getDeferralQueue = asksEventEnv eventEnvClears
829+{-# INLINE scheduleClear #-}
830+scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
831+scheduleClear r = defer $ SomeClear r
833+instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
834+ {-# INLINE getDeferralQueue #-}
835+ getDeferralQueue = asksEventEnv eventEnvRootClears
837+{-# INLINE scheduleRootClear #-}
838+scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
839+scheduleRootClear r = defer $ SomeRootClear r
841+instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
842+ {-# INLINE getDeferralQueue #-}
843+ getDeferralQueue = asksEventEnv eventEnvResetCoincidences
845+-- Note: hold cannot examine its event until after the phase is over
846+{-# INLINE [1] hold #-}
847+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
849+ valRef <- liftIO $ newIORef v0
850+ invsRef <- liftIO $ newIORef []
851+ parentRef <- liftIO $ newIORef Nothing
853+ nodeId <- liftIO newNodeId
856+ { holdValue = valRef
857+ , holdInvalidators = invsRef
859+ , holdParent = parentRef
861+ , holdNodeId = nodeId
864+ defer $ SomeHoldInit h
867+{-# INLINE getHoldEventSubscription #-}
868+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)
869+getHoldEventSubscription h = do
870+ ep <- liftIO $ readIORef $ holdParent h
872+ Just subd -> return subd
875+ subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
876+ (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
877+ liftIO $ writeIORef subscriptionRef $! subscription
879+ Nothing -> return ()
881+ old <- liftIO $ readIORef $ holdValue h
883+ Nothing -> return ()
885+ -- Need to evaluate these so that we don't retain the Hold itself
886+ v <- liftIO $ evaluate $ holdValue h
887+ i <- liftIO $ evaluate $ holdInvalidators h
888+ defer $ SomeAssignment v i new
889+ liftIO $ writeIORef (holdParent h) $ Just subscription
892+type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
894+--type role BehaviorM representational
895+-- BehaviorM can sample behaviors
896+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
898+instance Monad (BehaviorM x) where
899+ {-# INLINE (>>=) #-}
900+ BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
902+ BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
903+ {-# INLINE return #-}
904+ return x = BehaviorM $ return x
906+ fail s = BehaviorM $ fail s
908+data BehaviorSubscribed x a
909+ = forall p. BehaviorSubscribedHold (Hold x p)
910+ | BehaviorSubscribedPull (PullSubscribed x a)
912+data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
914+--type role PullSubscribed representational
915+data PullSubscribed x a
916+ = PullSubscribed { pullSubscribedValue :: !a
917+ , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
918+ , pullSubscribedOwnInvalidator :: !(Invalidator x)
919+ , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
922+--type role Pull representational
924+ = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
925+ , pullCompute :: !(BehaviorM x a)
932+ = forall a. InvalidatorPull (Pull x a)
933+ | forall a. InvalidatorSwitch (SwitchSubscribed x a)
935+data RootSubscribed x a = forall k. GCompare k => RootSubscribed
936+ { rootSubscribedKey :: !(k a)
937+ , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
938+ , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
939+ , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
940+ , rootSubscribedUninit :: IO ()
941+ , 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?
943+ , rootSubscribedNodeId :: Int
947+data Root x (k :: * -> *)
948+ = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
949+ , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
950+ , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
953+data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
955+data SomeMergeUpdate x = SomeMergeUpdate
956+ { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
957+ , _someMergeUpdate_invalidateHeight :: !(IO ())
958+ , _someMergeUpdate_recalculateHeight :: !(IO ())
961+newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
963+-- EventM can do everything BehaviorM can, plus create holds
964+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
966+newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
968+instance Defer (SomeHoldInit x) (ComputeM x) where
969+ getDeferralQueue = ComputeM ask
971+{-# INLINABLE runComputeM #-}
972+runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
973+runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
975+newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
977+data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove
978+ { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)
979+ , _mergeSubscribedParentWithMove_key :: !(IORef (k a))
982+data HeightBag = HeightBag
983+ { _heightBag_size :: {-# UNPACK #-} !Int
984+ , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
986+ deriving (Show, Read, Eq, Ord)
988+heightBagEmpty :: HeightBag
989+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
991+heightBagSize :: HeightBag -> Int
992+heightBagSize = _heightBag_size
994+heightBagFromList :: [Height] -> HeightBag
995+heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
997+heightBagAdd :: Height -> HeightBag -> HeightBag
998+heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
1000+heightBagRemove :: Height -> HeightBag -> HeightBag
1001+heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
1002+ Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
1003+ Just old -> HeightBag (pred s) $ case old of
1004+ 0 -> IntMap.delete h c
1005+ _ -> IntMap.insert h (pred old) c
1007+heightBagMax :: HeightBag -> Height
1008+heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
1009+ Just ((h, _), _) -> Height h
1010+ Nothing -> zeroHeight
1012+heightBagVerify :: HeightBag -> HeightBag
1014+heightBagVerify b@(HeightBag s c) = if
1015+ | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
1016+ -> error $ "heightBagVerify: size doesn't match: " <> show b
1017+ | unHeight invalidHeight `IntMap.member` c
1018+ -> error $ "heightBagVerify: contains invalid height: " <> show b
1021+heightBagVerify = id
1024+data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1025+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1026+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1027+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1030+data FanSubscribed (x :: *) k
1031+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1032+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1033+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1034+ , fanSubscribedParent :: !(EventSubscription x)
1035+#ifdef DEBUG_NODEIDS
1036+ , fanSubscribedNodeId :: Int
1041+ = Fan { fanParent :: !(Event x (DMap k Identity))
1042+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1045+data SwitchSubscribed x a
1046+ = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1047+ , switchSubscribedOccurrence :: !(IORef (Maybe a))
1048+ , switchSubscribedHeight :: !(IORef Height)
1049+ , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1050+ , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1051+ , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1052+ , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1053+ , switchSubscribedParent :: !(Behavior x (Event x a))
1054+ , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1055+ , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1056+#ifdef DEBUG_NODEIDS
1057+ , switchSubscribedNodeId :: Int
1062+ = Switch { switchParent :: !(Behavior x (Event x a))
1063+ , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1066+#ifdef USE_TEMPLATE_HASKELL
1067+{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1069+data CoincidenceSubscribed x a
1070+ = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1071+ , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1072+ , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1073+ , coincidenceSubscribedHeight :: !(IORef Height)
1074+ , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1075+ , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1076+ , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1077+ , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1078+#ifdef DEBUG_NODEIDS
1079+ , coincidenceSubscribedNodeId :: Int
1083+data Coincidence x a
1084+ = Coincidence { coincidenceParent :: !(Event x (Event x a))
1085+ , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1088+{-# NOINLINE newInvalidatorSwitch #-}
1089+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1090+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1092+{-# NOINLINE newInvalidatorPull #-}
1093+newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1094+newInvalidatorPull p = return $! InvalidatorPull p
1096+instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1097+ fmapMaybe f = push $ return . f
1099+instance HasSpiderTimeline x => Align (Event x) where
1101+ align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1103+newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1105+newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1106+newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1108+--TODO: Avoid the duplication between this and R.zipDynWith
1109+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1110+zipDynWith f da db =
1111+ let eab = align (dynamicUpdated da) (dynamicUpdated db)
1112+ ec = flip push eab $ \o -> do
1113+ (a, b) <- case o of
1114+ This (Identity a) -> do
1115+ b <- readBehaviorUntracked $ dynamicCurrent db
1117+ That (Identity b) -> do
1118+ a <- readBehaviorUntracked $ dynamicCurrent da
1120+ These (Identity a) (Identity b) -> return (a, b)
1121+ return $ Just $ Identity $ f a b
1122+ in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1124+unsafeDyn :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1125+unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1126+ where x = (readV0, v')
1128+-- ResultM can read behaviors and events
1129+type ResultM = EventM
1131+{-# NOINLINE unsafeNewIORef #-}
1132+unsafeNewIORef :: a -> b -> IORef b
1133+unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1135+instance HasSpiderTimeline x => Functor (Event x) where
1136+ fmap f = push $ return . Just . f
1138+instance Functor (Behavior x) where
1139+ fmap f = pull . fmap f . readBehaviorTracked
1142+push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1143+push f e = cacheEvent (pushCheap f e)
1145+{-# INLINABLE pull #-}
1146+pull :: BehaviorM x a -> Behavior x a
1147+pull a = behaviorPull $ Pull
1149+ , pullValue = unsafeNewIORef a Nothing
1150+#ifdef DEBUG_NODEIDS
1151+ , pullNodeId = unsafeNodeId a
1155+{-# INLINABLE switch #-}
1156+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1157+switch a = eventSwitch $ Switch
1159+ , switchSubscribed = unsafeNewIORef a Nothing
1162+coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1163+coincidence a = eventCoincidence $ Coincidence
1164+ { coincidenceParent = a
1165+ , coincidenceSubscribed = unsafeNewIORef a Nothing
1168+-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1169+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1170+run roots after = do
1171+ tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1172+ t <- SpiderHost ask
1173+ result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1174+ rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1175+ occBefore <- liftIO $ do
1176+ occBefore <- readIORef occRef
1177+ writeIORef occRef $! DMap.insert k a occBefore
1179+ if DMap.null occBefore
1180+ then do scheduleRootClear occRef
1182+ else return Nothing
1183+ forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1184+ propagate a subscribersRef
1185+ delayedRef <- asksEventEnv eventEnvDelayedMerges
1187+ delayed <- liftIO $ readIORef delayedRef
1188+ case IntMap.minViewWithKey delayed of
1189+ Nothing -> return ()
1190+ Just ((currentHeight, cur), future) -> do
1191+ tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1192+ putCurrentHeight $ Height currentHeight
1193+ liftIO $ writeIORef delayedRef $! future
1197+ putCurrentHeight maxBound
1199+ tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1202+scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1203+scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1204+ height <- liftIO $ readIORef heightRef
1205+ currentHeight <- getCurrentHeight
1206+ case height `compare` currentHeight of
1207+ LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1208+ GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1211+data SomeClear = forall a. SomeClear (IORef (Maybe a))
1213+data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1215+data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1217+debugFinalize :: Bool
1218+debugFinalize = False
1220+mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1221+mkWeakPtrWithDebug x debugNote = do
1225+ then Just $ putStrLn $ "finalizing: " ++ debugNote
1228+type WeakList a = [Weak a]
1230+{-# INLINE withIncreasedDepth #-}
1232+withIncreasedDepth :: CanTrace x m => m a -> m a
1233+withIncreasedDepth a = do
1234+ spiderTimeline <- askSpiderTimelineEnv
1235+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1237+ liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1240+withIncreasedDepth :: m a -> m a
1241+withIncreasedDepth = id
1244+type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1246+{-# INLINE tracePropagate #-}
1247+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1248+tracePropagate p = traceWhen p debugPropagate
1250+{-# INLINE traceInvalidate #-}
1251+traceInvalidate :: String -> IO ()
1252+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1254+{-# INLINE traceWhen #-}
1255+traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1256+traceWhen p b message = traceMWhen p b $ return message
1258+{-# INLINE traceMWhen #-}
1259+traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1260+traceMWhen _ b getMessage = when b $ do
1261+ message <- getMessage
1263+ spiderTimeline <- askSpiderTimelineEnv
1264+ d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1268+ liftIO $ putStrLn $ replicate d ' ' <> message
1270+whoCreatedIORef :: IORef a -> IO [String]
1271+whoCreatedIORef (IORef a) = whoCreated $! a
1274+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1277+ (x :| xs) : t -> case groupByHead t of
1278+ [] -> [(x, xs :| [])]
1280+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1281+ | otherwise -> (x, xs :| []) : l
1283+listsToForest :: Eq a => [[a]] -> Forest a
1284+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1287+{-# INLINE propagateSubscriberHold #-}
1288+propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1289+propagateSubscriberHold h a = do
1290+ {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1291+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1292+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1293+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1294+ case {-# SCC "apply" #-} apply a v of
1295+ Nothing -> return ()
1297+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1298+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1299+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1300+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1302+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1304+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1305+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1307+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1309+ (!m, _) <- BehaviorM ask
1311+ Nothing -> return Nothing
1312+ Just (!wi, _) -> return $ Just wi
1314+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1316+ (!m, _) <- BehaviorM ask
1318+ Nothing -> return Nothing
1319+ Just (_, !p) -> return $ Just p
1321+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1322+askBehaviorHoldInits = do
1323+ (_, !his) <- BehaviorM ask
1326+{-# INLINE getDynHold #-}
1327+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1329+ mh <- liftIO $ readIORef $ unDyn d
1331+ Right h -> return h
1332+ Left (readV0, v') -> do
1333+ holdInits <- getDeferralQueue
1334+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1336+ liftIO $ writeIORef (unDyn d) $ Right h
1339+-- Always refers to 0
1340+{-# NOINLINE zeroRef #-}
1341+zeroRef :: IORef Height
1342+zeroRef = unsafePerformIO $ newIORef zeroHeight
1344+type CanSubscribe x m =
1345+ ( HasSpiderTimeline x
1346+ , HasCurrentHeight x m
1347+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1348+ , Defer SomeClear m -- Wiping out event firings
1349+ , Defer (SomeAssignment x) m -- Updating state
1350+ , Defer (SomeResetCoincidence x) m
1354+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1355+getRootSubscribed k r sub = do
1356+ mSubscribed <- readIORef $ rootSubscribed r
1357+ let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1358+ case DMap.lookup k mSubscribed of
1359+ Just subscribed -> {-# SCC "hitRoot" #-} do
1360+ sln <- subscribeRootSubscribed subscribed sub
1362+ return (sln, subscribed, occ)
1363+ Nothing -> {-# SCC "missRoot" #-} do
1364+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1365+ let !cached = rootSubscribed r
1366+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1367+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1368+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1369+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1370+ writeIORef uninitRef $! uninit
1371+ let !subscribed = RootSubscribed
1372+ { rootSubscribedKey = k
1373+ , rootSubscribedCachedSubscribed = cached
1374+ , rootSubscribedOccurrence = getOcc
1375+ , rootSubscribedSubscribers = subs
1376+ , rootSubscribedUninit = uninit
1377+ , rootSubscribedWeakSelf = weakSelf
1378+#ifdef DEBUG_NODEIDS
1379+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1382+ -- If we die at the same moment that all our children die, they will
1383+ -- try to clean us up but will fail because their Weak reference to us
1384+ -- will also be dead. So, if we are dying, check if there are any
1385+ -- children; since children don't bother cleaning themselves up if
1386+ -- their parents are already dead, I don't think there's a race
1387+ -- condition here. However, if there are any children, then we can
1388+ -- infer that we need to clean ourselves up, so we do.
1390+ cs <- readIORef $ _weakBag_children subs
1391+ when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)
1392+ writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)
1393+ 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
1395+ return (sln, subscribed, occ)
1397+#ifdef USE_TEMPLATE_HASKELL
1398+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1400+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1401+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1402+ rootSubscribedUninit self
1403+ modifyIORef' cached $ DMap.delete k
1405+{-# INLINE subscribeRootSubscribed #-}
1406+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1407+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1409+{-# INLINABLE getFanSubscribed #-}
1410+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)
1411+getFanSubscribed k f sub = do
1412+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1413+ case mSubscribed of
1414+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1415+ sln <- subscribeFanSubscribed k subscribed sub
1416+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1417+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1418+ Nothing -> {-# SCC "missFan" #-} do
1419+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1420+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1421+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1422+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1423+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1424+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1425+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1426+ occRef <- liftIO $ newIORef parentOcc
1427+ when (isJust parentOcc) $ scheduleClear occRef
1428+ let subscribed = FanSubscribed
1429+ { fanSubscribedCachedSubscribed = fanSubscribed f
1430+ , fanSubscribedOccurrence = occRef
1431+ , fanSubscribedParent = subscription
1432+ , fanSubscribedSubscribers = subscribersRef
1433+#ifdef DEBUG_NODEIDS
1434+ , fanSubscribedNodeId = unsafeNodeId f
1437+ let !self = (k, subscribed)
1438+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1439+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1440+ liftIO $ writeIORef subscribedRef $! subscribed
1441+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1442+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1444+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1445+cleanupFanSubscribed (k, subscribed) = do
1446+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1447+ let reducedSubscribers = DMap.delete k subscribers
1448+ if DMap.null reducedSubscribers
1450+ unsubscribe $ fanSubscribedParent subscribed
1451+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1452+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1453+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1455+{-# INLINE subscribeFanSubscribed #-}
1456+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1457+subscribeFanSubscribed k subscribed sub = do
1458+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1459+ case DMap.lookup k subscribers of
1460+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1461+ let !self = (k, subscribed)
1462+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1463+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1464+ 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
1466+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1468+{-# INLINABLE getSwitchSubscribed #-}
1469+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)
1470+getSwitchSubscribed s sub = do
1471+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1472+ case mSubscribed of
1473+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1474+ sln <- subscribeSwitchSubscribed subscribed sub
1475+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1476+ return (sln, subscribed, occ)
1477+ Nothing -> {-# SCC "missSwitch" #-} do
1478+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1479+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1480+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1481+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1482+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1483+ wiRef <- liftIO $ newIORef wi
1484+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1485+ holdInits <- getDeferralQueue
1486+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1487+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1488+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1489+ subscriptionRef <- liftIO $ newIORef subscription
1490+ occRef <- liftIO $ newIORef parentOcc
1491+ when (isJust parentOcc) $ scheduleClear occRef
1492+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1493+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1494+ let !subscribed = SwitchSubscribed
1495+ { switchSubscribedCachedSubscribed = switchSubscribed s
1496+ , switchSubscribedOccurrence = occRef
1497+ , switchSubscribedHeight = heightRef
1498+ , switchSubscribedSubscribers = subs
1499+ , switchSubscribedOwnInvalidator = i
1500+ , switchSubscribedOwnWeakInvalidator = wiRef
1501+ , switchSubscribedBehaviorParents = parentsRef
1502+ , switchSubscribedParent = switchParent s
1503+ , switchSubscribedCurrentParent = subscriptionRef
1504+ , switchSubscribedWeakSelf = weakSelf
1505+#ifdef DEBUG_NODEIDS
1506+ , switchSubscribedNodeId = unsafeNodeId s
1509+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1510+ liftIO $ writeIORef subscribedRef $! subscribed
1511+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1512+ return (slnForSub, subscribed, parentOcc)
1514+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1515+cleanupSwitchSubscribed subscribed = do
1516+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1517+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1518+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1520+{-# INLINE subscribeSwitchSubscribed #-}
1521+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1522+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1524+{-# INLINABLE getCoincidenceSubscribed #-}
1525+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)
1526+getCoincidenceSubscribed c sub = do
1527+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1528+ case mSubscribed of
1529+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1530+ sln <- subscribeCoincidenceSubscribed subscribed sub
1531+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1532+ return (sln, subscribed, occ)
1533+ Nothing -> {-# SCC "missCoincidence" #-} do
1534+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1535+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1536+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1537+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1538+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1539+ (occ, height, mInnerSubd) <- case outerOcc of
1540+ Nothing -> return (Nothing, outerHeight, Nothing)
1542+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1543+ return (occ, height, Just innerSubd)
1544+ occRef <- liftIO $ newIORef occ
1545+ when (isJust occ) $ scheduleClear occRef
1546+ heightRef <- liftIO $ newIORef height
1547+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1548+ scheduleClear innerSubdRef
1549+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1550+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1551+ let subscribed = CoincidenceSubscribed
1552+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1553+ , coincidenceSubscribedOccurrence = occRef
1554+ , coincidenceSubscribedHeight = heightRef
1555+ , coincidenceSubscribedSubscribers = subs
1556+ , coincidenceSubscribedOuter = subOuter
1557+ , coincidenceSubscribedOuterParent = outerSubscription
1558+ , coincidenceSubscribedInnerParent = innerSubdRef
1559+ , coincidenceSubscribedWeakSelf = weakSelf
1560+#ifdef DEBUG_NODEIDS
1561+ , coincidenceSubscribedNodeId = unsafeNodeId c
1564+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1565+ liftIO $ writeIORef subscribedRef $! subscribed
1566+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1567+ return (slnForSub, subscribed, occ)
1569+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1570+cleanupCoincidenceSubscribed subscribed = do
1571+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1572+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1574+{-# INLINE subscribeCoincidenceSubscribed #-}
1575+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1576+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1578+{-# INLINE merge #-}
1579+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1580+merge d = cacheEvent (mergeCheap d)
1582+{-# INLINE mergeWithMove #-}
1583+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1584+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1586+{-# INLINE [1] mergeCheap #-}
1587+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1588+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1590+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1591+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1592+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1593+ (mOldSubd, newPs) <- case me of
1594+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1596+ let s = subscriber $ return k
1597+ subscription@(EventSubscription _ subd) <- subscribe e s
1598+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1599+ let newParent = MergeSubscribedParent subscription
1600+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1601+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1602+ forM_ mOldSubd $ \oldSubd -> do
1603+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1604+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1605+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1606+ foldM f ([], oldParents) $ DMap.toList p
1607+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1608+ getInitialSubscribers initialParents subscriber = do
1609+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1610+ let s = subscriber $ return k
1611+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1612+ height <- liftIO $ getEventSubscribedHeight parentSubd
1613+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1614+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1615+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1616+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1618+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1619+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1621+{-# INLINE [1] mergeCheapWithMove #-}
1622+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1623+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1625+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1626+ updateMe subscriber heightBagRef oldParents p = do
1627+ -- Prepare new parents for insertion
1628+ let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1629+ subscribeParent k e = do
1630+ keyRef <- liftIO $ newIORef k
1631+ let s = subscriber $ liftIO $ readIORef keyRef
1632+ subscription@(EventSubscription _ subd) <- subscribe e s
1634+ newParentHeight <- getEventSubscribedHeight subd
1635+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1636+ return $ MergeSubscribedParentWithMove subscription keyRef
1637+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1638+ -- Collect old parents for deletion and update the keys of moved parents
1639+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1640+ moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
1642+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
1643+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1644+ return $ Just $ _mergeSubscribedParentWithMove_subscription parent
1646+ liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey
1648+ toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
1649+ return (toDelete, applyAlways p' oldParents)
1650+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1651+ getInitialSubscribers initialParents subscriber = do
1652+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1653+ keyRef <- liftIO $ newIORef k
1654+ let s = subscriber $ liftIO $ readIORef keyRef
1655+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1656+ height <- liftIO $ getEventSubscribedHeight parentSubd
1657+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1658+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1659+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1660+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1662+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1663+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1665+type MergeUpdateFunc k x p s
1666+ = (forall a. EventM x (k a) -> Subscriber x a)
1670+ -> EventM x ([EventSubscription x], DMap k s)
1672+type MergeInitFunc k x s
1674+ -> (forall a. EventM x (k a) -> Subscriber x a)
1675+ -> EventM x (DMap k Identity, [Height], DMap k s)
1677+type MergeDestroyFunc k s
1681+{-# INLINE mergeCheap' #-}
1682+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 -> (DMap k s -> Int) -> Dynamic x p -> Event x (DMap k Identity)
1683+mergeCheap' getInitialSubscribers updateFunc destroy numParents d = Event $ \sub -> do
1684+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1685+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1686+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1687+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1688+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1689+ let scheduleSelf height = scheduleMerge' height heightRef $ do
1690+ m <- liftIO $ readIORef accumRef
1691+ liftIO $ writeIORef accumRef $! DMap.empty
1692+ --TODO: Assert that m is not empty
1693+ subscriberPropagate sub m
1694+ invalidateMyHeight = do
1695+ oldHeight <- readIORef heightRef
1696+ 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
1697+ writeIORef heightRef $! invalidHeight
1698+ subscriberInvalidateHeight sub oldHeight
1699+ revalidateMyHeight = do
1700+ currentHeight <- readIORef heightRef
1701+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1702+ heights <- readIORef heightBagRef
1703+ parents <- readIORef parentsRef
1704+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1705+ case heightBagSize heights `compare` numParents parents of
1708+ let height = succHeight $ heightBagMax heights
1709+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1710+ writeIORef heightRef $! height
1711+ subscriberRecalculateHeight sub height
1712+ GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (numParents parents) <> ") for Merge"
1713+ subscriber :: forall a. EventM x (k a) -> Subscriber x a
1714+ subscriber getKey = Subscriber
1715+ { subscriberPropagate = \a -> do
1716+ oldM <- liftIO $ readIORef accumRef
1718+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1719+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1720+ liftIO $ writeIORef accumRef $! newM
1721+ when (DMap.null oldM) $ do -- Only schedule the firing once
1722+ height <- liftIO $ readIORef heightRef
1723+ --TODO: assertions about height
1724+ currentHeight <- getCurrentHeight
1725+ when (height <= currentHeight) $ do
1726+ if height /= invalidHeight
1728+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1729+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1732+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1733+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1734+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1738+ error $ "Causality loop found" <> cycleInfo
1739+ scheduleSelf height
1740+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1741+ modifyIORef' heightBagRef $ heightBagRemove old
1743+ , subscriberRecalculateHeight = \new -> do
1744+ modifyIORef' heightBagRef $ heightBagAdd new
1747+ let updateMe x = do
1748+ oldParents <- liftIO $ readIORef parentsRef
1749+ (subscriptionsToKill, newParents) <- updateFunc subscriber heightBagRef oldParents x
1750+ liftIO $ writeIORef parentsRef $! newParents
1751+ return subscriptionsToKill
1752+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents subscriber
1753+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1754+ myHeight = if invalidHeight `elem` heights
1756+ else succHeight $ heightBagMax myHeightBag
1757+ currentHeight <- getCurrentHeight
1758+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1759+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1761+ unless (DMap.null accum) $ do
1762+ scheduleSelf myHeight
1763+ occRef <- liftIO $ newIORef occ
1764+ when (isJust occ) $ scheduleClear occRef
1765+ liftIO $ writeIORef accumRef $! accum
1766+ liftIO $ writeIORef heightRef $! myHeight
1767+ liftIO $ writeIORef heightBagRef $! myHeightBag
1768+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1769+ liftIO $ writeIORef parentsRef $! initialParentState
1770+ defer $ SomeMergeInit $ do
1772+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1773+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1774+ defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1775+ , subscriberInvalidateHeight = \_ -> return ()
1776+ , subscriberRecalculateHeight = \_ -> return ()
1778+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1779+ forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1780+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1781+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1782+ -- its subscription.
1783+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1784+ let unsubscribeAll = destroy =<< readIORef parentsRef
1785+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1789+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1791+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1795+ , fanSubscribed = unsafeNewIORef e Nothing
1797+ in EventSelector $ \k -> eventFan k f
1799+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1800+runHoldInits holdInitRef mergeInitRef = do
1801+ holdInits <- liftIO $ readIORef holdInitRef
1802+ mergeInits <- liftIO $ readIORef mergeInitRef
1803+ unless (null holdInits && null mergeInits) $ do
1804+ liftIO $ writeIORef holdInitRef []
1805+ liftIO $ writeIORef mergeInitRef []
1806+ mapM_ initHold holdInits
1807+ mapM_ unSomeMergeInit mergeInits
1808+ runHoldInits holdInitRef mergeInitRef
1810+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1811+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1813+newEventEnv :: IO (EventEnv x)
1815+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1816+ holdInitRef <- newIORef []
1817+ mergeUpdateRef <- newIORef []
1818+ mergeInitRef <- newIORef []
1819+ heightRef <- newIORef zeroHeight
1820+ toClearRef <- newIORef []
1821+ toClearRootRef <- newIORef []
1822+ coincidenceInfosRef <- newIORef []
1823+ delayedRef <- newIORef IntMap.empty
1824+ return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1826+clearEventEnv :: EventEnv x -> IO ()
1827+clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1828+ writeIORef toAssignRef []
1829+ writeIORef holdInitRef []
1830+ writeIORef mergeUpdateRef []
1831+ writeIORef mergeInitRef []
1832+ writeIORef heightRef zeroHeight
1833+ writeIORef toClearRef []
1834+ writeIORef toClearRootRef []
1835+ writeIORef coincidenceInfosRef []
1836+ writeIORef delayedRef IntMap.empty
1838+-- | Run an event action outside of a frame
1839+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1840+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
1841+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
1844+ runHoldInits (eventEnvHoldInits 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
1846+ result <- runEventM go
1847+ toClear <- readIORef $ eventEnvClears env
1848+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1849+ toClearRoot <- readIORef $ eventEnvRootClears env
1850+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1851+ toAssign <- readIORef $ eventEnvAssignments env
1852+ toReconnectRef <- newIORef []
1853+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1854+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1856+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1857+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1858+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1859+ writeIORef (eventEnvMergeUpdates env) []
1860+ when debugPropagate $ putStrLn "Updating merges"
1861+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1862+ when debugPropagate $ putStrLn "Updating merges done"
1863+ toReconnect <- readIORef toReconnectRef
1865+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1866+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1867+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1868+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1870+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1871+ wi' <- mkWeakPtrWithDebug i "wi'"
1872+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1873+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1874+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1875+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1876+ runEventM $ runHoldInits (eventEnvHoldInits 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
1877+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1878+ sub <- newSubscriberSwitch subscribed
1879+ 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
1881+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1882+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1883+ EventRoot _ -> "EventRoot"
1884+ EventNever -> "EventNever"
1885+ _ -> "something else"
1887+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1888+ return oldSubscription
1889+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1890+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1891+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1892+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1893+ parentHeight <- getEventSubscribedHeight subd'
1894+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1895+ when (parentHeight /= myHeight) $ do
1896+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1897+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1898+ 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
1899+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1900+ unsubscribe subscription
1901+ mapM_ invalidateCoincidenceHeight mcs
1902+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1903+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1904+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1905+ height <- calculateSwitchHeight subscribed
1906+ updateSwitchHeight height subscribed
1909+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1911+{-# INLINE zeroHeight #-}
1912+zeroHeight :: Height
1913+zeroHeight = Height 0
1915+{-# INLINE invalidHeight #-}
1916+invalidHeight :: Height
1917+invalidHeight = Height (-1000)
1920+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1921+{-# INLINE invalidHeightBeingTraversed #-}
1922+invalidHeightBeingTraversed :: Height
1923+invalidHeightBeingTraversed = Height (-1001)
1926+{-# INLINE succHeight #-}
1927+succHeight :: Height -> Height
1928+succHeight h@(Height a) =
1929+ if h == invalidHeight
1931+ else Height $ succ a
1933+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1934+invalidateCoincidenceHeight subscribed = do
1935+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1936+ when (oldHeight /= invalidHeight) $ do
1937+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1938+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1940+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1941+updateSwitchHeight new subscribed = do
1942+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1943+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1944+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1945+ writeIORef (switchSubscribedHeight subscribed) $! new
1946+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1948+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1949+recalculateCoincidenceHeight subscribed = do
1950+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1951+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1952+ height <- calculateCoincidenceHeight subscribed
1953+ when (height /= invalidHeight) $ do
1954+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1955+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1957+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1958+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1960+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1961+calculateCoincidenceHeight subscribed = do
1962+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1963+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1964+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1966+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1968+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1969+invalidate toReconnectRef wis = do
1970+ forM_ wis $ \wi -> do
1974+ traceInvalidate "invalidate Dead"
1975+ return () --TODO: Should we clean this up here?
1977+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1979+ InvalidatorPull p -> do
1980+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1981+ mVal <- readIORef $ pullValue p
1982+ forM_ mVal $ \val -> do
1983+ writeIORef (pullValue p) Nothing
1984+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1985+ InvalidatorSwitch subscribed -> do
1986+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1987+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1988+ 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
1990+--------------------------------------------------------------------------------
1991+-- Reflex integration
1992+--------------------------------------------------------------------------------
1994+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1995+-- When we're specializing, we include this from Reflex.Class instead, because
1996+-- it needs access to these types; when we're not, we want them here, so our
1997+-- instance isn't an orphan instance.
1998+#include "SpiderTimeline.include.hs"
1999+#include "SpiderTimelineHost.include.hs"
2002+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
2003+unsafeNewSpiderTimelineEnv = do
2007+ depthRef <- newIORef 0
2009+ return $ SpiderTimelineEnv
2010+ { _spiderTimeline_lock = lock
2011+ , _spiderTimeline_eventEnv = env
2013+ , _spiderTimeline_depth = depthRef
2017+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2018+-- | Create a new SpiderTimelineEnv
2019+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2020+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2022+data LocalSpiderTimeline x s
2024+instance Reifies s (SpiderTimelineEnv x) =>
2025+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2026+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2030+ -> SpiderTimelineEnv x
2031+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2032+localSpiderTimeline _ = unsafeCoerce
2034+-- | Pass a new timeline to the given function.
2035+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2036+withSpiderTimeline k = do
2037+ env <- unsafeNewSpiderTimelineEnv
2038+ reify env $ \s -> k $ localSpiderTimeline s env
2041+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2043+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2045+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2046+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2047+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2048+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2049+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2050+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2051+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2052+ type PullM (SpiderTimeline x) = SpiderPullM x
2053+ type PushM (SpiderTimeline x) = SpiderPushM x
2054+ {-# INLINABLE never #-}
2055+ never = SpiderEvent eventNever
2056+ {-# INLINABLE constant #-}
2057+ constant = SpiderBehavior . behaviorConst
2058+ {-# INLINE push #-}
2059+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2060+ {-# INLINE pushCheap #-}
2061+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2062+ {-# INLINABLE pull #-}
2063+ pull = SpiderBehavior . pull . coerce
2064+ {-# INLINABLE merge #-}
2065+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2066+ {-# INLINABLE fan #-}
2067+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2068+ {-# INLINABLE switch #-}
2069+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2070+ {-# INLINABLE coincidence #-}
2071+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2072+ {-# INLINABLE current #-}
2073+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2074+ {-# INLINABLE updated #-}
2075+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2076+ {-# INLINABLE unsafeBuildDynamic #-}
2077+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
2078+ {-# INLINABLE unsafeBuildIncremental #-}
2079+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2080+ {-# INLINABLE mergeIncremental #-}
2081+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2082+ {-# INLINABLE mergeIncrementalWithMove #-}
2083+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2084+ {-# INLINABLE currentIncremental #-}
2085+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2086+ {-# INLINABLE updatedIncremental #-}
2087+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2088+ {-# INLINABLE incrementalToDynamic #-}
2089+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2090+ c <- readBehaviorUntracked $ dynamicCurrent i
2091+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2092+ eventCoercion Coercion = Coercion
2093+ behaviorCoercion Coercion = Coercion
2094+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2097+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2099+data SpiderEventHandle x a = SpiderEventHandle
2100+ { spiderEventHandleSubscription :: EventSubscription x
2101+ , spiderEventHandleValue :: IORef (Maybe a)
2104+instance MonadRef (EventM x) where
2105+ type Ref (EventM x) = Ref IO
2106+ {-# INLINABLE newRef #-}
2107+ {-# INLINABLE readRef #-}
2108+ {-# INLINABLE writeRef #-}
2109+ newRef = liftIO . newRef
2110+ readRef = liftIO . readRef
2111+ writeRef r a = liftIO $ writeRef r a
2113+instance MonadAtomicRef (EventM x) where
2114+ {-# INLINABLE atomicModifyRef #-}
2115+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2117+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2118+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2120+instance Monad (SpiderHost x) where
2121+ {-# INLINABLE (>>=) #-}
2122+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2123+ {-# INLINABLE (>>) #-}
2124+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2125+ {-# INLINABLE return #-}
2126+ return x = SpiderHost $ return x
2127+ {-# INLINABLE fail #-}
2128+ fail s = SpiderHost $ fail s
2130+-- | Run an action affecting the global Spider timeline; this will be guarded by
2131+-- a mutex for that timeline
2132+runSpiderHost :: SpiderHost Global a -> IO a
2133+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2135+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2136+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2137+-- mutex for that timeline
2138+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2139+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2142+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2144+instance Monad (SpiderHostFrame x) where
2145+ {-# INLINABLE (>>=) #-}
2146+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2147+ {-# INLINABLE (>>) #-}
2148+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2149+ {-# INLINABLE return #-}
2150+ return x = SpiderHostFrame $ return x
2151+ {-# INLINABLE fail #-}
2152+ fail s = SpiderHostFrame $ fail s
2154+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2155+newEventWithTriggerIO f = do
2156+ es <- newFanEventWithTriggerIO $ \Refl -> f
2157+ return $ select es Refl
2159+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2160+newFanEventWithTriggerIO f = do
2161+ occRef <- newIORef DMap.empty
2162+ subscribedRef <- newIORef DMap.empty
2164+ { rootOccurrence = occRef
2165+ , rootSubscribed = subscribedRef
2168+ return $ EventSelector $ \k -> eventRoot k r
2170+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2172+instance MonadRef (SpiderHost x) where
2173+ type Ref (SpiderHost x) = Ref IO
2174+ newRef = SpiderHost . newRef
2175+ readRef = SpiderHost . readRef
2176+ writeRef r = SpiderHost . writeRef r
2178+instance MonadAtomicRef (SpiderHost x) where
2179+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2181+instance MonadRef (SpiderHostFrame x) where
2182+ type Ref (SpiderHostFrame x) = Ref IO
2183+ newRef = SpiderHostFrame . newRef
2184+ readRef = SpiderHostFrame . readRef
2185+ writeRef r = SpiderHostFrame . writeRef r
2187+instance MonadAtomicRef (SpiderHostFrame x) where
2188+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2190+instance PrimMonad (SpiderHostFrame x) where
2191+ type PrimState (SpiderHostFrame x) = PrimState IO
2192+ primitive = SpiderHostFrame . EventM . primitive