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