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