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