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