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