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