@@ -9,7 +9,6 @@
99{-# LANGUAGE GADTs #-}
1010{-# LANGUAGE GeneralizedNewtypeDeriving #-}
1111{-# LANGUAGE LambdaCase #-}
12−{-# LANGUAGE MultiParamTypeClasses #-}
1312{-# LANGUAGE MultiWayIf #-}
1413{-# LANGUAGE RankNTypes #-}
1514{-# LANGUAGE RoleAnnotations #-}
@@ -17,9 +16,15 @@
1716{-# LANGUAGE TypeFamilies #-}
1817{-# LANGUAGE TypeOperators #-}
1918{-# LANGUAGE UndecidableInstances #-}
19+{-# LANGUAGE PolyKinds #-}
20+{-# LANGUAGE DeriveFunctor #-}
21+{-# LANGUAGE StandaloneDeriving #-}
22+{-# LANGUAGE InstanceSigs #-}
23+
2024#ifdef USE_REFLEX_OPTIMIZER
2125{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
2226#endif
27+{-# OPTIONS_GHC -Wunused-binds #-}
2328-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
2429-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
2530module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
@@ -33,7 +38,10 @@ import Control.Monad hiding (forM, forM_, mapM, mapM_)
3338import Control.Monad.Exception
3439import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
3540import Control.Monad.Primitive
36−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
41+--import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_)
42+import Control.Monad.Reader.Class
43+import Control.Monad.IO.Class
44+import Control.Monad.ReaderIO
3745import Control.Monad.Ref
3846import Data.Align
3947import Data.Coerce
@@ -49,6 +57,7 @@ import Data.GADT.Compare
4957import Data.IntMap.Strict (IntMap)
5058import qualified Data.IntMap.Strict as IntMap
5159import Data.IORef
60+import Data.Kind (Type)
5261import Data.Maybe hiding (mapMaybe)
5362import Data.Monoid ((<>))
5463import Data.Proxy
@@ -63,6 +72,15 @@ import System.IO.Unsafe
6372import System.Mem.Weak
6473import Unsafe.Coerce
6574
75+#ifdef MIN_VERSION_semialign
76+#if MIN_VERSION_these(0,8,0)
77+import Data.These.Combinators (justThese)
78+#endif
79+#if MIN_VERSION_semialign(1,1,0)
80+import Data.Zip (Zip (..))
81+#endif
82+#endif
83+
6684#ifdef DEBUG_CYCLES
6785import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
6886import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
@@ -74,9 +92,9 @@ import Data.Tree (Forest, Tree (..), drawForest)
7492import Data.FastWeakBag (FastWeakBag)
7593import qualified Data.FastWeakBag as FastWeakBag
7694import Data.Reflection
77−import Data.Some (Some)
78−import qualified Data.Some as Some
95+import Data.Some (Some(Some))
7996import Data.Type.Coercion
97+import Data.Profunctor.Unsafe ((#.), (.#))
8098import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
8199import qualified Data.WeakBag as WeakBag
82100import qualified Reflex.Class
@@ -85,6 +103,7 @@ import qualified Reflex.Host.Class
85103import Reflex.NotReady.Class
86104import Reflex.Patch
87105import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
106+import Reflex.PerformEvent.Base (PerformEventT)
88107
89108#ifdef DEBUG_TRACE_EVENTS
90109import qualified Data.ByteString.Char8 as BS8
@@ -193,12 +212,6 @@ nextNodeIdRef = unsafePerformIO $ newIORef 1
193212
194213newNodeId :: IO Int
195214newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
196−
197−{-# NOINLINE unsafeNodeId #-}
198−unsafeNodeId :: a -> Int
199−unsafeNodeId a = unsafePerformIO $ do
200− touch a
201− newNodeId
202215#endif
203216
204217--------------------------------------------------------------------------------
@@ -302,9 +315,10 @@ cacheEvent e =
302315#else
303316 Event $
304317#endif
305− let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
306− !mSubscribedRef = unsafeNewIORef e emptyFastWeak
307− in \sub -> {-# SCC "cacheEvent" #-} do
318+ unsafePerformIO $ do
319+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
320+ <- newIORef emptyFastWeak
321+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
308322#ifdef DEBUG_TRACE_EVENTS
309323 unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
310324#endif
@@ -319,9 +333,9 @@ cacheEvent e =
319333 scheduleClear occRef
320334 propagateFast a subscribers
321335 , subscriberInvalidateHeight = \old -> do
322− FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
336+ FastWeakBag.traverse_ subscribers $ invalidateSubscriberHeight old
323337 , subscriberRecalculateHeight = \new -> do
324− FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
338+ FastWeakBag.traverse_ subscribers $ recalculateSubscriberHeight new
325339 }
326340 when (isJust occ) $ do
327341 liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
@@ -370,7 +384,7 @@ eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed
370384eventNever :: Event x a
371385eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
372386
373−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
387+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
374388eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
375389
376390eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
@@ -422,14 +436,14 @@ newSubscriberHold h = return $ Subscriber
422436 , subscriberRecalculateHeight = \_ -> return ()
423437 }
424438
425−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
439+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
426440newSubscriberFan subscribed = return $ Subscriber
427441 { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
428442 subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
429443 tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
430444 liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
431445 scheduleClear $ fanSubscribedOccurrence subscribed
432− let f _ (Pair (Identity v) subsubs) = do
446+ let f _ (Pair v subsubs) = do
433447 propagate v $ _fanSubscribedChildren_list subsubs
434448 return $ Constant ()
435449 _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
@@ -437,12 +451,12 @@ newSubscriberFan subscribed = return $ Subscriber
437451 , subscriberInvalidateHeight = \old -> do
438452 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
439453 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
440− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
454+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
441455 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
442456 , subscriberRecalculateHeight = \new -> do
443457 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
444458 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
445− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
459+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
446460 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
447461 }
448462
@@ -458,7 +472,7 @@ newSubscriberSwitch subscribed = return $ Subscriber
458472 oldHeight <- readIORef $ switchSubscribedHeight subscribed
459473 when (oldHeight /= invalidHeight) $ do
460474 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
461− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
475+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
462476 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
463477 , subscriberRecalculateHeight = \new -> do
464478 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
@@ -481,8 +495,8 @@ newSubscriberCoincidenceOuter subscribed = return $ Subscriber
481495 Nothing -> do
482496 when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
483497 writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
484− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
485− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
498+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
499+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
486500 Just o -> do -- Since it's already firing, no need to adjust height
487501 liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
488502 scheduleClear $ coincidenceSubscribedOccurrence subscribed
@@ -529,14 +543,14 @@ propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
529543propagate a subscribers = withIncreasedDepth $ do
530544 -- 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
531545 --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
532− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
546+ WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
533547
534548-- | Propagate everything at the current height
535549propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
536550propagateFast a subscribers = withIncreasedDepth $ do
537551 -- 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
538552 --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
539− FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
553+ FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
540554
541555--------------------------------------------------------------------------------
542556-- EventSubscribed
@@ -545,6 +559,11 @@ propagateFast a subscribers = withIncreasedDepth $ do
545559toAny :: a -> Any
546560toAny = unsafeCoerce
547561
562+-- Why do we use Any here, instead of just giving eventSubscribedRetained an
563+-- existential type? Sadly, GHC does not currently know how to unbox types
564+-- with existentially quantified fields. So instead we just coerce values
565+-- to type Any on the way in. Since we never coerce them back, this is
566+-- perfectly safe.
548567data EventSubscribed x = EventSubscribed
549568 { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
550569 , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
@@ -577,12 +596,12 @@ eventSubscribedNever = EventSubscribed
577596#endif
578597 }
579598
580−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
599+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
581600eventSubscribedFan !subscribed = EventSubscribed
582601 { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
583602 , eventSubscribedRetained = toAny subscribed
584603#ifdef DEBUG_CYCLES
585− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
604+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
586605 , eventSubscribedHasOwnHeightRef = False
587606 , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
588607#endif
@@ -595,7 +614,7 @@ eventSubscribedSwitch !subscribed = EventSubscribed
595614#ifdef DEBUG_CYCLES
596615 , eventSubscribedGetParents = do
597616 s <- readIORef $ switchSubscribedCurrentParent subscribed
598− return [Some.This $ _eventSubscription_subscribed s]
617+ return [Some $ _eventSubscription_subscribed s]
599618 , eventSubscribedHasOwnHeightRef = True
600619 , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
601620#endif
@@ -608,8 +627,8 @@ eventSubscribedCoincidence !subscribed = EventSubscribed
608627#ifdef DEBUG_CYCLES
609628 , eventSubscribedGetParents = do
610629 innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
611− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
612− innerParents = maybeToList $ fmap Some.This innerSubscription
630+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
631+ innerParents = maybeToList $ fmap Some innerSubscription
613632 return $ outerParent : innerParents
614633 , eventSubscribedHasOwnHeightRef = True
615634 , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
@@ -625,13 +644,13 @@ whoCreatedEventSubscribed = eventSubscribedWhoCreated
625644
626645walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
627646walkInvalidHeightParents s0 = do
628− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
647+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
629648 h <- liftIO $ readIORef $ eventSubscribedHeightRef s
630649 when (h == invalidHeight) $ do
631650 when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
632− modify (Some.This s :)
651+ modify (Some s :)
633652 mapM_ loop =<< liftIO (eventSubscribedGetParents s)
634− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
653+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
635654 return subscribers
636655#endif
637656
@@ -659,7 +678,7 @@ behaviorPull !p = Behavior $ do
659678 val <- liftIO $ readIORef $ pullValue p
660679 case val of
661680 Just subscribed -> do
662− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedPull subscribed)) :))
681+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
663682 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
664683 liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
665684 return $ pullSubscribedValue subscribed
@@ -668,7 +687,7 @@ behaviorPull !p = Behavior $ do
668687 wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
669688 parentsRef <- liftIO $ newIORef []
670689 holdInits <- askBehaviorHoldInits
671− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
690+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
672691 invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
673692 parents <- liftIO $ readIORef parentsRef
674693 let subscribed = PullSubscribed
@@ -678,7 +697,7 @@ behaviorPull !p = Behavior $ do
678697 , pullSubscribedParents = parents
679698 }
680699 liftIO $ writeIORef (pullValue p) $ Just subscribed
681− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedPull subscribed)) :))
700+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
682701 return a
683702
684703behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
@@ -689,7 +708,7 @@ readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
689708readHoldTracked h = do
690709 result <- liftIO $ readIORef $ holdValue h
691710 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
692− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedHold h)) :))
711+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
693712 liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
694713 return result
695714
@@ -703,42 +722,46 @@ readBehaviorUntracked b = do
703722-- Dynamic
704723--------------------------------------------------------------------------------
705724
706−data Dynamic x p = Dynamic
707− { dynamicCurrent :: !(Behavior x (PatchTarget p))
725+type DynamicS x p = Dynamic x (PatchTarget p) p
726+
727+data Dynamic x target p = Dynamic
728+ { dynamicCurrent :: !(Behavior x target)
708729 , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
709730 }
710731
711−dynamicHold :: Hold x p -> Dynamic x p
732+deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
733+
734+
735+
736+
737+dynamicHold :: Hold x p -> DynamicS x p
712738dynamicHold !h = Dynamic
713739 { dynamicCurrent = behaviorHold h
714740 , dynamicUpdated = eventHold h
715741 }
716742
717−dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
743+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
718744dynamicHoldIdentity = dynamicHold
719745
720−dynamicConst :: PatchTarget p -> Dynamic x p
746+dynamicConst :: PatchTarget p -> DynamicS x p
721747dynamicConst !a = Dynamic
722748 { dynamicCurrent = behaviorConst a
723749 , dynamicUpdated = eventNever
724750 }
725751
726−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
752+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
727753dynamicDyn !d = Dynamic
728754 { dynamicCurrent = behaviorDyn d
729755 , dynamicUpdated = eventDyn d
730756 }
731757
732−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
758+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
733759dynamicDynIdentity = dynamicDyn
734760
735761--------------------------------------------------------------------------------
736762-- Combinators
737763--------------------------------------------------------------------------------
738764
739−--TODO: Figure out why certain things are not 'representational', then make them
740−--representational so we can use coerce
741−
742765--type role Hold representational
743766data Hold x p
744767 = Hold { holdValue :: !(IORef (PatchTarget p))
@@ -759,20 +782,25 @@ globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
759782
760783-- | Stores all global data relevant to a particular Spider timeline; only one
761784-- value should exist for each type @x@
762−data SpiderTimelineEnv x = SpiderTimelineEnv
785+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
786+-- We implement SpiderTimelineEnv with a newtype wrapper so
787+-- we can get the coercions we want safely.
788+type role SpiderTimelineEnv nominal
789+
790+data SpiderTimelineEnv' x = SpiderTimelineEnv
763791 { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
764792 , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
765793#ifdef DEBUG
766794 , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
767795#endif
768796 }
769−type role SpiderTimelineEnv nominal
797+type role SpiderTimelineEnv' phantom
770798
771799instance Eq (SpiderTimelineEnv x) where
772800 _ == _ = True -- Since only one exists of each type
773801
774802instance GEq SpiderTimelineEnv where
775− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
803+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
776804 then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
777805 else Nothing
778806
@@ -795,7 +823,7 @@ runEventM :: EventM x a -> IO a
795823runEventM = unEventM
796824
797825asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
798−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
826+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
799827
800828class MonadIO m => Defer a m where
801829 getDeferralQueue :: m (IORef [a])
@@ -862,7 +890,7 @@ instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
862890
863891{-# INLINE scheduleClear #-}
864892scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
865−scheduleClear r = defer $ Some.This $ Clear r
893+scheduleClear r = defer $ Some $ Clear r
866894
867895instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
868896 {-# INLINE getDeferralQueue #-}
@@ -870,7 +898,7 @@ instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
870898
871899{-# INLINE scheduleIntClear #-}
872900scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
873−scheduleIntClear r = defer $ Some.This $ IntClear r
901+scheduleIntClear r = defer $ Some $ IntClear r
874902
875903instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
876904 {-# INLINE getDeferralQueue #-}
@@ -878,7 +906,7 @@ instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
878906
879907{-# INLINE scheduleRootClear #-}
880908scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
881−scheduleRootClear r = defer $ Some.This $ RootClear r
909+scheduleRootClear r = defer $ Some $ RootClear r
882910
883911instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
884912 {-# INLINE getDeferralQueue #-}
@@ -933,9 +961,9 @@ getHoldEventSubscription h = do
933961
934962type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
935963
936−--type role BehaviorM representational
937964-- BehaviorM can sample behaviors
938−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
965+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
966+ deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
939967
940968instance Monad (BehaviorM x) where
941969 {-# INLINE (>>=) #-}
@@ -986,7 +1014,7 @@ data RootSubscribed x a = forall k. GCompare k => RootSubscribed
9861014#endif
9871015 }
9881016
989−data Root x (k :: * -> *)
1017+data Root x k
9901018 = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
9911019 , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
9921020 , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
@@ -1056,25 +1084,25 @@ heightBagVerify b@(HeightBag s c) = if
10561084heightBagVerify = id
10571085#endif
10581086
1059−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1060− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1061− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1062− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1087+data FanSubscribedChildren x k v a = FanSubscribedChildren
1088+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1089+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1090+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
10631091 }
10641092
1065−data FanSubscribed (x :: *) k
1066− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1067− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1068− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1093+data FanSubscribed x k v
1094+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1095+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1096+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
10691097 , fanSubscribedParent :: !(EventSubscription x)
10701098#ifdef DEBUG_NODEIDS
10711099 , fanSubscribedNodeId :: Int
10721100#endif
10731101 }
10741102
1075−data Fan x k
1076− = Fan { fanParent :: !(Event x (DMap k Identity))
1077− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1103+data Fan x k v
1104+ = Fan { fanParent :: !(Event x (DMap k v))
1105+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
10781106 }
10791107
10801108data SwitchSubscribed x a
@@ -1136,19 +1164,27 @@ instance HasSpiderTimeline x => Align (Event x) where
11361164#if MIN_VERSION_these(0, 8, 0)
11371165instance HasSpiderTimeline x => Semialign (Event x) where
11381166#endif
1139− align ea eb = mapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1167+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1168+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1169+
1170+#ifdef MIN_VERSION_semialign
1171+#if MIN_VERSION_semialign(1,1,0)
1172+instance HasSpiderTimeline x => Zip (Event x) where
1173+#endif
1174+ zip x y = mapMaybe justThese $ align x y
1175+#endif
11401176
11411177data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
11421178 | BuildDyn !(EventM x (PatchTarget p), Event x p)
11431179 | HoldDyn !(Hold x p)
11441180
1145−newtype Dyn x p = Dyn { unDyn :: IORef (DynType x p) }
1181+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
11461182
1147−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1183+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
11481184newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
11491185
11501186--TODO: Avoid the duplication between this and R.zipDynWith
1151−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1187+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
11521188zipDynWith f da db =
11531189 let eab = align (dynamicUpdated da) (dynamicUpdated db)
11541190 ec = flip push eab $ \o -> do
@@ -1171,18 +1207,12 @@ buildDynamic readV0 v' = do
11711207 return d
11721208
11731209unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1174−unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1175− where x = (readV0, v')
1210+unsafeBuildDynamic readV0 v' =
1211+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
11761212
11771213-- ResultM can read behaviors and events
11781214type ResultM = EventM
11791215
1180−{-# NOINLINE unsafeNewIORef #-}
1181−unsafeNewIORef :: a -> b -> IORef b
1182−unsafeNewIORef a b = unsafePerformIO $ do
1183− touch a
1184− newIORef b
1185−
11861216instance HasSpiderTimeline x => Functor (Event x) where
11871217 fmap f = push $ return . Just . f
11881218
@@ -1195,33 +1225,42 @@ push f e = cacheEvent (pushCheap f e)
11951225
11961226{-# INLINABLE pull #-}
11971227pull :: BehaviorM x a -> Behavior x a
1198−pull a = behaviorPull $ Pull
1199− { pullCompute = a
1200− , pullValue = unsafeNewIORef a Nothing
1228+pull a = unsafePerformIO $ do
1229+ ref <- newIORef Nothing
12011230#ifdef DEBUG_NODEIDS
1202− , pullNodeId = unsafeNodeId a
1231+ nid <- newNodeId
12031232#endif
1204− }
1233+ pure $ behaviorPull $ Pull
1234+ { pullCompute = a
1235+ , pullValue = ref
1236+#ifdef DEBUG_NODEIDS
1237+ , pullNodeId = nid
1238+#endif
1239+ }
12051240
12061241{-# INLINABLE switch #-}
12071242switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1208−switch a = eventSwitch $ Switch
1209− { switchParent = a
1210− , switchSubscribed = unsafeNewIORef a Nothing
1211− }
1243+switch a = unsafePerformIO $ do
1244+ ref <- newIORef Nothing
1245+ pure $ eventSwitch $ Switch
1246+ { switchParent = a
1247+ , switchSubscribed = ref
1248+ }
12121249
12131250coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1214−coincidence a = eventCoincidence $ Coincidence
1215− { coincidenceParent = a
1216− , coincidenceSubscribed = unsafeNewIORef a Nothing
1217− }
1251+coincidence a = unsafePerformIO $ do
1252+ ref <- newIORef Nothing
1253+ pure $ eventCoincidence $ Coincidence
1254+ { coincidenceParent = a
1255+ , coincidenceSubscribed = ref
1256+ }
12181257
12191258-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
12201259run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
12211260run roots after = do
12221261 tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
12231262 let t = spiderTimeline :: SpiderTimelineEnv x
1224− result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1263+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
12251264 rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
12261265 occBefore <- liftIO $ do
12271266 occBefore <- readIORef occRef
@@ -1285,9 +1324,9 @@ type WeakList a = [Weak a]
12851324withIncreasedDepth :: CanTrace x m => m a -> m a
12861325withIncreasedDepth a = do
12871326 spiderTimeline <- askSpiderTimelineEnv
1288− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1327+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
12891328 result <- a
1290− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1329+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
12911330 return result
12921331#else
12931332withIncreasedDepth :: m a -> m a
@@ -1314,7 +1353,7 @@ traceMWhen _ b getMessage = when b $ do
13141353 message <- getMessage
13151354#ifdef DEBUG
13161355 spiderTimeline <- askSpiderTimelineEnv
1317− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1356+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
13181357#else
13191358 let d = 0
13201359#endif
@@ -1355,25 +1394,25 @@ propagateSubscriberHold h a = do
13551394data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
13561395
13571396runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1358−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1397+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
13591398
13601399askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
13611400askInvalidator = do
1362− (!m, _) <- BehaviorM ask
1401+ (!m, _) <- ask
13631402 case m of
13641403 Nothing -> return Nothing
13651404 Just (!wi, _) -> return $ Just wi
13661405
13671406askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
13681407askParentsRef = do
1369− (!m, _) <- BehaviorM ask
1408+ (!m, _) <- ask
13701409 case m of
13711410 Nothing -> return Nothing
13721411 Just (_, !p) -> return $ Just p
13731412
13741413askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
13751414askBehaviorHoldInits = do
1376− (_, !his) <- BehaviorM ask
1415+ (_, !his) <- ask
13771416 return his
13781417
13791418{-# INLINE getDynHold #-}
@@ -1418,6 +1457,9 @@ getRootSubscribed k r sub = do
14181457 when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
14191458 uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
14201459 writeIORef uninitRef $! uninit
1460+#ifdef DEBUG_NODEIDS
1461+ nid <- newNodeId
1462+#endif
14211463 let !subscribed = RootSubscribed
14221464 { rootSubscribedKey = k
14231465 , rootSubscribedCachedSubscribed = cached
@@ -1426,7 +1468,7 @@ getRootSubscribed k r sub = do
14261468 , rootSubscribedUninit = uninit
14271469 , rootSubscribedWeakSelf = weakSelf
14281470#ifdef DEBUG_NODEIDS
1429− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1471+ , rootSubscribedNodeId = nid
14301472#endif
14311473 }
14321474 -- If we die at the same moment that all our children die, they will
@@ -1475,16 +1517,10 @@ newFanInt = do
14751517 , _fanInt_occRef = occRef
14761518 }
14771519
1478−{-# NOINLINE unsafeNewFanInt #-}
1479−unsafeNewFanInt :: b -> FanInt x a
1480−unsafeNewFanInt b = unsafePerformIO $ do
1481− touch b
1482− newFanInt
1483−
14841520fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1485−fanInt p =
1486− let self = unsafeNewFanInt p
1487− in EventSelectorInt $ \k -> Event $ \sub -> do
1521+fanInt p = unsafePerformIO $ do
1522+ self <- newFanInt
1523+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
14881524 isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
14891525 when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
14901526 (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
@@ -1492,15 +1528,15 @@ fanInt p =
14921528 liftIO $ writeIORef (_fanInt_occRef self) m
14931529 scheduleIntClear $ _fanInt_occRef self
14941530 FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1495− FastWeakBag.traverse b $ \s -> do
1531+ FastWeakBag.traverse_ b $ \s -> do
14961532 subscriberPropagate s v
14971533 , subscriberInvalidateHeight = \old -> do
14981534 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1499− FastWeakBag.traverse b $ \s -> do
1535+ FastWeakBag.traverse_ b $ \s -> do
15001536 subscriberInvalidateHeight s old
15011537 , subscriberRecalculateHeight = \new -> do
15021538 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1503− FastWeakBag.traverse b $ \s -> do
1539+ FastWeakBag.traverse_ b $ \s -> do
15041540 subscriberRecalculateHeight s new
15051541 }
15061542 liftIO $ do
@@ -1520,7 +1556,7 @@ fanInt p =
15201556 return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
15211557
15221558{-# INLINABLE getFanSubscribed #-}
1523−getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1559+getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k v, Maybe (v a))
15241560getFanSubscribed k f sub = do
15251561 mSubscribed <- liftIO $ readIORef $ fanSubscribed f
15261562 case mSubscribed of
@@ -1538,13 +1574,16 @@ getFanSubscribed k f sub = do
15381574 subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
15391575 occRef <- liftIO $ newIORef parentOcc
15401576 when (isJust parentOcc) $ scheduleClear occRef
1577+#ifdef DEBUG_NODEIDS
1578+ nid <- liftIO newNodeId
1579+#endif
15411580 let subscribed = FanSubscribed
15421581 { fanSubscribedCachedSubscribed = fanSubscribed f
15431582 , fanSubscribedOccurrence = occRef
15441583 , fanSubscribedParent = subscription
15451584 , fanSubscribedSubscribers = subscribersRef
15461585#ifdef DEBUG_NODEIDS
1547− , fanSubscribedNodeId = unsafeNodeId f
1586+ , fanSubscribedNodeId = nid
15481587#endif
15491588 }
15501589 let !self = (k, subscribed)
@@ -1554,7 +1593,7 @@ getFanSubscribed k f sub = do
15541593 liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
15551594 return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
15561595
1557−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1596+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
15581597cleanupFanSubscribed (k, subscribed) = do
15591598 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15601599 let reducedSubscribers = DMap.delete k subscribers
@@ -1566,7 +1605,7 @@ cleanupFanSubscribed (k, subscribed) = do
15661605 else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
15671606
15681607{-# INLINE subscribeFanSubscribed #-}
1569−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1608+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
15701609subscribeFanSubscribed k subscribed sub = do
15711610 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15721611 case DMap.lookup k subscribers of
@@ -1604,6 +1643,9 @@ getSwitchSubscribed s sub = do
16041643 when (isJust parentOcc) $ scheduleClear occRef
16051644 weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
16061645 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1646+#ifdef DEBUG_NODEIDS
1647+ nid <- liftIO newNodeId
1648+#endif
16071649 let !subscribed = SwitchSubscribed
16081650 { switchSubscribedCachedSubscribed = switchSubscribed s
16091651 , switchSubscribedOccurrence = occRef
@@ -1616,7 +1658,7 @@ getSwitchSubscribed s sub = do
16161658 , switchSubscribedCurrentParent = subscriptionRef
16171659 , switchSubscribedWeakSelf = weakSelf
16181660#ifdef DEBUG_NODEIDS
1619− , switchSubscribedNodeId = unsafeNodeId s
1661+ , switchSubscribedNodeId = nid
16201662#endif
16211663 }
16221664 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
@@ -1661,6 +1703,9 @@ getCoincidenceSubscribed c sub = do
16611703 scheduleClear innerSubdRef
16621704 weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
16631705 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1706+#ifdef DEBUG_NODEIDS
1707+ nid <- liftIO newNodeId
1708+#endif
16641709 let subscribed = CoincidenceSubscribed
16651710 { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
16661711 , coincidenceSubscribedOccurrence = occRef
@@ -1671,7 +1716,7 @@ getCoincidenceSubscribed c sub = do
16711716 , coincidenceSubscribedInnerParent = innerSubdRef
16721717 , coincidenceSubscribedWeakSelf = weakSelf
16731718#ifdef DEBUG_NODEIDS
1674− , coincidenceSubscribedNodeId = unsafeNodeId c
1719+ , coincidenceSubscribedNodeId = nid
16751720#endif
16761721 }
16771722 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
@@ -1688,26 +1733,34 @@ cleanupCoincidenceSubscribed subscribed = do
16881733subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
16891734subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
16901735
1691−{-# INLINE merge #-}
1692−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1693−merge d = cacheEvent (mergeCheap d)
1736+{-# INLINE mergeG #-}
1737+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1738+ => (forall a. q a -> Event x (v a))
1739+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1740+mergeG nt d = cacheEvent (mergeCheap nt d)
16941741
16951742{-# INLINE mergeWithMove #-}
1696−mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1697−mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1743+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1744+ => (forall a. q a -> Event x (v a))
1745+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1746+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
16981747
16991748{-# INLINE [1] mergeCheap #-}
1700−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1701−mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1749+mergeCheap
1750+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1751+ => (forall a. q a -> Event x (v a))
1752+ -> DynamicS x (PatchDMap k q)
1753+ -> Event x (DMap k v)
1754+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
17021755 where
1703− updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1756+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
17041757 updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
17051758 let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
17061759 (mOldSubd, newPs) <- case me of
17071760 Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
17081761 Just e -> do
17091762 let s = subscriber $ return k
1710− subscription@(EventSubscription _ subd) <- subscribe e s
1763+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
17111764 newParentHeight <- liftIO $ getEventSubscribedHeight subd
17121765 let newParent = MergeSubscribedParent subscription
17131766 liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
@@ -1717,28 +1770,33 @@ mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
17171770 liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
17181771 return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
17191772 foldM f ([], oldParents) $ DMap.toList p
1720− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1773+
1774+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
17211775 getInitialSubscribers initialParents subscriber = do
17221776 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17231777 let s = subscriber $ return k
1724− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1778+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17251779 height <- liftIO $ getEventSubscribedHeight parentSubd
1726− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1780+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
17271781 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17281782 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17291783 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17301784 )
1785+
17311786 destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
17321787 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
17331788
17341789{-# INLINE [1] mergeCheapWithMove #-}
1735−mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1736−mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1790+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1791+ => (forall a. q a -> Event x (v a))
1792+ -> DynamicS x (PatchDMapWithMove k q)
1793+ -> Event x (DMap k v)
1794+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
17371795 where
1738− updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1796+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
17391797 updateMe subscriber heightBagRef oldParents p = do
17401798 -- Prepare new parents for insertion
1741− let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1799+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
17421800 subscribeParent k e = do
17431801 keyRef <- liftIO $ newIORef k
17441802 let s = subscriber $ liftIO $ readIORef keyRef
@@ -1747,9 +1805,9 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17471805 newParentHeight <- getEventSubscribedHeight subd
17481806 modifyIORef' heightBagRef $ heightBagAdd newParentHeight
17491807 return $ MergeSubscribedParentWithMove subscription keyRef
1750− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1808+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
17511809 -- Collect old parents for deletion and update the keys of moved parents
1752− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1810+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
17531811 moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
17541812 Nothing -> do
17551813 oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
@@ -1760,46 +1818,47 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17601818 return Nothing
17611819 toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
17621820 return (toDelete, applyAlways p' oldParents)
1763− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1821+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
17641822 getInitialSubscribers initialParents subscriber = do
17651823 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17661824 keyRef <- liftIO $ newIORef k
17671825 let s = subscriber $ liftIO $ readIORef keyRef
1768− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1826+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17691827 height <- liftIO $ getEventSubscribedHeight parentSubd
1770− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1828+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
17711829 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17721830 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17731831 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17741832 )
1833+
17751834 destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
17761835 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
17771836
1778−type MergeUpdateFunc k x p s
1779− = (forall a. EventM x (k a) -> Subscriber x a)
1837+type MergeUpdateFunc k v x p s
1838+ = (forall a. EventM x (k a) -> Subscriber x (v a))
17801839 -> IORef HeightBag
17811840 -> DMap k s
17821841 -> p
17831842 -> EventM x ([EventSubscription x], DMap k s)
17841843
1785−type MergeInitFunc k x s
1786− = DMap k (Event x)
1787− -> (forall a. EventM x (k a) -> Subscriber x a)
1788− -> EventM x (DMap k Identity, [Height], DMap k s)
1844+type MergeInitFunc k v q x s
1845+ = DMap k q
1846+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1847+ -> EventM x (DMap k v, [Height], DMap k s)
17891848
17901849type MergeDestroyFunc k s
17911850 = DMap k s
17921851 -> IO ()
17931852
1794−data Merge x k s = Merge
1853+data Merge x k v s = Merge
17951854 { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
17961855 , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
17971856 , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1798− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1799− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1857+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1858+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
18001859 }
18011860
1802−invalidateMergeHeight :: Merge x k s -> IO ()
1861+invalidateMergeHeight :: Merge x k v s -> IO ()
18031862invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
18041863
18051864invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
@@ -1809,8 +1868,7 @@ invalidateMergeHeight' heightRef sub = do
18091868 writeIORef heightRef $! invalidHeight
18101869 subscriberInvalidateHeight sub oldHeight
18111870
1812−
1813−revalidateMergeHeight :: Merge x k s -> IO ()
1871+revalidateMergeHeight :: Merge x k v s -> IO ()
18141872revalidateMergeHeight m = do
18151873 currentHeight <- readIORef $ _merge_heightRef m
18161874 when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
@@ -1826,19 +1884,19 @@ revalidateMergeHeight m = do
18261884 subscriberRecalculateHeight (_merge_sub m) height
18271885 GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
18281886
1829−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1887+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
18301888scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
18311889 vals <- liftIO $ readIORef $ _merge_accumRef m
18321890 liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty -- Once we're done with this, we can clear it immediately, because if there's a cacheEvent in front of us, it'll handle subsequent subscribers, and if not, we won't get subsequent subscribers
18331891 --TODO: Assert that m is not empty
18341892 subscriberPropagate (_merge_sub m) vals
18351893
1836−mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1894+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
18371895mergeSubscriber m getKey = Subscriber
18381896 { subscriberPropagate = \a -> do
18391897 oldM <- liftIO $ readIORef $ _merge_accumRef m
18401898 k <- getKey
1841− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1899+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
18421900 tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
18431901 liftIO $ writeIORef (_merge_accumRef m) $! newM
18441902 when (DMap.null oldM) $ do -- Only schedule the firing once
@@ -1853,7 +1911,7 @@ mergeSubscriber m getKey = Subscriber
18531911 else liftIO $ do
18541912#ifdef DEBUG_CYCLES
18551913 nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1856− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1914+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
18571915 let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
18581916#else
18591917 let cycleInfo = ""
@@ -1869,7 +1927,7 @@ mergeSubscriber m getKey = Subscriber
18691927 }
18701928
18711929--TODO: Be able to run as much of this as possible promptly
1872−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1930+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
18731931updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
18741932 where updateMe = do
18751933 oldParents <- liftIO $ readIORef $ _merge_parentsRef m
@@ -1877,9 +1935,10 @@ updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m)
18771935 liftIO $ writeIORef (_merge_parentsRef m) $! newParents
18781936 return subscriptionsToKill
18791937
1880−{-# INLINE mergeCheap' #-}
1881−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 -> Dynamic x p -> Event x (DMap k Identity)
1882−mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1938+{-# INLINE mergeGCheap' #-}
1939+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1940+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1941+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
18831942 initialParents <- readBehaviorUntracked $ dynamicCurrent d
18841943 accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
18851944 heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
@@ -1927,11 +1986,11 @@ mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
19271986 , occ
19281987 )
19291988
1930−mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1989+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
19311990mergeInt = cacheEvent . mergeIntCheap
19321991
19331992{-# INLINABLE mergeIntCheap #-}
1934−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1993+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
19351994mergeIntCheap d = Event $ \sub -> do
19361995 initialParents <- readBehaviorUntracked $ dynamicCurrent d
19371996 accum <- liftIO $ FastMutableIntMap.newEmpty
@@ -2028,14 +2087,16 @@ mergeIntCheap d = Event $ \sub -> do
20282087 )
20292088
20302089newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2090+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
20312091
2032−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2033−fan e =
2092+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2093+fanG e = unsafePerformIO $ do
2094+ ref <- newIORef Nothing
20342095 let f = Fan
20352096 { fanParent = e
2036− , fanSubscribed = unsafeNewIORef e Nothing
2097+ , fanSubscribed = ref
20372098 }
2038− in EventSelector $ \k -> eventFan k f
2099+ pure $ EventSelectorG $ \k -> eventFan k f
20392100
20402101runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
20412102runHoldInits holdInitRef dynInitRef mergeInitRef = do
@@ -2089,18 +2150,18 @@ clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeI
20892150-- | Run an event action outside of a frame
20902151runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
20912152runFrame a = SpiderHost $ do
2092− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2153+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
20932154 let go = do
20942155 result <- a
20952156 runHoldInits (eventEnvHoldInits env) (eventEnvDynInits 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
20962157 return result
20972158 result <- runEventM go
20982159 toClear <- readIORef $ eventEnvClears env
2099− forM_ toClear $ \(Some.This (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2160+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
21002161 toClearInt <- readIORef $ eventEnvIntClears env
2101− forM_ toClearInt $ \(Some.This (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2162+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
21022163 toClearRoot <- readIORef $ eventEnvRootClears env
2103− forM_ toClearRoot $ \(Some.This (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2164+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
21042165 toAssign <- readIORef $ eventEnvAssignments env
21052166 toReconnectRef <- newIORef []
21062167 coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
@@ -2147,7 +2208,7 @@ runFrame a = SpiderHost $ do
21472208 myHeight <- readIORef $ switchSubscribedHeight subscribed
21482209 when (parentHeight /= myHeight) $ do
21492210 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2150− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2211+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
21512212 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
21522213 forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
21532214 unsubscribe subscription
@@ -2188,7 +2249,7 @@ invalidateCoincidenceHeight subscribed = do
21882249 oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
21892250 when (oldHeight /= invalidHeight) $ do
21902251 writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2191− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2252+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
21922253
21932254updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
21942255updateSwitchHeight new subscribed = do
@@ -2196,7 +2257,7 @@ updateSwitchHeight new subscribed = do
21962257 when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21972258 when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21982259 writeIORef (switchSubscribedHeight subscribed) $! new
2199− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2260+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
22002261
22012262recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
22022263recalculateCoincidenceHeight subscribed = do
@@ -2205,7 +2266,7 @@ recalculateCoincidenceHeight subscribed = do
22052266 height <- calculateCoincidenceHeight subscribed
22062267 when (height /= invalidHeight) $ do
22072268 writeIORef (coincidenceSubscribedHeight subscribed) $! height
2208− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2269+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
22092270
22102271calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
22112272calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
@@ -2300,7 +2361,7 @@ instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x))
23002361 fail _ = error "Dynamic does not support 'fail'"
23012362
23022363{-# INLINABLE newJoinDyn #-}
2303−newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2364+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
23042365newJoinDyn d =
23052366 let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
23062367 eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
@@ -2450,7 +2511,7 @@ unsafeNewSpiderTimelineEnv = do
24502511#ifdef DEBUG
24512512 depthRef <- newIORef 0
24522513#endif
2453− return $ SpiderTimelineEnv
2514+ return $ STE $ SpiderTimelineEnv
24542515 { _spiderTimeline_lock = lock
24552516 , _spiderTimeline_eventEnv = env
24562517#ifdef DEBUG
@@ -2460,19 +2521,19 @@ unsafeNewSpiderTimelineEnv = do
24602521
24612522-- | Create a new SpiderTimelineEnv
24622523newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2463−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2524+newSpiderTimeline = withSpiderTimeline (pure . Some)
24642525
2465−data LocalSpiderTimeline x s
2526+data LocalSpiderTimeline (x :: Type) s
24662527
24672528instance Reifies s (SpiderTimelineEnv x) =>
24682529 HasSpiderTimeline (LocalSpiderTimeline x s) where
2469− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2530+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
24702531
24712532localSpiderTimeline
2472− :: Proxy s
2533+ :: proxy s
24732534 -> SpiderTimelineEnv x
24742535 -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2475−localSpiderTimeline _ = unsafeCoerce
2536+localSpiderTimeline _ = coerce
24762537
24772538-- | Pass a new timeline to the given function.
24782539withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
@@ -2480,18 +2541,18 @@ withSpiderTimeline k = do
24802541 env <- unsafeNewSpiderTimelineEnv
24812542 reify env $ \s -> k $ localSpiderTimeline s env
24822543
2483−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2544+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
24842545
24852546type ComputeM = EventM
24862547
2487−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2548+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
24882549
24892550instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
24902551 {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
24912552 newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
24922553 newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2493− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2494− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2554+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2555+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
24952556 type PullM (SpiderTimeline x) = SpiderPullM x
24962557 type PushM (SpiderTimeline x) = SpiderPushM x
24972558 {-# INLINABLE never #-}
@@ -2504,10 +2565,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25042565 pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
25052566 {-# INLINABLE pull #-}
25062567 pull = SpiderBehavior . pull . coerce
2507− {-# INLINABLE merge #-}
2508− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2509− {-# INLINABLE fan #-}
2510− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2568+ {-# INLINABLE fanG #-}
2569+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2570+ {-# INLINABLE mergeG #-}
2571+ mergeG
2572+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2573+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2574+ -> DMap k q
2575+ -> R.Event (SpiderTimeline x) (DMap k v)
2576+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
25112577 {-# INLINABLE switch #-}
25122578 switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
25132579 {-# INLINABLE coincidence #-}
@@ -2515,15 +2581,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25152581 {-# INLINABLE current #-}
25162582 current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
25172583 {-# INLINABLE updated #-}
2518− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2584+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
25192585 {-# INLINABLE unsafeBuildDynamic #-}
25202586 unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
25212587 {-# INLINABLE unsafeBuildIncremental #-}
25222588 unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2523− {-# INLINABLE mergeIncremental #-}
2524− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2525− {-# INLINABLE mergeIncrementalWithMove #-}
2526− mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2589+ {-# INLINABLE mergeIncrementalG #-}
2590+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2591+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2592+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
25272593 {-# INLINABLE currentIncremental #-}
25282594 currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
25292595 {-# INLINABLE updatedIncremental #-}
@@ -2534,9 +2600,10 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25342600 return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
25352601 eventCoercion Coercion = Coercion
25362602 behaviorCoercion Coercion = Coercion
2537− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2603+ dynamicCoercion Coercion = Coercion
2604+ incrementalCoercion Coercion Coercion = Coercion
25382605 {-# INLINABLE mergeIntIncremental #-}
2539− mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2606+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
25402607 {-# INLINABLE fanInt #-}
25412608 fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
25422609
@@ -2561,7 +2628,7 @@ instance MonadAtomicRef (EventM x) where
25612628 atomicModifyRef r f = liftIO $ atomicModifyRef r f
25622629
25632630-- | The monad for actions that manipulate a Spider timeline identified by @x@
2564−newtype SpiderHost x a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2631+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
25652632
25662633instance Monad (SpiderHost x) where
25672634 {-# INLINABLE (>>=) #-}
@@ -2583,7 +2650,7 @@ runSpiderHost (SpiderHost a) = a
25832650runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
25842651runSpiderHostForTimeline (SpiderHost a) _ = a
25852652
2586−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2653+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
25872654 deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
25882655
25892656instance Monad (SpiderHostFrame x) where
@@ -2639,3 +2706,11 @@ instance MonadAtomicRef (SpiderHostFrame x) where
26392706instance PrimMonad (SpiderHostFrame x) where
26402707 type PrimState (SpiderHostFrame x) = PrimState IO
26412708 primitive = SpiderHostFrame . EventM . primitive
2709+
2710+instance NotReady (SpiderTimeline x) (SpiderHost x) where
2711+ notReadyUntil _ = return ()
2712+ notReady = return ()
2713+
2714+instance HasSpiderTimeline x => NotReady (SpiderTimeline x) (PerformEventT (SpiderTimeline x) (SpiderHost x)) where
2715+ notReadyUntil _ = return ()
2716+ notReady = return ()