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