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