@@ -0,0 +1,2176 @@
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)
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+ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1369+ 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
1370+ occ <- getOcc
1371+ return (sln, subscribed, occ)
1372+
1373+#ifdef USE_TEMPLATE_HASKELL
1374+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1375+#endif
1376+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1377+cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1378+ rootSubscribedUninit self
1379+ modifyIORef' cached $ DMap.delete k
1380+
1381+{-# INLINE subscribeRootSubscribed #-}
1382+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1383+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1384+
1385+{-# INLINABLE getFanSubscribed #-}
1386+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)
1387+getFanSubscribed k f sub = do
1388+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1389+ case mSubscribed of
1390+ Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1391+ sln <- subscribeFanSubscribed k subscribed sub
1392+ occ <- readIORef $ fanSubscribedOccurrence subscribed
1393+ return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1394+ Nothing -> {-# SCC "missFan" #-} do
1395+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1396+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1397+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1398+ (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1399+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1400+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1401+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1402+ occRef <- liftIO $ newIORef parentOcc
1403+ when (isJust parentOcc) $ scheduleClear occRef
1404+ let subscribed = FanSubscribed
1405+ { fanSubscribedCachedSubscribed = fanSubscribed f
1406+ , fanSubscribedOccurrence = occRef
1407+ , fanSubscribedParent = subscription
1408+ , fanSubscribedSubscribers = subscribersRef
1409+#ifdef DEBUG_NODEIDS
1410+ , fanSubscribedNodeId = unsafeNodeId f
1411+#endif
1412+ }
1413+ let !self = (k, subscribed)
1414+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1415+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1416+ liftIO $ writeIORef subscribedRef $! subscribed
1417+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1418+ return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1419+
1420+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1421+cleanupFanSubscribed (k, subscribed) = do
1422+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1423+ let reducedSubscribers = DMap.delete k subscribers
1424+ if DMap.null reducedSubscribers
1425+ then do
1426+ unsubscribe $ fanSubscribedParent subscribed
1427+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1428+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1429+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1430+
1431+{-# INLINE subscribeFanSubscribed #-}
1432+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1433+subscribeFanSubscribed k subscribed sub = do
1434+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1435+ case DMap.lookup k subscribers of
1436+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1437+ let !self = (k, subscribed)
1438+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1439+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1440+ 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
1441+ return sln
1442+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1443+
1444+{-# INLINABLE getSwitchSubscribed #-}
1445+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)
1446+getSwitchSubscribed s sub = do
1447+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1448+ case mSubscribed of
1449+ Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1450+ sln <- subscribeSwitchSubscribed subscribed sub
1451+ occ <- readIORef $ switchSubscribedOccurrence subscribed
1452+ return (sln, subscribed, occ)
1453+ Nothing -> {-# SCC "missSwitch" #-} do
1454+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1455+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1456+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1457+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1458+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1459+ wiRef <- liftIO $ newIORef wi
1460+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1461+ holdInits <- getDeferralQueue
1462+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1463+ (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1464+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1465+ subscriptionRef <- liftIO $ newIORef subscription
1466+ occRef <- liftIO $ newIORef parentOcc
1467+ when (isJust parentOcc) $ scheduleClear occRef
1468+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1469+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1470+ let !subscribed = SwitchSubscribed
1471+ { switchSubscribedCachedSubscribed = switchSubscribed s
1472+ , switchSubscribedOccurrence = occRef
1473+ , switchSubscribedHeight = heightRef
1474+ , switchSubscribedSubscribers = subs
1475+ , switchSubscribedOwnInvalidator = i
1476+ , switchSubscribedOwnWeakInvalidator = wiRef
1477+ , switchSubscribedBehaviorParents = parentsRef
1478+ , switchSubscribedParent = switchParent s
1479+ , switchSubscribedCurrentParent = subscriptionRef
1480+ , switchSubscribedWeakSelf = weakSelf
1481+#ifdef DEBUG_NODEIDS
1482+ , switchSubscribedNodeId = unsafeNodeId s
1483+#endif
1484+ }
1485+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1486+ liftIO $ writeIORef subscribedRef $! subscribed
1487+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1488+ return (slnForSub, subscribed, parentOcc)
1489+
1490+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1491+cleanupSwitchSubscribed subscribed = do
1492+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1493+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1494+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1495+
1496+{-# INLINE subscribeSwitchSubscribed #-}
1497+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1498+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1499+
1500+{-# INLINABLE getCoincidenceSubscribed #-}
1501+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)
1502+getCoincidenceSubscribed c sub = do
1503+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1504+ case mSubscribed of
1505+ Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1506+ sln <- subscribeCoincidenceSubscribed subscribed sub
1507+ occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1508+ return (sln, subscribed, occ)
1509+ Nothing -> {-# SCC "missCoincidence" #-} do
1510+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1511+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1512+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1513+ (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1514+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1515+ (occ, height, mInnerSubd) <- case outerOcc of
1516+ Nothing -> return (Nothing, outerHeight, Nothing)
1517+ Just o -> do
1518+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1519+ return (occ, height, Just innerSubd)
1520+ occRef <- liftIO $ newIORef occ
1521+ when (isJust occ) $ scheduleClear occRef
1522+ heightRef <- liftIO $ newIORef height
1523+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1524+ scheduleClear innerSubdRef
1525+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1526+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1527+ let subscribed = CoincidenceSubscribed
1528+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1529+ , coincidenceSubscribedOccurrence = occRef
1530+ , coincidenceSubscribedHeight = heightRef
1531+ , coincidenceSubscribedSubscribers = subs
1532+ , coincidenceSubscribedOuter = subOuter
1533+ , coincidenceSubscribedOuterParent = outerSubscription
1534+ , coincidenceSubscribedInnerParent = innerSubdRef
1535+ , coincidenceSubscribedWeakSelf = weakSelf
1536+#ifdef DEBUG_NODEIDS
1537+ , coincidenceSubscribedNodeId = unsafeNodeId c
1538+#endif
1539+ }
1540+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1541+ liftIO $ writeIORef subscribedRef $! subscribed
1542+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1543+ return (slnForSub, subscribed, occ)
1544+
1545+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1546+cleanupCoincidenceSubscribed subscribed = do
1547+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1548+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1549+
1550+{-# INLINE subscribeCoincidenceSubscribed #-}
1551+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1552+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1553+
1554+{-# INLINE merge #-}
1555+merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1556+merge d = cacheEvent (mergeCheap d)
1557+
1558+{-# INLINE mergeWithMove #-}
1559+mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1560+mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1561+
1562+{-# INLINE [1] mergeCheap #-}
1563+mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1564+mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1565+ where
1566+ updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1567+ updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
1568+ let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1569+ (mOldSubd, newPs) <- case me of
1570+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1571+ Just e -> do
1572+ let s = subscriber $ return k
1573+ subscription@(EventSubscription _ subd) <- subscribe e s
1574+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1575+ let newParent = MergeSubscribedParent subscription
1576+ liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1577+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1578+ forM_ mOldSubd $ \oldSubd -> do
1579+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1580+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1581+ return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1582+ foldM f ([], oldParents) $ DMap.toList p
1583+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1584+ getInitialSubscribers initialParents subscriber = do
1585+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1586+ let s = subscriber $ return k
1587+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1588+ height <- liftIO $ getEventSubscribedHeight parentSubd
1589+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1590+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1591+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1592+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1593+ )
1594+ destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
1595+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
1596+
1597+{-# INLINE [1] mergeCheapWithMove #-}
1598+mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1599+mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy DMap.size
1600+ where
1601+ updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1602+ updateMe subscriber heightBagRef oldParents pWrapped = do
1603+ let p = unPatchDMapWithMove pWrapped
1604+ let f (subscriptionsToKill, ps) (k :=> edit) = do
1605+ let deleteHere = return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1606+ insertHere e = do
1607+ keyRef <- liftIO $ newIORef k
1608+ let s = subscriber $ liftIO $ readIORef keyRef
1609+ subscription@(EventSubscription _ subd) <- subscribe e s
1610+ liftIO $ do
1611+ newParentHeight <- getEventSubscribedHeight subd
1612+ let newParent = MergeSubscribedParentWithMove subscription keyRef
1613+ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1614+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1615+ (mOldSubd, newPs) <- case edit of
1616+ DMapEdit_Delete moved -> do
1617+ (toDelete, newPs) <- deleteHere
1618+ return (if moved then Nothing else toDelete, newPs)
1619+ DMapEdit_Insert moved e -> do
1620+ (toDelete, newPs) <- insertHere e
1621+ return (if moved then Nothing else toDelete, newPs)
1622+ DMapEdit_Move moved sourceKey -> do
1623+ (toDelete, newPs) <- case DMap.lookup sourceKey ps of
1624+ Nothing -> deleteHere
1625+ Just s@(MergeSubscribedParentWithMove _ keyRef) -> do
1626+ liftIO $ writeIORef keyRef k
1627+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k s ps
1628+ return (if moved then Nothing else toDelete, newPs)
1629+ forM_ mOldSubd $ \oldSubd -> do
1630+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription oldSubd
1631+ liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1632+ return (maybeToList (_mergeSubscribedParentWithMove_subscription <$> mOldSubd) ++ subscriptionsToKill, newPs)
1633+ foldM f ([], oldParents) $ DMap.toList p
1634+ getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1635+ getInitialSubscribers initialParents subscriber = do
1636+ subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1637+ keyRef <- liftIO $ newIORef k
1638+ let s = subscriber $ liftIO $ readIORef keyRef
1639+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1640+ height <- liftIO $ getEventSubscribedHeight parentSubd
1641+ return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1642+ return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1643+ , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1644+ , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1645+ )
1646+ destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
1647+ destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
1648+
1649+type MergeUpdateFunc k x p s
1650+ = (forall a. EventM x (k a) -> Subscriber x a)
1651+ -> IORef HeightBag
1652+ -> DMap k s
1653+ -> p
1654+ -> EventM x ([EventSubscription x], DMap k s)
1655+
1656+type MergeInitFunc k x s
1657+ = DMap k (Event x)
1658+ -> (forall a. EventM x (k a) -> Subscriber x a)
1659+ -> EventM x (DMap k Identity, [Height], DMap k s)
1660+
1661+type MergeDestroyFunc k s
1662+ = DMap k s
1663+ -> IO ()
1664+
1665+{-# INLINE mergeCheap' #-}
1666+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)
1667+mergeCheap' getInitialSubscribers updateFunc destroy numParents d = Event $ \sub -> do
1668+ initialParents <- readBehaviorUntracked $ dynamicCurrent d
1669+ accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1670+ heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1671+ heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1672+ parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1673+ let scheduleSelf height = scheduleMerge' height heightRef $ do
1674+ m <- liftIO $ readIORef accumRef
1675+ liftIO $ writeIORef accumRef $! DMap.empty
1676+ --TODO: Assert that m is not empty
1677+ subscriberPropagate sub m
1678+ invalidateMyHeight = do
1679+ oldHeight <- readIORef heightRef
1680+ 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
1681+ writeIORef heightRef $! invalidHeight
1682+ subscriberInvalidateHeight sub oldHeight
1683+ revalidateMyHeight = do
1684+ currentHeight <- readIORef heightRef
1685+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1686+ heights <- readIORef heightBagRef
1687+ parents <- readIORef parentsRef
1688+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1689+ case heightBagSize heights `compare` numParents parents of
1690+ LT -> return ()
1691+ EQ -> do
1692+ let height = succHeight $ heightBagMax heights
1693+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1694+ writeIORef heightRef $! height
1695+ subscriberRecalculateHeight sub height
1696+ GT -> error $ "revalidateMergeHeight: more heights than parents for Merge"
1697+ subscriber :: forall a. EventM x (k a) -> Subscriber x a
1698+ subscriber getKey = Subscriber
1699+ { subscriberPropagate = \a -> do
1700+ oldM <- liftIO $ readIORef accumRef
1701+ k <- getKey
1702+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1703+ tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1704+ liftIO $ writeIORef accumRef $! newM
1705+ when (DMap.null oldM) $ do -- Only schedule the firing once
1706+ height <- liftIO $ readIORef heightRef
1707+ --TODO: assertions about height
1708+ currentHeight <- getCurrentHeight
1709+ when (height <= currentHeight) $ do
1710+ if height /= invalidHeight
1711+ then do
1712+ myStack <- liftIO $ whoCreatedIORef undefined --TODO
1713+ error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1714+ else liftIO $ do
1715+#ifdef DEBUG_CYCLES
1716+ nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1717+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1718+ let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1719+#else
1720+ let cycleInfo = ""
1721+#endif
1722+ error $ "Causality loop found" <> cycleInfo
1723+ scheduleSelf height
1724+ , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1725+ modifyIORef' heightBagRef $ heightBagRemove old
1726+ invalidateMyHeight
1727+ , subscriberRecalculateHeight = \new -> do
1728+ modifyIORef' heightBagRef $ heightBagAdd new
1729+ revalidateMyHeight
1730+ }
1731+ let updateMe x = do
1732+ oldParents <- liftIO $ readIORef parentsRef
1733+ (subscriptionsToKill, newParents) <- updateFunc subscriber heightBagRef oldParents x
1734+ liftIO $ writeIORef parentsRef $! newParents
1735+ return subscriptionsToKill
1736+ (dm, heights, initialParentState) <- getInitialSubscribers initialParents subscriber
1737+ let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1738+ myHeight = if invalidHeight `elem` heights
1739+ then invalidHeight
1740+ else succHeight $ heightBagMax myHeightBag
1741+ currentHeight <- getCurrentHeight
1742+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1743+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1744+ else (Nothing, dm)
1745+ unless (DMap.null accum) $ do
1746+ scheduleSelf myHeight
1747+ occRef <- liftIO $ newIORef occ
1748+ when (isJust occ) $ scheduleClear occRef
1749+ liftIO $ writeIORef accumRef $! accum
1750+ liftIO $ writeIORef heightRef $! myHeight
1751+ liftIO $ writeIORef heightBagRef $! myHeightBag
1752+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1753+ liftIO $ writeIORef parentsRef $! initialParentState
1754+ defer $ SomeMergeInit $ do
1755+ let s = Subscriber
1756+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1757+ tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1758+ defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1759+ , subscriberInvalidateHeight = \_ -> return ()
1760+ , subscriberRecalculateHeight = \_ -> return ()
1761+ }
1762+ (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1763+ forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1764+ -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1765+ -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1766+ -- its subscription.
1767+ liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1768+ let unsubscribeAll = destroy =<< readIORef parentsRef
1769+ return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1770+ , occ
1771+ )
1772+
1773+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1774+
1775+fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1776+fan e =
1777+ let f = Fan
1778+ { fanParent = e
1779+ , fanSubscribed = unsafeNewIORef e Nothing
1780+ }
1781+ in EventSelector $ \k -> eventFan k f
1782+
1783+runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1784+runHoldInits holdInitRef mergeInitRef = do
1785+ holdInits <- liftIO $ readIORef holdInitRef
1786+ mergeInits <- liftIO $ readIORef mergeInitRef
1787+ unless (null holdInits && null mergeInits) $ do
1788+ liftIO $ writeIORef holdInitRef []
1789+ liftIO $ writeIORef mergeInitRef []
1790+ mapM_ initHold holdInits
1791+ mapM_ unSomeMergeInit mergeInits
1792+ runHoldInits holdInitRef mergeInitRef
1793+
1794+initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1795+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1796+
1797+newEventEnv :: IO (EventEnv x)
1798+newEventEnv = do
1799+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1800+ holdInitRef <- newIORef []
1801+ mergeUpdateRef <- newIORef []
1802+ mergeInitRef <- newIORef []
1803+ heightRef <- newIORef zeroHeight
1804+ toClearRef <- newIORef []
1805+ toClearRootRef <- newIORef []
1806+ coincidenceInfosRef <- newIORef []
1807+ delayedRef <- newIORef IntMap.empty
1808+ return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1809+
1810+clearEventEnv :: EventEnv x -> IO ()
1811+clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1812+ writeIORef toAssignRef []
1813+ writeIORef holdInitRef []
1814+ writeIORef mergeUpdateRef []
1815+ writeIORef mergeInitRef []
1816+ writeIORef heightRef zeroHeight
1817+ writeIORef toClearRef []
1818+ writeIORef toClearRootRef []
1819+ writeIORef coincidenceInfosRef []
1820+ writeIORef delayedRef IntMap.empty
1821+
1822+-- | Run an event action outside of a frame
1823+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1824+runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
1825+ let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
1826+ let go = do
1827+ result <- a
1828+ 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
1829+ return result
1830+ result <- runEventM go
1831+ toClear <- readIORef $ eventEnvClears env
1832+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1833+ toClearRoot <- readIORef $ eventEnvRootClears env
1834+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1835+ toAssign <- readIORef $ eventEnvAssignments env
1836+ toReconnectRef <- newIORef []
1837+ coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1838+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1839+ writeIORef vRef v
1840+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1841+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1842+ mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1843+ writeIORef (eventEnvMergeUpdates env) []
1844+ when debugPropagate $ putStrLn "Updating merges"
1845+ mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1846+ when debugPropagate $ putStrLn "Updating merges done"
1847+ toReconnect <- readIORef toReconnectRef
1848+ clearEventEnv env
1849+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1850+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1851+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1852+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1853+ finalize wi
1854+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1855+ wi' <- mkWeakPtrWithDebug i "wi'"
1856+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1857+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1858+ writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1859+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1860+ 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
1861+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1862+ sub <- newSubscriberSwitch subscribed
1863+ 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
1864+ {-
1865+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1866+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1867+ EventRoot _ -> "EventRoot"
1868+ EventNever -> "EventNever"
1869+ _ -> "something else"
1870+ -}
1871+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1872+ return oldSubscription
1873+ liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1874+ liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1875+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1876+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1877+ parentHeight <- getEventSubscribedHeight subd'
1878+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1879+ when (parentHeight /= myHeight) $ do
1880+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1881+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1882+ 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
1883+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1884+ unsubscribe subscription
1885+ mapM_ invalidateCoincidenceHeight mcs
1886+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1887+ mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1888+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1889+ height <- calculateSwitchHeight subscribed
1890+ updateSwitchHeight height subscribed
1891+ return result
1892+
1893+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1894+
1895+{-# INLINE zeroHeight #-}
1896+zeroHeight :: Height
1897+zeroHeight = Height 0
1898+
1899+{-# INLINE invalidHeight #-}
1900+invalidHeight :: Height
1901+invalidHeight = Height (-1000)
1902+
1903+#ifdef DEBUG_CYCLES
1904+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1905+{-# INLINE invalidHeightBeingTraversed #-}
1906+invalidHeightBeingTraversed :: Height
1907+invalidHeightBeingTraversed = Height (-1001)
1908+#endif
1909+
1910+{-# INLINE succHeight #-}
1911+succHeight :: Height -> Height
1912+succHeight h@(Height a) =
1913+ if h == invalidHeight
1914+ then invalidHeight
1915+ else Height $ succ a
1916+
1917+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1918+invalidateCoincidenceHeight subscribed = do
1919+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1920+ when (oldHeight /= invalidHeight) $ do
1921+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1922+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1923+
1924+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1925+updateSwitchHeight new subscribed = do
1926+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1927+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1928+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1929+ writeIORef (switchSubscribedHeight subscribed) $! new
1930+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1931+
1932+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1933+recalculateCoincidenceHeight subscribed = do
1934+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1935+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1936+ height <- calculateCoincidenceHeight subscribed
1937+ when (height /= invalidHeight) $ do
1938+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1939+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1940+
1941+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1942+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1943+
1944+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1945+calculateCoincidenceHeight subscribed = do
1946+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1947+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1948+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1949+
1950+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1951+
1952+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1953+invalidate toReconnectRef wis = do
1954+ forM_ wis $ \wi -> do
1955+ mi <- deRefWeak wi
1956+ case mi of
1957+ Nothing -> do
1958+ traceInvalidate "invalidate Dead"
1959+ return () --TODO: Should we clean this up here?
1960+ Just i -> do
1961+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1962+ case i of
1963+ InvalidatorPull p -> do
1964+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1965+ mVal <- readIORef $ pullValue p
1966+ forM_ mVal $ \val -> do
1967+ writeIORef (pullValue p) Nothing
1968+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1969+ InvalidatorSwitch subscribed -> do
1970+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1971+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1972+ 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
1973+
1974+--------------------------------------------------------------------------------
1975+-- Reflex integration
1976+--------------------------------------------------------------------------------
1977+
1978+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1979+-- When we're specializing, we include this from Reflex.Class instead, because
1980+-- it needs access to these types; when we're not, we want them here, so our
1981+-- instance isn't an orphan instance.
1982+#include "SpiderTimeline.include.hs"
1983+#include "SpiderTimelineHost.include.hs"
1984+#endif
1985+
1986+unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
1987+unsafeNewSpiderTimelineEnv = do
1988+ lock <- newMVar ()
1989+ env <- newEventEnv
1990+#ifdef DEBUG
1991+ depthRef <- newIORef 0
1992+#endif
1993+ return $ SpiderTimelineEnv
1994+ { _spiderTimeline_lock = lock
1995+ , _spiderTimeline_eventEnv = env
1996+#ifdef DEBUG
1997+ , _spiderTimeline_depth = depthRef
1998+#endif
1999+ }
2000+
2001+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2002+-- | Create a new SpiderTimelineEnv
2003+newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2004+newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2005+
2006+data LocalSpiderTimeline x s
2007+
2008+instance Reifies s (SpiderTimelineEnv x) =>
2009+ HasSpiderTimeline (LocalSpiderTimeline x s) where
2010+ spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2011+
2012+localSpiderTimeline
2013+ :: Proxy s
2014+ -> SpiderTimelineEnv x
2015+ -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2016+localSpiderTimeline _ = unsafeCoerce
2017+
2018+-- | Pass a new timeline to the given function.
2019+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
2020+withSpiderTimeline k = do
2021+ env <- unsafeNewSpiderTimelineEnv
2022+ reify env $ \s -> k $ localSpiderTimeline s env
2023+#endif
2024+
2025+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2026+
2027+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2028+
2029+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2030+instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
2031+ {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
2032+ newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2033+ newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2034+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2035+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2036+ type PullM (SpiderTimeline x) = SpiderPullM x
2037+ type PushM (SpiderTimeline x) = SpiderPushM x
2038+ {-# INLINABLE never #-}
2039+ never = SpiderEvent eventNever
2040+ {-# INLINABLE constant #-}
2041+ constant = SpiderBehavior . behaviorConst
2042+ {-# INLINE push #-}
2043+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2044+ {-# INLINE pushCheap #-}
2045+ pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
2046+ {-# INLINABLE pull #-}
2047+ pull = SpiderBehavior . pull . coerce
2048+ {-# INLINABLE merge #-}
2049+ merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2050+ {-# INLINABLE fan #-}
2051+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2052+ {-# INLINABLE switch #-}
2053+ switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2054+ {-# INLINABLE coincidence #-}
2055+ coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2056+ {-# INLINABLE current #-}
2057+ current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2058+ {-# INLINABLE updated #-}
2059+ updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2060+ {-# INLINABLE unsafeBuildDynamic #-}
2061+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
2062+ {-# INLINABLE unsafeBuildIncremental #-}
2063+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2064+ {-# INLINABLE mergeIncremental #-}
2065+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2066+ {-# INLINABLE mergeIncrementalWithMove #-}
2067+ mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2068+ {-# INLINABLE currentIncremental #-}
2069+ currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2070+ {-# INLINABLE updatedIncremental #-}
2071+ updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2072+ {-# INLINABLE incrementalToDynamic #-}
2073+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2074+ c <- readBehaviorUntracked $ dynamicCurrent i
2075+ return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
2076+ eventCoercion Coercion = Coercion
2077+ behaviorCoercion Coercion = Coercion
2078+ dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2079+#endif
2080+
2081+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2082+
2083+data SpiderEventHandle x a = SpiderEventHandle
2084+ { spiderEventHandleSubscription :: EventSubscription x
2085+ , spiderEventHandleValue :: IORef (Maybe a)
2086+ }
2087+
2088+instance MonadRef (EventM x) where
2089+ type Ref (EventM x) = Ref IO
2090+ {-# INLINABLE newRef #-}
2091+ {-# INLINABLE readRef #-}
2092+ {-# INLINABLE writeRef #-}
2093+ newRef = liftIO . newRef
2094+ readRef = liftIO . readRef
2095+ writeRef r a = liftIO $ writeRef r a
2096+
2097+instance MonadAtomicRef (EventM x) where
2098+ {-# INLINABLE atomicModifyRef #-}
2099+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2100+
2101+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2102+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2103+
2104+instance Monad (SpiderHost x) where
2105+ {-# INLINABLE (>>=) #-}
2106+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2107+ {-# INLINABLE (>>) #-}
2108+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2109+ {-# INLINABLE return #-}
2110+ return x = SpiderHost $ return x
2111+ {-# INLINABLE fail #-}
2112+ fail s = SpiderHost $ fail s
2113+
2114+-- | Run an action affecting the global Spider timeline; this will be guarded by
2115+-- a mutex for that timeline
2116+runSpiderHost :: SpiderHost Global a -> IO a
2117+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2118+
2119+#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2120+-- | Run an action affecting a given Spider timeline; this will be guarded by a
2121+-- mutex for that timeline
2122+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2123+runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2124+#endif
2125+
2126+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2127+
2128+instance Monad (SpiderHostFrame x) where
2129+ {-# INLINABLE (>>=) #-}
2130+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2131+ {-# INLINABLE (>>) #-}
2132+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2133+ {-# INLINABLE return #-}
2134+ return x = SpiderHostFrame $ return x
2135+ {-# INLINABLE fail #-}
2136+ fail s = SpiderHostFrame $ fail s
2137+
2138+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2139+newEventWithTriggerIO f = do
2140+ es <- newFanEventWithTriggerIO $ \Refl -> f
2141+ return $ select es Refl
2142+
2143+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2144+newFanEventWithTriggerIO f = do
2145+ occRef <- newIORef DMap.empty
2146+ subscribedRef <- newIORef DMap.empty
2147+ let !r = Root
2148+ { rootOccurrence = occRef
2149+ , rootSubscribed = subscribedRef
2150+ , rootInit = f
2151+ }
2152+ return $ EventSelector $ \k -> eventRoot k r
2153+
2154+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2155+
2156+instance MonadRef (SpiderHost x) where
2157+ type Ref (SpiderHost x) = Ref IO
2158+ newRef = SpiderHost . newRef
2159+ readRef = SpiderHost . readRef
2160+ writeRef r = SpiderHost . writeRef r
2161+
2162+instance MonadAtomicRef (SpiderHost x) where
2163+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2164+
2165+instance MonadRef (SpiderHostFrame x) where
2166+ type Ref (SpiderHostFrame x) = Ref IO
2167+ newRef = SpiderHostFrame . newRef
2168+ readRef = SpiderHostFrame . readRef
2169+ writeRef r = SpiderHostFrame . writeRef r
2170+
2171+instance MonadAtomicRef (SpiderHostFrame x) where
2172+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2173+
2174+instance PrimMonad (SpiderHostFrame x) where
2175+ type PrimState (SpiderHostFrame x) = PrimState IO
2176+ primitive = SpiderHostFrame . EventM . primitive