@@ -1,2083 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE ExistentialQuantification #-}
6−{-# LANGUAGE FlexibleContexts #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
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 #-}
24−#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
25−{-# OPTIONS_GHC -fno-warn-orphans #-}
27−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
28−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
29−module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
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
42−import Data.Dependent.Map (DMap, DSum (..))
43−import qualified Data.Dependent.Map as DMap
44−import Data.Foldable hiding (concat, elem, sequence_)
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
53−import Data.List hiding (foldl')
55−import Data.Monoid ((<>))
58−import Data.Traversable
61−import GHC.IORef (IORef (..))
63−import Reflex.FunctorMaybe
64−import System.IO.Unsafe
65−import System.Mem.Weak
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)
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
89−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
90−import Prelude hiding (any, concat, mapM, mapM_, sequence)
92−#ifdef DEBUG_TRACE_EVENTS
93−import System.IO (stderr)
94−import qualified Data.ByteString.Char8 as BS8
97−#ifdef DEBUG_TRACE_EVENTS
99−withStackOneLine :: (BS8.ByteString -> a) -> a
100−withStackOneLine expr = unsafePerformIO $ do
101− stack <- currentCallStack
102− return (expr (BS8.pack (unwords (reverse stack))))
106−debugPropagate :: Bool
108−debugInvalidateHeight :: Bool
110−debugInvalidate :: Bool
114−#define DEBUG_NODEIDS
116−debugPropagate = True
118−debugInvalidateHeight = False
120−debugInvalidate = True
122−class HasNodeId a where
123− getNodeId :: a -> Int
125−instance HasNodeId (Hold x p a) where
126− getNodeId = holdNodeId
128−instance HasNodeId (PushSubscribed x a b) where
129− getNodeId = pushSubscribedNodeId
131−instance HasNodeId (SwitchSubscribed x a) where
132− getNodeId = switchSubscribedNodeId
134−instance HasNodeId (FanSubscribed x a) where
135− getNodeId = fanSubscribedNodeId
137−instance HasNodeId (CoincidenceSubscribed x a) where
138− getNodeId = coincidenceSubscribedNodeId
140−instance HasNodeId (RootSubscribed x a) where
141− getNodeId = rootSubscribedNodeId
143−instance HasNodeId (Pull x a) where
144− getNodeId = pullNodeId
146−{-# INLINE showNodeId #-}
147−showNodeId :: HasNodeId a => a -> String
148−showNodeId = ("#"<>) . show . getNodeId
150−showSubscriberType :: Subscriber x a -> String
151−showSubscriberType = \case
152− SubscriberPush _ _ -> "SubscriberPush"
153− SubscriberMerge _ _ -> "SubscriberMerge"
154− SubscriberFan _ -> "SubscriberFan"
155− SubscriberMergeChange _ -> "SubscriberMergeChange"
156− SubscriberHold _ -> "SubscriberHold"
157− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
158− SubscriberSwitch _ -> "SubscriberSwitch"
159− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
160− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
161− SubscriberHandle -> "SubscriberHandle"
163−showEventType :: Event x a -> String
164−showEventType = \case
165− EventRoot _ _ -> "EventRoot"
166− EventNever -> "EventNever"
167− EventPush _ -> "EventPush"
168− EventMerge _ -> "EventMerge"
169− EventFan _ _ -> "EventFan"
170− EventSwitch _ -> "EventSwitch"
171− EventCoincidence _ -> "EventCoincidence"
172− EventHold _ -> "EventHold"
173− EventDyn _ -> "EventDyn"
174− EventHoldIdentity _ -> "EventHoldIdentity"
175− EventDynIdentity _ -> "EventDynIdentity"
179−debugPropagate = False
181−debugInvalidateHeight = False
183−debugInvalidate = False
185−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
186−{-# INLINE showNodeId #-}
187−showNodeId :: a -> String
193−{-# NOINLINE nextNodeIdRef #-}
194−nextNodeIdRef :: IORef Int
195−nextNodeIdRef = unsafePerformIO $ newIORef 1
198−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
200−{-# NOINLINE unsafeNodeId #-}
201−unsafeNodeId :: a -> Int
202−unsafeNodeId a = unsafePerformIO $ do
207−--------------------------------------------------------------------------------
209−--------------------------------------------------------------------------------
211−--NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back
212−-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.
213−data EventSubscription x = EventSubscription
214− { _eventSubscription_unsubscribe :: !(IO ())
215− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
218−unsubscribe :: EventSubscription x -> IO ()
219−unsubscribe (EventSubscription u _) = u
221−--------------------------------------------------------------------------------
223−--------------------------------------------------------------------------------
225−newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
227−{-# INLINE subscribeAndRead #-}
228−subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
229−subscribeAndRead = unEvent
232−"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e
233−"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)
234−"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e
237−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
238−-- caching; if the computation function is very cheap, this is (much) more
239−-- efficient than 'push'
240−{-# NOINLINE pushCheap #-}
241−pushCheap :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
242−pushCheap f e = Event $ \sub -> do
243− (subscription, occ) <- subscribeAndRead e $ sub
244− { subscriberPropagate = \a -> do
245− mb <- runComputeM $ f a
246− mapM_ (subscriberPropagate sub) mb
248− occ' <- join <$> mapM (runComputeM . f) occ
249− return (subscription, occ')
251−data CacheSubscribed x a
252− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))
253− , _cacheSubscribed_weakSelf :: {-# UNPACK #-} !(IORef (Weak (CacheSubscribed x a)))
254− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
255− , _cacheSubscribed_cached :: {-# UNPACK #-} !(IORef (Maybe (CacheSubscribed x a)))
256− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
259−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
262−--TODO: Try a caching strategy where we subscribe directly to the parent when
263−--there's only one subscriber, and then build our own WeakBag only when a second
265−{-# NOINLINE cacheEvent #-}
266−cacheEvent :: HasSpiderTimeline x => Event x a -> Event x a
268−#ifdef DEBUG_TRACE_EVENTS
269− withStackOneLine $ \callSite -> Event $
273− let !mSubscribedRef = unsafeNewIORef e Nothing
274− in \sub -> {-# SCC "cacheEvent" #-} do
275−#ifdef DEBUG_TRACE_EVENTS
276− unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
278− mSubscribed <- liftIO $ readIORef mSubscribedRef
280− Just subscribed -> liftIO $ do
281− ticket <- WeakBag.insert sub (_cacheSubscribed_subscribers subscribed) (_cacheSubscribed_weakSelf subscribed) cleanupCacheSubscribed
282− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
283− let es = EventSubscribed
284− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
285− , eventSubscribedRetained = toAny subscribed
287− return (EventSubscription (WeakBag.remove ticket >> touch ticket) es, occ)
289− weakSelf <- liftIO $ newIORef $ error "cacheEvent: weakSelf not yet intialized"
290− (subscribers, ticket) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCacheSubscribed
291− occRef <- liftIO $ newIORef undefined
292− (parentSub, occ) <- subscribeAndRead e $ Subscriber
293− { subscriberPropagate = \a -> do
294− liftIO $ writeIORef occRef $ Just a
295− scheduleClear occRef
296− propagate a subscribers
297− , subscriberInvalidateHeight = \old -> do
298− WeakBag.traverse subscribers $ invalidateSubscriberHeight old
299− , subscriberRecalculateHeight = \new -> do
300− WeakBag.traverse subscribers $ recalculateSubscriberHeight new
302− liftIO $ writeIORef occRef occ
303− when (isJust occ) $ scheduleClear occRef
304− let !subscribed = CacheSubscribed
305− { _cacheSubscribed_subscribers = subscribers
306− , _cacheSubscribed_weakSelf = weakSelf
307− , _cacheSubscribed_parent = parentSub
308− , _cacheSubscribed_cached = mSubscribedRef
309− , _cacheSubscribed_occurrence = occRef
311− liftIO $ writeIORef mSubscribedRef $ Just subscribed
312− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
313− return (EventSubscription (WeakBag.remove ticket >> touch ticket) (EventSubscribed (eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub) (toAny subscribed)), occ)
315−cleanupCacheSubscribed :: CacheSubscribed x a -> IO ()
316−cleanupCacheSubscribed self = do
317− unsubscribe $ _cacheSubscribed_parent self
318− writeIORef (_cacheSubscribed_cached self) Nothing
320−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
321−subscribe e s = fst <$> subscribeAndRead e s
324−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
325−wrap tag getSpecificSubscribed sub = do
326− (sln, subd, occ) <- getSpecificSubscribed sub
328− return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)
330−eventRoot :: GCompare k => k a -> Root x k -> Event x a
331−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
333−eventNever :: Event x a
334−eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
336−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
337−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
339−eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
340−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
342−eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
343−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
345−eventHold :: HasSpiderTimeline x => Hold x p -> Event x p
346−eventHold !h = Event $ subscribeHoldEvent h
348−eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p
349−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
351−{-# INLINE subscribeCoincidenceInner #-}
352−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x)
353−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
354− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
355− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
356− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
357− let height = max innerHeight outerHeight
358− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
359− return (innerOcc, height, innerSubd)
361−--------------------------------------------------------------------------------
363−--------------------------------------------------------------------------------
365−data Subscriber x a = Subscriber
366− { subscriberPropagate :: !(a -> EventM x ())
367− , subscriberInvalidateHeight :: !(Height -> IO ())
368− , subscriberRecalculateHeight :: !(Height -> IO ())
371−--TODO: Move this comment to WeakBag
372−-- These function are constructor functions that are marked NOINLINE so they are
373−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
374−-- so any weak references that are attached to the constructors will have their
375−-- finalizer run. Using the opaque constructor, does not see the
376−-- constructor application, so it behaves like an IORef and cannot be fused away.
378−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
379−-- the weak pointer to it in some cases.
381−newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
382−newSubscriberHold h = return $ Subscriber
383− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
384− , subscriberInvalidateHeight = \_ -> return ()
385− , subscriberRecalculateHeight = \_ -> return ()
388−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
389−newSubscriberFan subscribed = return $ Subscriber
390− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
391− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
392− tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
393− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
394− scheduleClear $ fanSubscribedOccurrence subscribed
395− let f _ (Pair (Identity v) subsubs) = do
396− propagate v $ _fanSubscribedChildren_list subsubs
397− return $ Constant ()
398− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
400− , subscriberInvalidateHeight = \old -> do
401− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
402− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
403− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
404− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
405− , subscriberRecalculateHeight = \new -> do
406− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
407− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
408− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
409− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
412−newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
413−newSubscriberSwitch subscribed = return $ Subscriber
414− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
415− tracePropagate (Proxy :: Proxy x) $ "SubscriberSwitch" <> showNodeId subscribed
416− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
417− scheduleClear $ switchSubscribedOccurrence subscribed
418− propagate a $ switchSubscribedSubscribers subscribed
419− , subscriberInvalidateHeight = \_ -> do
420− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
421− oldHeight <- readIORef $ switchSubscribedHeight subscribed
422− when (oldHeight /= invalidHeight) $ do
423− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
424− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
425− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
426− , subscriberRecalculateHeight = \new -> do
427− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
428− updateSwitchHeight new subscribed
429− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
432−newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
433−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
434− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
435− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
436− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
437− tracePropagate (Proxy :: Proxy x) $ " outerHeight = " <> show outerHeight
438− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
439− tracePropagate (Proxy :: Proxy x) $ " isJust occ = " <> show (isJust occ)
440− tracePropagate (Proxy :: Proxy x) $ " innerHeight = " <> show innerHeight
441− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
442− scheduleClear $ coincidenceSubscribedInnerParent subscribed
445− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
446− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
447− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
448− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
449− Just o -> do -- Since it's already firing, no need to adjust height
450− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
451− scheduleClear $ coincidenceSubscribedOccurrence subscribed
452− propagate o $ coincidenceSubscribedSubscribers subscribed
453− , subscriberInvalidateHeight = \_ -> do
454− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
455− invalidateCoincidenceHeight subscribed
456− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
457− , subscriberRecalculateHeight = \_ -> do
458− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
459− recalculateCoincidenceHeight subscribed
460− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
463−newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
464−newSubscriberCoincidenceInner subscribed = return $ Subscriber
465− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
466− tracePropagate (Proxy :: Proxy x) $ "SubscriberCoincidenceInner" <> showNodeId subscribed
467− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
469− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
471− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
472− scheduleClear $ coincidenceSubscribedOccurrence subscribed
473− propagate a $ coincidenceSubscribedSubscribers subscribed
474− , subscriberInvalidateHeight = \_ -> do
475− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
476− invalidateCoincidenceHeight subscribed
477− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
478− , subscriberRecalculateHeight = \_ -> do
479− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
480− recalculateCoincidenceHeight subscribed
481− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
484−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
485−invalidateSubscriberHeight = flip subscriberInvalidateHeight
487−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
488−recalculateSubscriberHeight = flip subscriberRecalculateHeight
490−-- | Propagate everything at the current height
491−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
492−propagate a subscribers = withIncreasedDepth $ do
493− -- 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
494− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
495− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
497−--------------------------------------------------------------------------------
499−--------------------------------------------------------------------------------
504−data EventSubscribed x = EventSubscribed
505− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
506− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
508− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
509− , eventSubscribedHasOwnHeightRef :: !Bool
510− , eventSubscribedWhoCreated :: !(IO [String])
514−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
515−eventSubscribedRoot !r = EventSubscribed
516− { eventSubscribedHeightRef = zeroRef
517− , eventSubscribedRetained = toAny r
519− , eventSubscribedGetParents = return []
520− , eventSubscribedHasOwnHeightRef = False
521− , eventSubscribedWhoCreated = return ["root"]
525−eventSubscribedNever :: EventSubscribed x
526−eventSubscribedNever = EventSubscribed
527− { eventSubscribedHeightRef = zeroRef
528− , eventSubscribedRetained = toAny ()
530− , eventSubscribedGetParents = return []
531− , eventSubscribedHasOwnHeightRef = False
532− , eventSubscribedWhoCreated = return ["never"]
536−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
537−eventSubscribedFan !subscribed = EventSubscribed
538− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
539− , eventSubscribedRetained = toAny subscribed
541− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
542− , eventSubscribedHasOwnHeightRef = False
543− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
547−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
548−eventSubscribedSwitch !subscribed = EventSubscribed
549− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
550− , eventSubscribedRetained = toAny subscribed
552− , eventSubscribedGetParents = do
553− s <- readIORef $ switchSubscribedCurrentParent subscribed
554− return [Some.This $ _eventSubscription_subscribed s]
555− , eventSubscribedHasOwnHeightRef = True
556− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
560−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
561−eventSubscribedCoincidence !subscribed = EventSubscribed
562− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
563− , eventSubscribedRetained = toAny subscribed
565− , eventSubscribedGetParents = do
566− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
567− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
568− innerParents = maybeToList $ fmap Some.This innerSubscription
569− return $ outerParent : innerParents
570− , eventSubscribedHasOwnHeightRef = True
571− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
575−getEventSubscribedHeight :: EventSubscribed x -> IO Height
576−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
579−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
580−whoCreatedEventSubscribed = eventSubscribedWhoCreated
582−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
583−walkInvalidHeightParents s0 = do
584− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
585− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
586− when (h == invalidHeight) $ do
587− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
588− modify (Some.This s :)
589− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
590− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
594−{-# INLINE subscribeHoldEvent #-}
595−subscribeHoldEvent :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (EventSubscription x, Maybe p)
596−subscribeHoldEvent = subscribeAndRead . holdEvent
598−--------------------------------------------------------------------------------
600−--------------------------------------------------------------------------------
602−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
604−behaviorHold :: Hold x p -> Behavior x (PatchTarget p)
605−behaviorHold !h = Behavior $ readHoldTracked h
607−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
608−behaviorHoldIdentity = behaviorHold
610−behaviorConst :: a -> Behavior x a
611−behaviorConst !a = Behavior $ return a
613−behaviorPull :: Pull x a -> Behavior x a
614−behaviorPull !p = Behavior $ do
615− val <- liftIO $ readIORef $ pullValue p
617− Just subscribed -> do
618− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
619− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
620− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
621− return $ pullSubscribedValue subscribed
623− i <- liftIO $ newInvalidatorPull p
624− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
625− parentsRef <- liftIO $ newIORef []
626− holdInits <- askBehaviorHoldInits
627− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
628− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
629− parents <- liftIO $ readIORef parentsRef
630− let subscribed = PullSubscribed
631− { pullSubscribedValue = a
632− , pullSubscribedInvalidators = invsRef
633− , pullSubscribedOwnInvalidator = i
634− , pullSubscribedParents = parents
636− liftIO $ writeIORef (pullValue p) $ Just subscribed
637− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
640−behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
641−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
643−{-# INLINE readHoldTracked #-}
644−readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
645−readHoldTracked h = do
646− result <- liftIO $ readIORef $ holdValue h
647− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
648− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
651−{-# INLINABLE readBehaviorUntracked #-}
652−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
653−readBehaviorUntracked b = do
654− holdInits <- getDeferralQueue
655− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
657−--------------------------------------------------------------------------------
659−--------------------------------------------------------------------------------
661−data Dynamic x p = Dynamic
662− { dynamicCurrent :: !(Behavior x (PatchTarget p))
663− , dynamicUpdated :: !(Event x p)
666−dynamicHold :: HasSpiderTimeline x => Hold x p -> Dynamic x p
667−dynamicHold !h = Dynamic
668− { dynamicCurrent = behaviorHold h
669− , dynamicUpdated = eventHold h
672−dynamicHoldIdentity :: HasSpiderTimeline x => Hold x (Identity a) -> Dynamic x (Identity a)
673−dynamicHoldIdentity = dynamicHold
675−dynamicConst :: PatchTarget p -> Dynamic x p
676−dynamicConst !a = Dynamic
677− { dynamicCurrent = behaviorConst a
678− , dynamicUpdated = eventNever
681−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
682−dynamicDyn !d = Dynamic
683− { dynamicCurrent = behaviorDyn d
684− , dynamicUpdated = eventDyn d
687−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
688−dynamicDynIdentity = dynamicDyn
690−--------------------------------------------------------------------------------
692−--------------------------------------------------------------------------------
694−--TODO: Figure out why certain things are not 'representational', then make them
695−--representational so we can use coerce
697−--type role Hold representational
699− = Hold { holdValue :: !(IORef (PatchTarget p))
700− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
701− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
702− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
708−-- | A statically allocated 'SpiderTimeline'; this is the only instance of
709−-- 'SpiderTimeline' that can used when using
710−-- -fspecialize-to-spidertimeline-global.
713−{-# NOINLINE globalSpiderTimelineEnv #-}
714−globalSpiderTimelineEnv :: SpiderTimelineEnv Global
715−globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
717−-- | Stores all global data relevant to a particular Spider timeline; only one
718−-- value should exist for each type @x@
719−data SpiderTimelineEnv x = SpiderTimelineEnv
720− { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
721− , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
723− , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
726−type role SpiderTimelineEnv nominal
728−instance GEq SpiderTimelineEnv where
729− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
730− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
734− = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
735− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
736− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
737− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
738− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
739− , eventEnvRootClears :: !(IORef [SomeRootClear])
740− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
741− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
742− , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
745−{-# INLINE runEventM #-}
746−runEventM :: EventM x a -> IO a
749−asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
750−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
752−class MonadIO m => Defer a m where
753− getDeferralQueue :: m (IORef [a])
756−defer :: Defer a m => a -> m ()
758− q <- getDeferralQueue
759− liftIO $ modifyIORef' q (a:)
761−instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where
762− {-# INLINE getDeferralQueue #-}
763− getDeferralQueue = asksEventEnv eventEnvAssignments
765−instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where
766− {-# INLINE getDeferralQueue #-}
767− getDeferralQueue = asksEventEnv eventEnvHoldInits
769−instance Defer (SomeHoldInit x) (BehaviorM x) where
770− {-# INLINE getDeferralQueue #-}
771− getDeferralQueue = BehaviorM $ asks snd
773−instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where
774− {-# INLINE getDeferralQueue #-}
775− getDeferralQueue = asksEventEnv eventEnvMergeUpdates
777−instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where
778− {-# INLINE getDeferralQueue #-}
779− getDeferralQueue = asksEventEnv eventEnvMergeInits
781−class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where
782− getCurrentHeight :: m Height
783− scheduleMerge :: Height -> EventM x () -> m ()
785−instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where
786− {-# INLINE getCurrentHeight #-}
787− getCurrentHeight = do
788− heightRef <- asksEventEnv eventEnvCurrentHeight
789− liftIO $ readIORef heightRef
790− {-# INLINE scheduleMerge #-}
791− scheduleMerge height subscribed = do
792− delayedRef <- asksEventEnv eventEnvDelayedMerges
793− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]
795−#ifdef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
796−class x ~ Global => HasSpiderTimeline x where
798−class HasSpiderTimeline x where
800− -- | Retrieve the current SpiderTimelineEnv
801− spiderTimeline :: SpiderTimelineEnv x
803−instance HasSpiderTimeline Global where
804− spiderTimeline = globalSpiderTimelineEnv
806−putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()
807−putCurrentHeight h = do
808− heightRef <- asksEventEnv eventEnvCurrentHeight
809− liftIO $ writeIORef heightRef $! h
811−instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
812− {-# INLINE getDeferralQueue #-}
813− getDeferralQueue = asksEventEnv eventEnvClears
815−{-# INLINE scheduleClear #-}
816−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
817−scheduleClear r = defer $ SomeClear r
819−instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
820− {-# INLINE getDeferralQueue #-}
821− getDeferralQueue = asksEventEnv eventEnvRootClears
823−{-# INLINE scheduleRootClear #-}
824−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
825−scheduleRootClear r = defer $ SomeRootClear r
827−instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
828− {-# INLINE getDeferralQueue #-}
829− getDeferralQueue = asksEventEnv eventEnvResetCoincidences
831−-- Note: hold cannot examine its event until after the phase is over
832−{-# INLINE [1] hold #-}
833−hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)
835− valRef <- liftIO $ newIORef v0
836− invsRef <- liftIO $ newIORef []
837− parentRef <- liftIO $ newIORef Nothing
839− nodeId <- liftIO newNodeId
842− { holdValue = valRef
843− , holdInvalidators = invsRef
845− , holdParent = parentRef
847− , holdNodeId = nodeId
850− defer $ SomeHoldInit h
853−{-# INLINE getHoldEventSubscription #-}
854−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)
855−getHoldEventSubscription h = do
856− ep <- liftIO $ readIORef $ holdParent h
858− Just subd -> return subd
861− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
862− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
863− liftIO $ writeIORef subscriptionRef $! subscription
865− Nothing -> return ()
867− old <- liftIO $ readIORef $ holdValue h
869− Nothing -> return ()
871− -- Need to evaluate these so that we don't retain the Hold itself
872− v <- liftIO $ evaluate $ holdValue h
873− i <- liftIO $ evaluate $ holdInvalidators h
874− defer $ SomeAssignment v i new
875− liftIO $ writeIORef (holdParent h) $ Just subscription
878−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
880−--type role BehaviorM representational
881−-- BehaviorM can sample behaviors
882−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
884−instance Monad (BehaviorM x) where
885− {-# INLINE (>>=) #-}
886− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
888− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
889− {-# INLINE return #-}
890− return x = BehaviorM $ return x
892− fail s = BehaviorM $ fail s
894−data BehaviorSubscribed x a
895− = forall p. BehaviorSubscribedHold (Hold x p)
896− | BehaviorSubscribedPull (PullSubscribed x a)
898−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
900−--type role PullSubscribed representational
901−data PullSubscribed x a
902− = PullSubscribed { pullSubscribedValue :: !a
903− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
904− , pullSubscribedOwnInvalidator :: !(Invalidator x)
905− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
908−--type role Pull representational
910− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
911− , pullCompute :: !(BehaviorM x a)
918− = forall a. InvalidatorPull (Pull x a)
919− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
921−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
922− { rootSubscribedKey :: !(k a)
923− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
924− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
925− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
926− , rootSubscribedUninit :: IO ()
927− , 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?
929− , rootSubscribedNodeId :: Int
933−data Root x (k :: * -> *)
934− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
935− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
936− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
939−data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)
941−data SomeMergeUpdate x = SomeMergeUpdate
942− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
943− , _someMergeUpdate_invalidateHeight :: !(IO ())
944− , _someMergeUpdate_recalculateHeight :: !(IO ())
947−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
949−-- EventM can do everything BehaviorM can, plus create holds
950−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
952−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
954−instance Defer (SomeHoldInit x) (ComputeM x) where
955− getDeferralQueue = ComputeM ask
957−{-# INLINABLE runComputeM #-}
958−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
959−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
961−newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }
963−data HeightBag = HeightBag
964− { _heightBag_size :: {-# UNPACK #-} !Int
965− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
967− deriving (Show, Read, Eq, Ord)
969−heightBagEmpty :: HeightBag
970−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
972−heightBagSize :: HeightBag -> Int
973−heightBagSize = _heightBag_size
975−heightBagFromList :: [Height] -> HeightBag
976−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
978−heightBagAdd :: Height -> HeightBag -> HeightBag
979−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
981−heightBagRemove :: Height -> HeightBag -> HeightBag
982−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
983− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
984− Just old -> HeightBag (pred s) $ case old of
985− 0 -> IntMap.delete h c
986− _ -> IntMap.insert h (pred old) c
988−heightBagMax :: HeightBag -> Height
989−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
990− Just ((h, _), _) -> Height h
991− Nothing -> zeroHeight
993−heightBagVerify :: HeightBag -> HeightBag
995−heightBagVerify b@(HeightBag s c) = if
996− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
997− -> error $ "heightBagVerify: size doesn't match: " <> show b
998− | unHeight invalidHeight `IntMap.member` c
999− -> error $ "heightBagVerify: contains invalid height: " <> show b
1002−heightBagVerify = id
1005−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1006− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1007− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1008− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1011−data FanSubscribed (x :: *) k
1012− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1013− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1014− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1015− , fanSubscribedParent :: !(EventSubscription x)
1016−#ifdef DEBUG_NODEIDS
1017− , fanSubscribedNodeId :: Int
1022− = Fan { fanParent :: !(Event x (DMap k Identity))
1023− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1026−data SwitchSubscribed x a
1027− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1028− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1029− , switchSubscribedHeight :: !(IORef Height)
1030− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1031− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1032− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1033− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1034− , switchSubscribedParent :: !(Behavior x (Event x a))
1035− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1036− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1037−#ifdef DEBUG_NODEIDS
1038− , switchSubscribedNodeId :: Int
1043− = Switch { switchParent :: !(Behavior x (Event x a))
1044− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1047−#ifdef USE_TEMPLATE_HASKELL
1048−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1050−data CoincidenceSubscribed x a
1051− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1052− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1053− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1054− , coincidenceSubscribedHeight :: !(IORef Height)
1055− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1056− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1057− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1058− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1059−#ifdef DEBUG_NODEIDS
1060− , coincidenceSubscribedNodeId :: Int
1064−data Coincidence x a
1065− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1066− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1069−{-# NOINLINE newInvalidatorSwitch #-}
1070−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1071−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1073−{-# NOINLINE newInvalidatorPull #-}
1074−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1075−newInvalidatorPull p = return $! InvalidatorPull p
1077−instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1078− fmapMaybe f = push $ return . f
1080−instance HasSpiderTimeline x => Align (Event x) where
1082− align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]
1084−newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (PatchTarget p), Event x p) (Hold x p)) }
1086−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1087−newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1089−--TODO: Avoid the duplication between this and R.zipDynWith
1090−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1091−zipDynWith f da db =
1092− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1093− ec = flip push eab $ \o -> do
1094− (a, b) <- case o of
1095− This (Identity a) -> do
1096− b <- readBehaviorUntracked $ dynamicCurrent db
1098− That (Identity b) -> do
1099− a <- readBehaviorUntracked $ dynamicCurrent da
1101− These (Identity a) (Identity b) -> return (a, b)
1102− return $ Just $ Identity $ f a b
1103− in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1105−unsafeDyn :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1106−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1107− where x = (readV0, v')
1109−-- ResultM can read behaviors and events
1110−type ResultM = EventM
1112−{-# NOINLINE unsafeNewIORef #-}
1113−unsafeNewIORef :: a -> b -> IORef b
1114−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1116−instance HasSpiderTimeline x => Functor (Event x) where
1117− fmap f = push $ return . Just . f
1119−instance Functor (Behavior x) where
1120− fmap f = pull . fmap f . readBehaviorTracked
1123−push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1124−push f e = cacheEvent (pushCheap f e)
1126−{-# INLINABLE pull #-}
1127−pull :: BehaviorM x a -> Behavior x a
1128−pull a = behaviorPull $ Pull
1130− , pullValue = unsafeNewIORef a Nothing
1131−#ifdef DEBUG_NODEIDS
1132− , pullNodeId = unsafeNodeId a
1136−{-# INLINABLE switch #-}
1137−switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1138−switch a = eventSwitch $ Switch
1140− , switchSubscribed = unsafeNewIORef a Nothing
1143−coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1144−coincidence a = eventCoincidence $ Coincidence
1145− { coincidenceParent = a
1146− , coincidenceSubscribed = unsafeNewIORef a Nothing
1149−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1150−run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1151−run roots after = do
1152− tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
1153− t <- SpiderHost ask
1154− result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock t) $ \_ -> flip runReaderT t $ unSpiderHost $ runFrame $ do
1155− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1156− occBefore <- liftIO $ do
1157− occBefore <- readIORef occRef
1158− writeIORef occRef $! DMap.insert k a occBefore
1160− if DMap.null occBefore
1161− then do scheduleRootClear occRef
1163− else return Nothing
1164− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1165− propagate a subscribersRef
1166− delayedRef <- asksEventEnv eventEnvDelayedMerges
1168− delayed <- liftIO $ readIORef delayedRef
1169− case IntMap.minViewWithKey delayed of
1170− Nothing -> return ()
1171− Just ((currentHeight, cur), future) -> do
1172− tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight
1173− putCurrentHeight $ Height currentHeight
1174− liftIO $ writeIORef delayedRef $! future
1178− putCurrentHeight maxBound
1180− tracePropagate (Proxy :: Proxy x) "Done running an event frame"
1183−scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
1184−scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
1185− height <- liftIO $ readIORef heightRef
1186− currentHeight <- getCurrentHeight
1187− case height `compare` currentHeight of
1188− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1189− GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1192−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1194−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1196−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1198−debugFinalize :: Bool
1199−debugFinalize = False
1201−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1202−mkWeakPtrWithDebug x debugNote = do
1206− then Just $ putStrLn $ "finalizing: " ++ debugNote
1209−type WeakList a = [Weak a]
1211−{-# INLINE withIncreasedDepth #-}
1213−withIncreasedDepth :: CanTrace x m => m a -> m a
1214−withIncreasedDepth a = do
1215− spiderTimeline <- askSpiderTimelineEnv
1216− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1218− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1221−withIncreasedDepth :: m a -> m a
1222−withIncreasedDepth = id
1225−type CanTrace x m = (HasSpiderTimeline x, MonadIO m)
1227−{-# INLINE tracePropagate #-}
1228−tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()
1229−tracePropagate p = traceWhen p debugPropagate
1231−{-# INLINE traceInvalidate #-}
1232−traceInvalidate :: String -> IO ()
1233−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1235−{-# INLINE traceWhen #-}
1236−traceWhen :: (CanTrace x m) => proxy x -> Bool -> String -> m ()
1237−traceWhen p b message = traceMWhen p b $ return message
1239−{-# INLINE traceMWhen #-}
1240−traceMWhen :: (CanTrace x m) => proxy x -> Bool -> m String -> m ()
1241−traceMWhen _ b getMessage = when b $ do
1242− message <- getMessage
1244− spiderTimeline <- askSpiderTimelineEnv
1245− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1249− liftIO $ putStrLn $ replicate d ' ' <> message
1251−whoCreatedIORef :: IORef a -> IO [String]
1252−whoCreatedIORef (IORef a) = whoCreated $! a
1255−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1258− (x :| xs) : t -> case groupByHead t of
1259− [] -> [(x, xs :| [])]
1261− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1262− | otherwise -> (x, xs :| []) : l
1264−listsToForest :: Eq a => [[a]] -> Forest a
1265−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1268−{-# INLINE propagateSubscriberHold #-}
1269−propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
1270−propagateSubscriberHold h a = do
1271− {-# SCC "trace" #-} traceMWhen (Proxy :: Proxy x) debugPropagate $ liftIO $ do
1272− invalidators <- liftIO $ readIORef $ holdInvalidators h
1273− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1274− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1275− case {-# SCC "apply" #-} apply a v of
1276− Nothing -> return ()
1278− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate (Proxy :: Proxy x) $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1279− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1280− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1281− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1283−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1285−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1286−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1288−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1290− (!m, _) <- BehaviorM ask
1292− Nothing -> return Nothing
1293− Just (!wi, _) -> return $ Just wi
1295−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1297− (!m, _) <- BehaviorM ask
1299− Nothing -> return Nothing
1300− Just (_, !p) -> return $ Just p
1302−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1303−askBehaviorHoldInits = do
1304− (_, !his) <- BehaviorM ask
1307−{-# INLINE getDynHold #-}
1308−getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)
1310− mh <- liftIO $ readIORef $ unDyn d
1312− Right h -> return h
1313− Left (readV0, v') -> do
1314− holdInits <- getDeferralQueue
1315− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1317− liftIO $ writeIORef (unDyn d) $ Right h
1320−-- Always refers to 0
1321−{-# NOINLINE zeroRef #-}
1322−zeroRef :: IORef Height
1323−zeroRef = unsafePerformIO $ newIORef zeroHeight
1325−type CanSubscribe x m =
1326− ( HasSpiderTimeline x
1327− , HasCurrentHeight x m
1328− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1329− , Defer SomeClear m -- Wiping out event firings
1330− , Defer (SomeAssignment x) m -- Updating state
1331− , Defer (SomeResetCoincidence x) m
1335−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1336−getRootSubscribed k r sub = do
1337− mSubscribed <- readIORef $ rootSubscribed r
1338− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1339− case DMap.lookup k mSubscribed of
1340− Just subscribed -> {-# SCC "hitRoot" #-} do
1341− sln <- subscribeRootSubscribed subscribed sub
1343− return (sln, subscribed, occ)
1344− Nothing -> {-# SCC "missRoot" #-} do
1345− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1346− let !cached = rootSubscribed r
1347− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1348− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1349− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1350− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1351− writeIORef uninitRef $! uninit
1352− let subscribed = RootSubscribed
1353− { rootSubscribedKey = k
1354− , rootSubscribedCachedSubscribed = cached
1355− , rootSubscribedOccurrence = getOcc
1356− , rootSubscribedSubscribers = subs
1357− , rootSubscribedUninit = uninit
1358− , rootSubscribedWeakSelf = weakSelf
1359−#ifdef DEBUG_NODEIDS
1360− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1363− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1364− 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
1366− return (sln, subscribed, occ)
1368−#ifdef USE_TEMPLATE_HASKELL
1369−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1371−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1372−cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do
1373− rootSubscribedUninit self
1374− modifyIORef' cached $ DMap.delete k
1376−{-# INLINE subscribeRootSubscribed #-}
1377−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1378−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1380−{-# INLINABLE getFanSubscribed #-}
1381−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)
1382−getFanSubscribed k f sub = do
1383− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1384− case mSubscribed of
1385− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1386− sln <- subscribeFanSubscribed k subscribed sub
1387− occ <- readIORef $ fanSubscribedOccurrence subscribed
1388− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1389− Nothing -> {-# SCC "missFan" #-} do
1390− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1391− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1392− s <- liftIO $ newSubscriberFan subscribedUnsafe
1393− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1394− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1395− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1396− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1397− occRef <- liftIO $ newIORef parentOcc
1398− when (isJust parentOcc) $ scheduleClear occRef
1399− let subscribed = FanSubscribed
1400− { fanSubscribedCachedSubscribed = fanSubscribed f
1401− , fanSubscribedOccurrence = occRef
1402− , fanSubscribedParent = subscription
1403− , fanSubscribedSubscribers = subscribersRef
1404−#ifdef DEBUG_NODEIDS
1405− , fanSubscribedNodeId = unsafeNodeId f
1408− let !self = (k, subscribed)
1409− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1410− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1411− liftIO $ writeIORef subscribedRef $! subscribed
1412− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1413− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1415−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1416−cleanupFanSubscribed (k, subscribed) = do
1417− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1418− let reducedSubscribers = DMap.delete k subscribers
1419− if DMap.null reducedSubscribers
1421− unsubscribe $ fanSubscribedParent subscribed
1422− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1423− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1424− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1426−{-# INLINE subscribeFanSubscribed #-}
1427−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1428−subscribeFanSubscribed k subscribed sub = do
1429− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1430− case DMap.lookup k subscribers of
1431− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1432− let !self = (k, subscribed)
1433− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1434− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1435− 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
1437− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1439−{-# INLINABLE getSwitchSubscribed #-}
1440−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)
1441−getSwitchSubscribed s sub = do
1442− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1443− case mSubscribed of
1444− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1445− sln <- subscribeSwitchSubscribed subscribed sub
1446− occ <- readIORef $ switchSubscribedOccurrence subscribed
1447− return (sln, subscribed, occ)
1448− Nothing -> {-# SCC "missSwitch" #-} do
1449− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1450− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1451− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1452− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1453− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1454− wiRef <- liftIO $ newIORef wi
1455− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1456− holdInits <- getDeferralQueue
1457− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1458− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1459− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1460− subscriptionRef <- liftIO $ newIORef subscription
1461− occRef <- liftIO $ newIORef parentOcc
1462− when (isJust parentOcc) $ scheduleClear occRef
1463− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1464− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1465− let !subscribed = SwitchSubscribed
1466− { switchSubscribedCachedSubscribed = switchSubscribed s
1467− , switchSubscribedOccurrence = occRef
1468− , switchSubscribedHeight = heightRef
1469− , switchSubscribedSubscribers = subs
1470− , switchSubscribedOwnInvalidator = i
1471− , switchSubscribedOwnWeakInvalidator = wiRef
1472− , switchSubscribedBehaviorParents = parentsRef
1473− , switchSubscribedParent = switchParent s
1474− , switchSubscribedCurrentParent = subscriptionRef
1475− , switchSubscribedWeakSelf = weakSelf
1476−#ifdef DEBUG_NODEIDS
1477− , switchSubscribedNodeId = unsafeNodeId s
1480− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1481− liftIO $ writeIORef subscribedRef $! subscribed
1482− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1483− return (slnForSub, subscribed, parentOcc)
1485−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1486−cleanupSwitchSubscribed subscribed = do
1487− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1488− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1489− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1491−{-# INLINE subscribeSwitchSubscribed #-}
1492−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1493−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1495−{-# INLINABLE getCoincidenceSubscribed #-}
1496−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)
1497−getCoincidenceSubscribed c sub = do
1498− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1499− case mSubscribed of
1500− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1501− sln <- subscribeCoincidenceSubscribed subscribed sub
1502− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1503− return (sln, subscribed, occ)
1504− Nothing -> {-# SCC "missCoincidence" #-} do
1505− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1506− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1507− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1508− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1509− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1510− (occ, height, mInnerSubd) <- case outerOcc of
1511− Nothing -> return (Nothing, outerHeight, Nothing)
1513− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1514− return (occ, height, Just innerSubd)
1515− occRef <- liftIO $ newIORef occ
1516− when (isJust occ) $ scheduleClear occRef
1517− heightRef <- liftIO $ newIORef height
1518− innerSubdRef <- liftIO $ newIORef mInnerSubd
1519− scheduleClear innerSubdRef
1520− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1521− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1522− let subscribed = CoincidenceSubscribed
1523− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1524− , coincidenceSubscribedOccurrence = occRef
1525− , coincidenceSubscribedHeight = heightRef
1526− , coincidenceSubscribedSubscribers = subs
1527− , coincidenceSubscribedOuter = subOuter
1528− , coincidenceSubscribedOuterParent = outerSubscription
1529− , coincidenceSubscribedInnerParent = innerSubdRef
1530− , coincidenceSubscribedWeakSelf = weakSelf
1531−#ifdef DEBUG_NODEIDS
1532− , coincidenceSubscribedNodeId = unsafeNodeId c
1535− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1536− liftIO $ writeIORef subscribedRef $! subscribed
1537− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1538− return (slnForSub, subscribed, occ)
1540−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1541−cleanupCoincidenceSubscribed subscribed = do
1542− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1543− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1545−{-# INLINE subscribeCoincidenceSubscribed #-}
1546−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1547−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1549−{-# INLINE merge #-}
1550−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1551−merge d = cacheEvent (mergeCheap d)
1553−{-# INLINE [1] mergeCheap #-}
1554−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1555−mergeCheap d = Event $ \sub -> do
1556− initialParents <- readBehaviorUntracked $ dynamicCurrent d
1557− accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
1558− heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
1559− heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"
1560− parentsRef <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"
1561− let scheduleSelf height = scheduleMerge' height heightRef $ do
1562− m <- liftIO $ readIORef accumRef
1563− liftIO $ writeIORef accumRef $! DMap.empty
1564− --TODO: Assert that m is not empty
1565− subscriberPropagate sub m
1566− invalidateMyHeight = do
1567− oldHeight <- readIORef heightRef
1568− 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
1569− writeIORef heightRef $! invalidHeight
1570− subscriberInvalidateHeight sub oldHeight
1571− revalidateMyHeight = do
1572− currentHeight <- readIORef heightRef
1573− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1574− heights <- readIORef heightBagRef
1575− parents <- readIORef parentsRef
1576− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1577− case heightBagSize heights `compare` DMap.size parents of
1580− let height = succHeight $ heightBagMax heights
1581− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1582− writeIORef heightRef $! height
1583− subscriberRecalculateHeight sub height
1584− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge"
1585− subscriber :: forall a. k a -> Subscriber x a
1586− subscriber k = Subscriber
1587− { subscriberPropagate = \a -> do
1588− oldM <- liftIO $ readIORef accumRef
1589− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1590− tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
1591− liftIO $ writeIORef accumRef $! newM
1592− when (DMap.null oldM) $ do -- Only schedule the firing once
1593− height <- liftIO $ readIORef heightRef
1594− --TODO: assertions about height
1595− currentHeight <- getCurrentHeight
1596− when (height <= currentHeight) $ do
1597− if height /= invalidHeight
1599− myStack <- liftIO $ whoCreatedIORef undefined --TODO
1600− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
1603− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1604− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1605− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
1609− error $ "Causality loop found" <> cycleInfo
1610− scheduleSelf height
1611− , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating
1612− modifyIORef' heightBagRef $ heightBagRemove old
1614− , subscriberRecalculateHeight = \new -> do
1615− modifyIORef' heightBagRef $ heightBagAdd new
1618− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1619− let s = subscriber k
1620− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1621− height <- liftIO $ getEventSubscribedHeight parentSubd
1622− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1623− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1624− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1625− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1626− myHeight = if invalidHeight `elem` heights
1628− else succHeight $ heightBagMax myHeightBag
1629− currentHeight <- getCurrentHeight
1630− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1631− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1633− unless (DMap.null accum) $ do
1634− scheduleSelf myHeight
1635− occRef <- liftIO $ newIORef occ
1636− when (isJust occ) $ scheduleClear occRef
1637− liftIO $ writeIORef accumRef $! accum
1638− liftIO $ writeIORef heightRef $! myHeight
1639− liftIO $ writeIORef heightBagRef $! myHeightBag
1640− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1641− liftIO $ writeIORef parentsRef $! DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1642− let updateMe (PatchDMap p) = do
1643− oldParents <- liftIO $ readIORef parentsRef
1644− let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
1645− (mOldSubd, newPs) <- case me of
1646− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1648− let s = subscriber k
1649− subscription@(EventSubscription _ subd) <- subscribe e s
1650− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1651− let newParent = MergeSubscribedParent subscription
1652− liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
1653− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1654− forM_ mOldSubd $ \oldSubd -> do
1655− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd
1656− liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
1657− return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
1658− (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
1659− liftIO $ writeIORef parentsRef $! newParents
1660− return subscriptionsToKill
1661− defer $ SomeMergeInit $ do
1663− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
1664− tracePropagate (Proxy :: Proxy x) $ "SubscriberMerge/Change"
1665− defer $ SomeMergeUpdate (updateMe a) invalidateMyHeight revalidateMyHeight
1666− , subscriberInvalidateHeight = \_ -> return ()
1667− , subscriberRecalculateHeight = \_ -> return ()
1669− (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) s
1670− forM_ change $ \c -> defer $ SomeMergeUpdate (updateMe c) invalidateMyHeight revalidateMyHeight
1671− -- We explicitly hold on to the unsubscribe function from subscribing to the update event.
1672− -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain
1673− -- its subscription.
1674− liftIO $ writeIORef changeSubdRef (s, changeSubscription)
1675− let unsubscribeAll = do
1676− parents <- readIORef parentsRef
1677− forM_ (DMap.toList parents) $ \(_ :=> MergeSubscribedParent s) -> unsubscribe s
1678− return ( EventSubscription unsubscribeAll $ EventSubscribed heightRef $ toAny (parentsRef, changeSubdRef)
1682−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1684−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
1688− , fanSubscribed = unsafeNewIORef e Nothing
1690− in EventSelector $ \k -> eventFan k f
1692−runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1693−runHoldInits holdInitRef mergeInitRef = do
1694− holdInits <- liftIO $ readIORef holdInitRef
1695− mergeInits <- liftIO $ readIORef mergeInitRef
1696− unless (null holdInits && null mergeInits) $ do
1697− liftIO $ writeIORef holdInitRef []
1698− liftIO $ writeIORef mergeInitRef []
1699− mapM_ initHold holdInits
1700− mapM_ unSomeMergeInit mergeInits
1701− runHoldInits holdInitRef mergeInitRef
1703−initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()
1704−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1706−newEventEnv :: IO (EventEnv x)
1708− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1709− holdInitRef <- newIORef []
1710− mergeUpdateRef <- newIORef []
1711− mergeInitRef <- newIORef []
1712− heightRef <- newIORef zeroHeight
1713− toClearRef <- newIORef []
1714− toClearRootRef <- newIORef []
1715− coincidenceInfosRef <- newIORef []
1716− delayedRef <- newIORef IntMap.empty
1717− return $ EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1719−clearEventEnv :: EventEnv x -> IO ()
1720−clearEventEnv (EventEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef) = do
1721− writeIORef toAssignRef []
1722− writeIORef holdInitRef []
1723− writeIORef mergeUpdateRef []
1724− writeIORef mergeInitRef []
1725− writeIORef heightRef zeroHeight
1726− writeIORef toClearRef []
1727− writeIORef toClearRootRef []
1728− writeIORef coincidenceInfosRef []
1729− writeIORef delayedRef IntMap.empty
1731−-- | Run an event action outside of a frame
1732−runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1733−runFrame a = SpiderHost $ ask >>= \_ -> lift $ do
1734− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
1737− 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
1739− result <- runEventM go
1740− toClear <- readIORef $ eventEnvClears env
1741− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1742− toClearRoot <- readIORef $ eventEnvRootClears env
1743− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1744− toAssign <- readIORef $ eventEnvAssignments env
1745− toReconnectRef <- newIORef []
1746− coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
1747− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1749− when debugInvalidate $ putStrLn $ "Invalidating Hold"
1750− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1751− mergeUpdates <- readIORef $ eventEnvMergeUpdates env
1752− writeIORef (eventEnvMergeUpdates env) []
1753− when debugPropagate $ putStrLn "Updating merges"
1754− mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1755− when debugPropagate $ putStrLn "Updating merges done"
1756− toReconnect <- readIORef toReconnectRef
1758− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1759− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1760− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1761− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1763− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1764− wi' <- mkWeakPtrWithDebug i "wi'"
1765− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1766− writeIORef (switchSubscribedBehaviorParents subscribed) []
1767− writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?
1768− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env
1769− 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
1770− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1771− sub <- newSubscriberSwitch subscribed
1772− 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
1774− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1775− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1776− EventRoot _ -> "EventRoot"
1777− EventNever -> "EventNever"
1778− _ -> "something else"
1780− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1781− return oldSubscription
1782− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1783− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1784− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1785− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1786− parentHeight <- getEventSubscribedHeight subd'
1787− myHeight <- readIORef $ switchSubscribedHeight subscribed
1788− when (parentHeight /= myHeight) $ do
1789− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1790− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1791− 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
1792− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1793− unsubscribe subscription
1794− mapM_ invalidateCoincidenceHeight mcs
1795− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1796− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1797− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1798− height <- calculateSwitchHeight subscribed
1799− updateSwitchHeight height subscribed
1802−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1804−{-# INLINE zeroHeight #-}
1805−zeroHeight :: Height
1806−zeroHeight = Height 0
1808−{-# INLINE invalidHeight #-}
1809−invalidHeight :: Height
1810−invalidHeight = Height (-1000)
1813−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1814−{-# INLINE invalidHeightBeingTraversed #-}
1815−invalidHeightBeingTraversed :: Height
1816−invalidHeightBeingTraversed = Height (-1001)
1819−{-# INLINE succHeight #-}
1820−succHeight :: Height -> Height
1821−succHeight h@(Height a) =
1822− if h == invalidHeight
1824− else Height $ succ a
1826−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1827−invalidateCoincidenceHeight subscribed = do
1828− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1829− when (oldHeight /= invalidHeight) $ do
1830− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1831− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1833−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1834−updateSwitchHeight new subscribed = do
1835− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1836− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1837− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1838− writeIORef (switchSubscribedHeight subscribed) $! new
1839− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1841−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1842−recalculateCoincidenceHeight subscribed = do
1843− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1844− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1845− height <- calculateCoincidenceHeight subscribed
1846− when (height /= invalidHeight) $ do
1847− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1848− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1850−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1851−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1853−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1854−calculateCoincidenceHeight subscribed = do
1855− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1856− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1857− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1859−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1861−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1862−invalidate toReconnectRef wis = do
1863− forM_ wis $ \wi -> do
1867− traceInvalidate "invalidate Dead"
1868− return () --TODO: Should we clean this up here?
1870− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1872− InvalidatorPull p -> do
1873− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1874− mVal <- readIORef $ pullValue p
1875− forM_ mVal $ \val -> do
1876− writeIORef (pullValue p) Nothing
1877− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1878− InvalidatorSwitch subscribed -> do
1879− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1880− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1881− 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
1883−--------------------------------------------------------------------------------
1884−-- Reflex integration
1885−--------------------------------------------------------------------------------
1887−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1888−-- When we're specializing, we include this from Reflex.Class instead, because
1889−-- it needs access to these types; when we're not, we want them here, so our
1890−-- instance isn't an orphan instance.
1891−#include "SpiderTimeline.include.hs"
1892−#include "SpiderTimelineHost.include.hs"
1895−unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)
1896−unsafeNewSpiderTimelineEnv = do
1900− depthRef <- newIORef 0
1902− return $ SpiderTimelineEnv
1903− { _spiderTimeline_lock = lock
1904− , _spiderTimeline_eventEnv = env
1906− , _spiderTimeline_depth = depthRef
1910−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1911−-- | Create a new SpiderTimelineEnv
1912−newSpiderTimeline :: IO (Some SpiderTimelineEnv)
1913−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
1915−data LocalSpiderTimeline x s
1917−instance Reifies s (SpiderTimelineEnv x) =>
1918− HasSpiderTimeline (LocalSpiderTimeline x s) where
1919− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
1923− -> SpiderTimelineEnv x
1924− -> SpiderTimelineEnv (LocalSpiderTimeline x s)
1925−localSpiderTimeline _ = unsafeCoerce
1927−-- | Pass a new timeline to the given function.
1928−withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
1929−withSpiderTimeline k = do
1930− env <- unsafeNewSpiderTimelineEnv
1931− reify env $ \s -> k $ localSpiderTimeline s env
1934−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1936−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1938−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
1939−instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
1940− {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
1941− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
1942− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
1943− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
1944− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
1945− type PullM (SpiderTimeline x) = SpiderPullM x
1946− type PushM (SpiderTimeline x) = SpiderPushM x
1947− {-# INLINABLE never #-}
1948− never = SpiderEvent eventNever
1949− {-# INLINABLE constant #-}
1950− constant = SpiderBehavior . behaviorConst
1951− {-# INLINE push #-}
1952− push f = SpiderEvent . push (coerce f) . unSpiderEvent
1953− {-# INLINE pushCheap #-}
1954− pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
1955− {-# INLINABLE pull #-}
1956− pull = SpiderBehavior . pull . coerce
1957− {-# INLINABLE merge #-}
1958− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
1959− {-# INLINABLE fan #-}
1960− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
1961− {-# INLINABLE switch #-}
1962− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
1963− {-# INLINABLE coincidence #-}
1964− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
1965− {-# INLINABLE current #-}
1966− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
1967− {-# INLINABLE updated #-}
1968− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
1969− {-# INLINABLE unsafeBuildDynamic #-}
1970− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
1971− {-# INLINABLE unsafeBuildIncremental #-}
1972− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
1973− {-# INLINABLE mergeIncremental #-}
1974− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
1975− {-# INLINABLE currentIncremental #-}
1976− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
1977− {-# INLINABLE updatedIncremental #-}
1978− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
1979− {-# INLINABLE incrementalToDynamic #-}
1980− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
1981− c <- readBehaviorUntracked $ dynamicCurrent i
1982− return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
1983− eventCoercion Coercion = Coercion
1984− behaviorCoercion Coercion = Coercion
1985− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
1988−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
1990−data SpiderEventHandle x a = SpiderEventHandle
1991− { spiderEventHandleSubscription :: EventSubscription x
1992− , spiderEventHandleValue :: IORef (Maybe a)
1995−instance MonadRef (EventM x) where
1996− type Ref (EventM x) = Ref IO
1997− {-# INLINABLE newRef #-}
1998− {-# INLINABLE readRef #-}
1999− {-# INLINABLE writeRef #-}
2000− newRef = liftIO . newRef
2001− readRef = liftIO . readRef
2002− writeRef r a = liftIO $ writeRef r a
2004−instance MonadAtomicRef (EventM x) where
2005− {-# INLINABLE atomicModifyRef #-}
2006− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2008−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2009−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimelineEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2011−instance Monad (SpiderHost x) where
2012− {-# INLINABLE (>>=) #-}
2013− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2014− {-# INLINABLE (>>) #-}
2015− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2016− {-# INLINABLE return #-}
2017− return x = SpiderHost $ return x
2018− {-# INLINABLE fail #-}
2019− fail s = SpiderHost $ fail s
2021−-- | Run an action affecting the global Spider timeline; this will be guarded by
2022−-- a mutex for that timeline
2023−runSpiderHost :: SpiderHost Global a -> IO a
2024−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimelineEnv
2026−#ifndef SPECIALIZE_TO_SPIDERTIMELINE_GLOBAL
2027−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2028−-- mutex for that timeline
2029−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
2030−runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2033−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2035−instance Monad (SpiderHostFrame x) where
2036− {-# INLINABLE (>>=) #-}
2037− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2038− {-# INLINABLE (>>) #-}
2039− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2040− {-# INLINABLE return #-}
2041− return x = SpiderHostFrame $ return x
2042− {-# INLINABLE fail #-}
2043− fail s = SpiderHostFrame $ fail s
2045−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2046−newEventWithTriggerIO f = do
2047− es <- newFanEventWithTriggerIO $ \Refl -> f
2048− return $ select es Refl
2050−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2051−newFanEventWithTriggerIO f = do
2052− occRef <- newIORef DMap.empty
2053− subscribedRef <- newIORef DMap.empty
2055− { rootOccurrence = occRef
2056− , rootSubscribed = subscribedRef
2059− return $ EventSelector $ \k -> eventRoot k r
2061−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2063−instance MonadRef (SpiderHost x) where
2064− type Ref (SpiderHost x) = Ref IO
2065− newRef = SpiderHost . newRef
2066− readRef = SpiderHost . readRef
2067− writeRef r = SpiderHost . writeRef r
2069−instance MonadAtomicRef (SpiderHost x) where
2070− atomicModifyRef r = SpiderHost . atomicModifyRef r
2072−instance MonadRef (SpiderHostFrame x) where
2073− type Ref (SpiderHostFrame x) = Ref IO
2074− newRef = SpiderHostFrame . newRef
2075− readRef = SpiderHostFrame . readRef
2076− writeRef r = SpiderHostFrame . writeRef r
2078−instance MonadAtomicRef (SpiderHostFrame x) where
2079− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2081−instance PrimMonad (SpiderHostFrame x) where
2082− type PrimState (SpiderHostFrame x) = PrimState IO
2083− primitive = SpiderHostFrame . EventM . primitive