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