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