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