@@ -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,20 +57,30 @@ import Data.GADT.Compare
4957import Data.IntMap.Strict (IntMap)
5058import qualified Data.IntMap.Strict as IntMap
5159import Data.IORef
52−import Data.Maybe
60+import Data.Kind (Type)
61+import Data.Maybe hiding (mapMaybe)
5362import Data.Monoid ((<>))
5463import Data.Proxy
5564import Data.These
5665import Data.Traversable
66+import Data.Witherable (Filterable, mapMaybe)
5767import GHC.Exts
5868import GHC.IORef (IORef (..))
5969import GHC.Stack
6070import Reflex.FastWeak
61−import Reflex.FunctorMaybe
6271import 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
@@ -193,12 +211,6 @@ nextNodeIdRef = unsafePerformIO $ newIORef 1
193211
194212newNodeId :: IO Int
195213newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
196−
197−{-# NOINLINE unsafeNodeId #-}
198−unsafeNodeId :: a -> Int
199−unsafeNodeId a = unsafePerformIO $ do
200− touch a
201− newNodeId
202214#endif
203215
204216--------------------------------------------------------------------------------
@@ -302,9 +314,10 @@ cacheEvent e =
302314#else
303315 Event $
304316#endif
305− let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
306− !mSubscribedRef = unsafeNewIORef e emptyFastWeak
307− in \sub -> {-# SCC "cacheEvent" #-} do
317+ unsafePerformIO $ do
318+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
319+ <- newIORef emptyFastWeak
320+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
308321#ifdef DEBUG_TRACE_EVENTS
309322 unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
310323#endif
@@ -319,9 +332,9 @@ cacheEvent e =
319332 scheduleClear occRef
320333 propagateFast a subscribers
321334 , subscriberInvalidateHeight = \old -> do
322− FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
335+ FastWeakBag.traverse_ subscribers $ invalidateSubscriberHeight old
323336 , subscriberRecalculateHeight = \new -> do
324− FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
337+ FastWeakBag.traverse_ subscribers $ recalculateSubscriberHeight new
325338 }
326339 when (isJust occ) $ do
327340 liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
@@ -370,7 +383,7 @@ eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed
370383eventNever :: Event x a
371384eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
372385
373−eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k -> Event x a
386+eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)
374387eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
375388
376389eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
@@ -422,14 +435,14 @@ newSubscriberHold h = return $ Subscriber
422435 , subscriberRecalculateHeight = \_ -> return ()
423436 }
424437
425−newSubscriberFan :: forall x k. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
438+newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))
426439newSubscriberFan subscribed = return $ Subscriber
427440 { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
428441 subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
429442 tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
430443 liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
431444 scheduleClear $ fanSubscribedOccurrence subscribed
432− let f _ (Pair (Identity v) subsubs) = do
445+ let f _ (Pair v subsubs) = do
433446 propagate v $ _fanSubscribedChildren_list subsubs
434447 return $ Constant ()
435448 _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
@@ -437,12 +450,12 @@ newSubscriberFan subscribed = return $ Subscriber
437450 , subscriberInvalidateHeight = \old -> do
438451 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
439452 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
440− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
453+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
441454 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
442455 , subscriberRecalculateHeight = \new -> do
443456 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
444457 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
445− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
458+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
446459 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
447460 }
448461
@@ -458,7 +471,7 @@ newSubscriberSwitch subscribed = return $ Subscriber
458471 oldHeight <- readIORef $ switchSubscribedHeight subscribed
459472 when (oldHeight /= invalidHeight) $ do
460473 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
461− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
474+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
462475 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
463476 , subscriberRecalculateHeight = \new -> do
464477 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
@@ -481,8 +494,8 @@ newSubscriberCoincidenceOuter subscribed = return $ Subscriber
481494 Nothing -> do
482495 when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
483496 writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
484− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
485− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
497+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
498+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
486499 Just o -> do -- Since it's already firing, no need to adjust height
487500 liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
488501 scheduleClear $ coincidenceSubscribedOccurrence subscribed
@@ -529,14 +542,14 @@ propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
529542propagate a subscribers = withIncreasedDepth $ do
530543 -- 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
531544 --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
545+ WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
533546
534547-- | Propagate everything at the current height
535548propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
536549propagateFast a subscribers = withIncreasedDepth $ do
537550 -- 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
538551 --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
552+ FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
540553
541554--------------------------------------------------------------------------------
542555-- EventSubscribed
@@ -545,6 +558,11 @@ propagateFast a subscribers = withIncreasedDepth $ do
545558toAny :: a -> Any
546559toAny = unsafeCoerce
547560
561+-- Why do we use Any here, instead of just giving eventSubscribedRetained an
562+-- existential type? Sadly, GHC does not currently know how to unbox types
563+-- with existentially quantified fields. So instead we just coerce values
564+-- to type Any on the way in. Since we never coerce them back, this is
565+-- perfectly safe.
548566data EventSubscribed x = EventSubscribed
549567 { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
550568 , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
@@ -577,12 +595,12 @@ eventSubscribedNever = EventSubscribed
577595#endif
578596 }
579597
580−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
598+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
581599eventSubscribedFan !subscribed = EventSubscribed
582600 { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
583601 , eventSubscribedRetained = toAny subscribed
584602#ifdef DEBUG_CYCLES
585− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
603+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
586604 , eventSubscribedHasOwnHeightRef = False
587605 , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
588606#endif
@@ -595,7 +613,7 @@ eventSubscribedSwitch !subscribed = EventSubscribed
595613#ifdef DEBUG_CYCLES
596614 , eventSubscribedGetParents = do
597615 s <- readIORef $ switchSubscribedCurrentParent subscribed
598− return [Some.This $ _eventSubscription_subscribed s]
616+ return [Some $ _eventSubscription_subscribed s]
599617 , eventSubscribedHasOwnHeightRef = True
600618 , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
601619#endif
@@ -608,8 +626,8 @@ eventSubscribedCoincidence !subscribed = EventSubscribed
608626#ifdef DEBUG_CYCLES
609627 , eventSubscribedGetParents = do
610628 innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
611− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
612− innerParents = maybeToList $ fmap Some.This innerSubscription
629+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
630+ innerParents = maybeToList $ fmap Some innerSubscription
613631 return $ outerParent : innerParents
614632 , eventSubscribedHasOwnHeightRef = True
615633 , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
@@ -625,13 +643,13 @@ whoCreatedEventSubscribed = eventSubscribedWhoCreated
625643
626644walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
627645walkInvalidHeightParents s0 = do
628− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
646+ subscribers <- flip execStateT mempty $ ($ Some s0) $ fix $ \loop (Some s) -> do
629647 h <- liftIO $ readIORef $ eventSubscribedHeightRef s
630648 when (h == invalidHeight) $ do
631649 when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
632− modify (Some.This s :)
650+ modify (Some s :)
633651 mapM_ loop =<< liftIO (eventSubscribedGetParents s)
634− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
652+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
635653 return subscribers
636654#endif
637655
@@ -659,7 +677,7 @@ behaviorPull !p = Behavior $ do
659677 val <- liftIO $ readIORef $ pullValue p
660678 case val of
661679 Just subscribed -> do
662− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
680+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
663681 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
664682 liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
665683 return $ pullSubscribedValue subscribed
@@ -668,7 +686,7 @@ behaviorPull !p = Behavior $ do
668686 wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
669687 parentsRef <- liftIO $ newIORef []
670688 holdInits <- askBehaviorHoldInits
671− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
689+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
672690 invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
673691 parents <- liftIO $ readIORef parentsRef
674692 let subscribed = PullSubscribed
@@ -678,7 +696,7 @@ behaviorPull !p = Behavior $ do
678696 , pullSubscribedParents = parents
679697 }
680698 liftIO $ writeIORef (pullValue p) $ Just subscribed
681− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
699+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
682700 return a
683701
684702behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
@@ -689,7 +707,7 @@ readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
689707readHoldTracked h = do
690708 result <- liftIO $ readIORef $ holdValue h
691709 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
692− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
710+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
693711 liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
694712 return result
695713
@@ -703,42 +721,46 @@ readBehaviorUntracked b = do
703721-- Dynamic
704722--------------------------------------------------------------------------------
705723
706−data Dynamic x p = Dynamic
707− { dynamicCurrent :: !(Behavior x (PatchTarget p))
708− , dynamicUpdated :: !(Event x p)
724+type DynamicS x p = Dynamic x (PatchTarget p) p
725+
726+data Dynamic x target p = Dynamic
727+ { dynamicCurrent :: !(Behavior x target)
728+ , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
709729 }
710730
711−dynamicHold :: Hold x p -> Dynamic x p
731+deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)
732+
733+
734+
735+
736+dynamicHold :: Hold x p -> DynamicS x p
712737dynamicHold !h = Dynamic
713738 { dynamicCurrent = behaviorHold h
714739 , dynamicUpdated = eventHold h
715740 }
716741
717−dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
742+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
718743dynamicHoldIdentity = dynamicHold
719744
720−dynamicConst :: PatchTarget p -> Dynamic x p
745+dynamicConst :: PatchTarget p -> DynamicS x p
721746dynamicConst !a = Dynamic
722747 { dynamicCurrent = behaviorConst a
723748 , dynamicUpdated = eventNever
724749 }
725750
726−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
751+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
727752dynamicDyn !d = Dynamic
728753 { dynamicCurrent = behaviorDyn d
729754 , dynamicUpdated = eventDyn d
730755 }
731756
732−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
757+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
733758dynamicDynIdentity = dynamicDyn
734759
735760--------------------------------------------------------------------------------
736761-- Combinators
737762--------------------------------------------------------------------------------
738763
739−--TODO: Figure out why certain things are not 'representational', then make them
740−--representational so we can use coerce
741−
742764--type role Hold representational
743765data Hold x p
744766 = Hold { holdValue :: !(IORef (PatchTarget p))
@@ -759,20 +781,25 @@ globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
759781
760782-- | Stores all global data relevant to a particular Spider timeline; only one
761783-- value should exist for each type @x@
762−data SpiderTimelineEnv x = SpiderTimelineEnv
784+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}
785+-- We implement SpiderTimelineEnv with a newtype wrapper so
786+-- we can get the coercions we want safely.
787+type role SpiderTimelineEnv nominal
788+
789+data SpiderTimelineEnv' x = SpiderTimelineEnv
763790 { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
764791 , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
765792#ifdef DEBUG
766793 , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
767794#endif
768795 }
769−type role SpiderTimelineEnv nominal
796+type role SpiderTimelineEnv' phantom
770797
771798instance Eq (SpiderTimelineEnv x) where
772799 _ == _ = True -- Since only one exists of each type
773800
774801instance GEq SpiderTimelineEnv where
775− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
802+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
776803 then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
777804 else Nothing
778805
@@ -782,9 +809,9 @@ data EventEnv x
782809 , eventEnvDynInits :: !(IORef [SomeDynInit x])
783810 , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
784811 , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
785− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
786− , eventEnvIntClears :: !(IORef [SomeIntClear])
787− , eventEnvRootClears :: !(IORef [SomeRootClear])
812+ , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe
813+ , eventEnvIntClears :: !(IORef [Some IntClear])
814+ , eventEnvRootClears :: !(IORef [Some RootClear])
788815 , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
789816 , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
790817 , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))
@@ -795,7 +822,7 @@ runEventM :: EventM x a -> IO a
795822runEventM = unEventM
796823
797824asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
798−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
825+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
799826
800827class MonadIO m => Defer a m where
801828 getDeferralQueue :: m (IORef [a])
@@ -856,29 +883,29 @@ putCurrentHeight h = do
856883 heightRef <- asksEventEnv eventEnvCurrentHeight
857884 liftIO $ writeIORef heightRef $! h
858885
859−instance HasSpiderTimeline x => Defer SomeClear (EventM x) where
886+instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
860887 {-# INLINE getDeferralQueue #-}
861888 getDeferralQueue = asksEventEnv eventEnvClears
862889
863890{-# INLINE scheduleClear #-}
864−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
865−scheduleClear r = defer $ SomeClear r
891+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
892+scheduleClear r = defer $ Some $ Clear r
866893
867−instance HasSpiderTimeline x => Defer SomeIntClear (EventM x) where
894+instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
868895 {-# INLINE getDeferralQueue #-}
869896 getDeferralQueue = asksEventEnv eventEnvIntClears
870897
871898{-# INLINE scheduleIntClear #-}
872−scheduleIntClear :: Defer SomeIntClear m => IORef (IntMap a) -> m ()
873−scheduleIntClear r = defer $ SomeIntClear r
899+scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
900+scheduleIntClear r = defer $ Some $ IntClear r
874901
875−instance HasSpiderTimeline x => Defer SomeRootClear (EventM x) where
902+instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
876903 {-# INLINE getDeferralQueue #-}
877904 getDeferralQueue = asksEventEnv eventEnvRootClears
878905
879906{-# INLINE scheduleRootClear #-}
880−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
881−scheduleRootClear r = defer $ SomeRootClear r
907+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
908+scheduleRootClear r = defer $ Some $ RootClear r
882909
883910instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
884911 {-# INLINE getDeferralQueue #-}
@@ -933,9 +960,9 @@ getHoldEventSubscription h = do
933960
934961type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
935962
936−--type role BehaviorM representational
937963-- BehaviorM can sample behaviors
938−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
964+newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }
965+ deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))
939966
940967instance Monad (BehaviorM x) where
941968 {-# INLINE (>>=) #-}
@@ -951,7 +978,7 @@ data BehaviorSubscribed x a
951978 = forall p. BehaviorSubscribedHold (Hold x p)
952979 | BehaviorSubscribedPull (PullSubscribed x a)
953980
954−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
981+newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))
955982
956983--type role PullSubscribed representational
957984data PullSubscribed x a
@@ -986,7 +1013,7 @@ data RootSubscribed x a = forall k. GCompare k => RootSubscribed
9861013#endif
9871014 }
9881015
989−data Root x (k :: * -> *)
1016+data Root x k
9901017 = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
9911018 , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
9921019 , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
@@ -1056,25 +1083,25 @@ heightBagVerify b@(HeightBag s c) = if
10561083heightBagVerify = id
10571084#endif
10581085
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)))
1086+data FanSubscribedChildren x k v a = FanSubscribedChildren
1087+ { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))
1088+ , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)
1089+ , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))
10631090 }
10641091
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
1092+data FanSubscribed x k v
1093+ = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
1094+ , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))
1095+ , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty
10691096 , fanSubscribedParent :: !(EventSubscription x)
10701097#ifdef DEBUG_NODEIDS
10711098 , fanSubscribedNodeId :: Int
10721099#endif
10731100 }
10741101
1075−data Fan x k
1076− = Fan { fanParent :: !(Event x (DMap k Identity))
1077− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1102+data Fan x k v
1103+ = Fan { fanParent :: !(Event x (DMap k v))
1104+ , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))
10781105 }
10791106
10801107data SwitchSubscribed x a
@@ -1128,24 +1155,35 @@ newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
11281155newInvalidatorPull :: Pull x a -> IO (Invalidator x)
11291156newInvalidatorPull p = return $! InvalidatorPull p
11301157
1131−instance HasSpiderTimeline x => FunctorMaybe (Event x) where
1132− fmapMaybe f = push $ return . f
1158+instance HasSpiderTimeline x => Filterable (Event x) where
1159+ mapMaybe f = push $ return . f
11331160
11341161instance HasSpiderTimeline x => Align (Event x) where
11351162 nil = eventNever
1136− align ea eb = fmapMaybe dmapToThese $ merge $ dynamicConst $ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1163+#if MIN_VERSION_these(0, 8, 0)
1164+instance HasSpiderTimeline x => Semialign (Event x) where
1165+#endif
1166+ align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $
1167+ DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]
1168+
1169+#ifdef MIN_VERSION_semialign
1170+#if MIN_VERSION_semialign(1,1,0)
1171+instance HasSpiderTimeline x => Zip (Event x) where
1172+#endif
1173+ zip x y = mapMaybe justThese $ align x y
1174+#endif
11371175
11381176data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
11391177 | BuildDyn !(EventM x (PatchTarget p), Event x p)
11401178 | HoldDyn !(Hold x p)
11411179
1142−newtype Dyn x p = Dyn { unDyn :: IORef (DynType x p) }
1180+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
11431181
1144−newMapDyn :: HasSpiderTimeline x => (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1182+newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)
11451183newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
11461184
11471185--TODO: Avoid the duplication between this and R.zipDynWith
1148−zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1186+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)
11491187zipDynWith f da db =
11501188 let eab = align (dynamicUpdated da) (dynamicUpdated db)
11511189 ec = flip push eab $ \o -> do
@@ -1168,18 +1206,12 @@ buildDynamic readV0 v' = do
11681206 return d
11691207
11701208unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1171−unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1172− where x = (readV0, v')
1209+unsafeBuildDynamic readV0 v' =
1210+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
11731211
11741212-- ResultM can read behaviors and events
11751213type ResultM = EventM
11761214
1177−{-# NOINLINE unsafeNewIORef #-}
1178−unsafeNewIORef :: a -> b -> IORef b
1179−unsafeNewIORef a b = unsafePerformIO $ do
1180− touch a
1181− newIORef b
1182−
11831215instance HasSpiderTimeline x => Functor (Event x) where
11841216 fmap f = push $ return . Just . f
11851217
@@ -1192,33 +1224,42 @@ push f e = cacheEvent (pushCheap f e)
11921224
11931225{-# INLINABLE pull #-}
11941226pull :: BehaviorM x a -> Behavior x a
1195−pull a = behaviorPull $ Pull
1196− { pullCompute = a
1197− , pullValue = unsafeNewIORef a Nothing
1227+pull a = unsafePerformIO $ do
1228+ ref <- newIORef Nothing
11981229#ifdef DEBUG_NODEIDS
1199− , pullNodeId = unsafeNodeId a
1230+ nid <- newNodeId
12001231#endif
1201− }
1232+ pure $ behaviorPull $ Pull
1233+ { pullCompute = a
1234+ , pullValue = ref
1235+#ifdef DEBUG_NODEIDS
1236+ , pullNodeId = nid
1237+#endif
1238+ }
12021239
12031240{-# INLINABLE switch #-}
12041241switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1205−switch a = eventSwitch $ Switch
1206− { switchParent = a
1207− , switchSubscribed = unsafeNewIORef a Nothing
1208− }
1242+switch a = unsafePerformIO $ do
1243+ ref <- newIORef Nothing
1244+ pure $ eventSwitch $ Switch
1245+ { switchParent = a
1246+ , switchSubscribed = ref
1247+ }
12091248
12101249coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1211−coincidence a = eventCoincidence $ Coincidence
1212− { coincidenceParent = a
1213− , coincidenceSubscribed = unsafeNewIORef a Nothing
1214− }
1250+coincidence a = unsafePerformIO $ do
1251+ ref <- newIORef Nothing
1252+ pure $ eventCoincidence $ Coincidence
1253+ { coincidenceParent = a
1254+ , coincidenceSubscribed = ref
1255+ }
12151256
12161257-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
12171258run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
12181259run roots after = do
12191260 tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
12201261 let t = spiderTimeline :: SpiderTimelineEnv x
1221− result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1262+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
12221263 rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
12231264 occBefore <- liftIO $ do
12241265 occBefore <- readIORef occRef
@@ -1256,11 +1297,11 @@ scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do
12561297 GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)
12571298 EQ -> a
12581299
1259−data SomeClear = forall a. SomeClear {-# UNPACK #-} !(IORef (Maybe a))
1300+newtype Clear a = Clear (IORef (Maybe a))
12601301
1261−data SomeIntClear = forall a. SomeIntClear {-# UNPACK #-} !(IORef (IntMap a))
1302+newtype IntClear a = IntClear (IORef (IntMap a))
12621303
1263−data SomeRootClear = forall k. SomeRootClear {-# UNPACK #-} !(IORef (DMap k Identity))
1304+newtype RootClear k = RootClear (IORef (DMap k Identity))
12641305
12651306data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
12661307
@@ -1282,9 +1323,9 @@ type WeakList a = [Weak a]
12821323withIncreasedDepth :: CanTrace x m => m a -> m a
12831324withIncreasedDepth a = do
12841325 spiderTimeline <- askSpiderTimelineEnv
1285− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1326+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
12861327 result <- a
1287− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1328+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
12881329 return result
12891330#else
12901331withIncreasedDepth :: m a -> m a
@@ -1311,7 +1352,7 @@ traceMWhen _ b getMessage = when b $ do
13111352 message <- getMessage
13121353#ifdef DEBUG
13131354 spiderTimeline <- askSpiderTimelineEnv
1314− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1355+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
13151356#else
13161357 let d = 0
13171358#endif
@@ -1352,25 +1393,25 @@ propagateSubscriberHold h a = do
13521393data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
13531394
13541395runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1355−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1396+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
13561397
13571398askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
13581399askInvalidator = do
1359− (!m, _) <- BehaviorM ask
1400+ (!m, _) <- ask
13601401 case m of
13611402 Nothing -> return Nothing
13621403 Just (!wi, _) -> return $ Just wi
13631404
13641405askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
13651406askParentsRef = do
1366− (!m, _) <- BehaviorM ask
1407+ (!m, _) <- ask
13671408 case m of
13681409 Nothing -> return Nothing
13691410 Just (_, !p) -> return $ Just p
13701411
13711412askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
13721413askBehaviorHoldInits = do
1373− (_, !his) <- BehaviorM ask
1414+ (_, !his) <- ask
13741415 return his
13751416
13761417{-# INLINE getDynHold #-}
@@ -1415,6 +1456,9 @@ getRootSubscribed k r sub = do
14151456 when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
14161457 uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
14171458 writeIORef uninitRef $! uninit
1459+#ifdef DEBUG_NODEIDS
1460+ nid <- newNodeId
1461+#endif
14181462 let !subscribed = RootSubscribed
14191463 { rootSubscribedKey = k
14201464 , rootSubscribedCachedSubscribed = cached
@@ -1423,7 +1467,7 @@ getRootSubscribed k r sub = do
14231467 , rootSubscribedUninit = uninit
14241468 , rootSubscribedWeakSelf = weakSelf
14251469#ifdef DEBUG_NODEIDS
1426− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1470+ , rootSubscribedNodeId = nid
14271471#endif
14281472 }
14291473 -- If we die at the same moment that all our children die, they will
@@ -1472,16 +1516,10 @@ newFanInt = do
14721516 , _fanInt_occRef = occRef
14731517 }
14741518
1475−{-# NOINLINE unsafeNewFanInt #-}
1476−unsafeNewFanInt :: b -> FanInt x a
1477−unsafeNewFanInt b = unsafePerformIO $ do
1478− touch b
1479− newFanInt
1480−
14811519fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1482−fanInt p =
1483− let self = unsafeNewFanInt p
1484− in EventSelectorInt $ \k -> Event $ \sub -> do
1520+fanInt p = unsafePerformIO $ do
1521+ self <- newFanInt
1522+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
14851523 isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
14861524 when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
14871525 (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
@@ -1489,15 +1527,15 @@ fanInt p =
14891527 liftIO $ writeIORef (_fanInt_occRef self) m
14901528 scheduleIntClear $ _fanInt_occRef self
14911529 FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1492− FastWeakBag.traverse b $ \s -> do
1530+ FastWeakBag.traverse_ b $ \s -> do
14931531 subscriberPropagate s v
14941532 , subscriberInvalidateHeight = \old -> do
14951533 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1496− FastWeakBag.traverse b $ \s -> do
1534+ FastWeakBag.traverse_ b $ \s -> do
14971535 subscriberInvalidateHeight s old
14981536 , subscriberRecalculateHeight = \new -> do
14991537 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1500− FastWeakBag.traverse b $ \s -> do
1538+ FastWeakBag.traverse_ b $ \s -> do
15011539 subscriberRecalculateHeight s new
15021540 }
15031541 liftIO $ do
@@ -1517,7 +1555,7 @@ fanInt p =
15171555 return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
15181556
15191557{-# INLINABLE getFanSubscribed #-}
1520−getFanSubscribed :: (HasSpiderTimeline x, GCompare k) => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a)
1558+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))
15211559getFanSubscribed k f sub = do
15221560 mSubscribed <- liftIO $ readIORef $ fanSubscribed f
15231561 case mSubscribed of
@@ -1535,13 +1573,16 @@ getFanSubscribed k f sub = do
15351573 subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
15361574 occRef <- liftIO $ newIORef parentOcc
15371575 when (isJust parentOcc) $ scheduleClear occRef
1576+#ifdef DEBUG_NODEIDS
1577+ nid <- liftIO newNodeId
1578+#endif
15381579 let subscribed = FanSubscribed
15391580 { fanSubscribedCachedSubscribed = fanSubscribed f
15401581 , fanSubscribedOccurrence = occRef
15411582 , fanSubscribedParent = subscription
15421583 , fanSubscribedSubscribers = subscribersRef
15431584#ifdef DEBUG_NODEIDS
1544− , fanSubscribedNodeId = unsafeNodeId f
1585+ , fanSubscribedNodeId = nid
15451586#endif
15461587 }
15471588 let !self = (k, subscribed)
@@ -1551,7 +1592,7 @@ getFanSubscribed k f sub = do
15511592 liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
15521593 return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
15531594
1554−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1595+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
15551596cleanupFanSubscribed (k, subscribed) = do
15561597 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15571598 let reducedSubscribers = DMap.delete k subscribers
@@ -1563,7 +1604,7 @@ cleanupFanSubscribed (k, subscribed) = do
15631604 else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
15641605
15651606{-# INLINE subscribeFanSubscribed #-}
1566−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1607+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket
15671608subscribeFanSubscribed k subscribed sub = do
15681609 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15691610 case DMap.lookup k subscribers of
@@ -1601,6 +1642,9 @@ getSwitchSubscribed s sub = do
16011642 when (isJust parentOcc) $ scheduleClear occRef
16021643 weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
16031644 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1645+#ifdef DEBUG_NODEIDS
1646+ nid <- liftIO newNodeId
1647+#endif
16041648 let !subscribed = SwitchSubscribed
16051649 { switchSubscribedCachedSubscribed = switchSubscribed s
16061650 , switchSubscribedOccurrence = occRef
@@ -1613,7 +1657,7 @@ getSwitchSubscribed s sub = do
16131657 , switchSubscribedCurrentParent = subscriptionRef
16141658 , switchSubscribedWeakSelf = weakSelf
16151659#ifdef DEBUG_NODEIDS
1616− , switchSubscribedNodeId = unsafeNodeId s
1660+ , switchSubscribedNodeId = nid
16171661#endif
16181662 }
16191663 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
@@ -1658,6 +1702,9 @@ getCoincidenceSubscribed c sub = do
16581702 scheduleClear innerSubdRef
16591703 weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
16601704 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1705+#ifdef DEBUG_NODEIDS
1706+ nid <- liftIO newNodeId
1707+#endif
16611708 let subscribed = CoincidenceSubscribed
16621709 { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
16631710 , coincidenceSubscribedOccurrence = occRef
@@ -1668,7 +1715,7 @@ getCoincidenceSubscribed c sub = do
16681715 , coincidenceSubscribedInnerParent = innerSubdRef
16691716 , coincidenceSubscribedWeakSelf = weakSelf
16701717#ifdef DEBUG_NODEIDS
1671− , coincidenceSubscribedNodeId = unsafeNodeId c
1718+ , coincidenceSubscribedNodeId = nid
16721719#endif
16731720 }
16741721 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
@@ -1685,26 +1732,34 @@ cleanupCoincidenceSubscribed subscribed = do
16851732subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
16861733subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
16871734
1688−{-# INLINE merge #-}
1689−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1690−merge d = cacheEvent (mergeCheap d)
1735+{-# INLINE mergeG #-}
1736+mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)
1737+ => (forall a. q a -> Event x (v a))
1738+ -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)
1739+mergeG nt d = cacheEvent (mergeCheap nt d)
16911740
16921741{-# INLINE mergeWithMove #-}
1693−mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1694−mergeWithMove d = cacheEvent (mergeCheapWithMove d)
1742+mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)
1743+ => (forall a. q a -> Event x (v a))
1744+ -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)
1745+mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)
16951746
16961747{-# INLINE [1] mergeCheap #-}
1697−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1698−mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
1748+mergeCheap
1749+ :: forall k x q v. (HasSpiderTimeline x, GCompare k)
1750+ => (forall a. q a -> Event x (v a))
1751+ -> DynamicS x (PatchDMap k q)
1752+ -> Event x (DMap k v)
1753+mergeCheap nt = mergeGCheap' getInitialSubscribers updateMe destroy
16991754 where
1700− updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1755+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
17011756 updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
17021757 let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
17031758 (mOldSubd, newPs) <- case me of
17041759 Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
17051760 Just e -> do
17061761 let s = subscriber $ return k
1707− subscription@(EventSubscription _ subd) <- subscribe e s
1762+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
17081763 newParentHeight <- liftIO $ getEventSubscribedHeight subd
17091764 let newParent = MergeSubscribedParent subscription
17101765 liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
@@ -1714,28 +1769,33 @@ mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
17141769 liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
17151770 return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
17161771 foldM f ([], oldParents) $ DMap.toList p
1717− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1772+
1773+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
17181774 getInitialSubscribers initialParents subscriber = do
17191775 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17201776 let s = subscriber $ return k
1721− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1777+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17221778 height <- liftIO $ getEventSubscribedHeight parentSubd
1723− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1779+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
17241780 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17251781 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17261782 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17271783 )
1784+
17281785 destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
17291786 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
17301787
17311788{-# INLINE [1] mergeCheapWithMove #-}
1732−mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1733−mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
1789+mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)
1790+ => (forall a. q a -> Event x (v a))
1791+ -> DynamicS x (PatchDMapWithMove k q)
1792+ -> Event x (DMap k v)
1793+mergeCheapWithMove nt = mergeGCheap' getInitialSubscribers updateMe destroy
17341794 where
1735− updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1795+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
17361796 updateMe subscriber heightBagRef oldParents p = do
17371797 -- Prepare new parents for insertion
1738− let subscribeParent :: forall a. k a -> Event x a -> EventM x (MergeSubscribedParentWithMove x k a)
1798+ let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)
17391799 subscribeParent k e = do
17401800 keyRef <- liftIO $ newIORef k
17411801 let s = subscriber $ liftIO $ readIORef keyRef
@@ -1744,9 +1804,9 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17441804 newParentHeight <- getEventSubscribedHeight subd
17451805 modifyIORef' heightBagRef $ heightBagAdd newParentHeight
17461806 return $ MergeSubscribedParentWithMove subscription keyRef
1747− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1807+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
17481808 -- Collect old parents for deletion and update the keys of moved parents
1749− let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k (Event x) a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
1809+ let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a
17501810 moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
17511811 Nothing -> do
17521812 oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
@@ -1757,46 +1817,47 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17571817 return Nothing
17581818 toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
17591819 return (toDelete, applyAlways p' oldParents)
1760− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1820+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
17611821 getInitialSubscribers initialParents subscriber = do
17621822 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17631823 keyRef <- liftIO $ newIORef k
17641824 let s = subscriber $ liftIO $ readIORef keyRef
1765− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1825+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17661826 height <- liftIO $ getEventSubscribedHeight parentSubd
1767− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1827+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
17681828 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17691829 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17701830 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17711831 )
1832+
17721833 destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
17731834 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
17741835
1775−type MergeUpdateFunc k x p s
1776− = (forall a. EventM x (k a) -> Subscriber x a)
1836+type MergeUpdateFunc k v x p s
1837+ = (forall a. EventM x (k a) -> Subscriber x (v a))
17771838 -> IORef HeightBag
17781839 -> DMap k s
17791840 -> p
17801841 -> EventM x ([EventSubscription x], DMap k s)
17811842
1782−type MergeInitFunc k x s
1783− = DMap k (Event x)
1784− -> (forall a. EventM x (k a) -> Subscriber x a)
1785− -> EventM x (DMap k Identity, [Height], DMap k s)
1843+type MergeInitFunc k v q x s
1844+ = DMap k q
1845+ -> (forall a. EventM x (k a) -> Subscriber x (v a))
1846+ -> EventM x (DMap k v, [Height], DMap k s)
17861847
17871848type MergeDestroyFunc k s
17881849 = DMap k s
17891850 -> IO ()
17901851
1791−data Merge x k s = Merge
1852+data Merge x k v s = Merge
17921853 { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
17931854 , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
17941855 , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1795− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1796− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1856+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1857+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
17971858 }
17981859
1799−invalidateMergeHeight :: Merge x k s -> IO ()
1860+invalidateMergeHeight :: Merge x k v s -> IO ()
18001861invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
18011862
18021863invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
@@ -1806,8 +1867,7 @@ invalidateMergeHeight' heightRef sub = do
18061867 writeIORef heightRef $! invalidHeight
18071868 subscriberInvalidateHeight sub oldHeight
18081869
1809−
1810−revalidateMergeHeight :: Merge x k s -> IO ()
1870+revalidateMergeHeight :: Merge x k v s -> IO ()
18111871revalidateMergeHeight m = do
18121872 currentHeight <- readIORef $ _merge_heightRef m
18131873 when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
@@ -1823,19 +1883,19 @@ revalidateMergeHeight m = do
18231883 subscriberRecalculateHeight (_merge_sub m) height
18241884 GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
18251885
1826−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1886+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
18271887scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
18281888 vals <- liftIO $ readIORef $ _merge_accumRef m
18291889 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
18301890 --TODO: Assert that m is not empty
18311891 subscriberPropagate (_merge_sub m) vals
18321892
1833−mergeSubscriber :: forall x k s a. (HasSpiderTimeline x, GCompare k) => Merge x k s -> EventM x (k a) -> Subscriber x a
1893+mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => Merge x k v s -> EventM x (k a) -> Subscriber x (v a)
18341894mergeSubscriber m getKey = Subscriber
18351895 { subscriberPropagate = \a -> do
18361896 oldM <- liftIO $ readIORef $ _merge_accumRef m
18371897 k <- getKey
1838− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k (Identity a) oldM
1898+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge") k a oldM
18391899 tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
18401900 liftIO $ writeIORef (_merge_accumRef m) $! newM
18411901 when (DMap.null oldM) $ do -- Only schedule the firing once
@@ -1850,7 +1910,7 @@ mergeSubscriber m getKey = Subscriber
18501910 else liftIO $ do
18511911#ifdef DEBUG_CYCLES
18521912 nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1853− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1913+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
18541914 let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
18551915#else
18561916 let cycleInfo = ""
@@ -1866,7 +1926,7 @@ mergeSubscriber m getKey = Subscriber
18661926 }
18671927
18681928--TODO: Be able to run as much of this as possible promptly
1869−updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k s -> MergeUpdateFunc k x p s -> p -> SomeMergeUpdate x
1929+updateMerge :: (HasSpiderTimeline x, GCompare k) => Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x
18701930updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
18711931 where updateMe = do
18721932 oldParents <- liftIO $ readIORef $ _merge_parentsRef m
@@ -1874,9 +1934,10 @@ updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m)
18741934 liftIO $ writeIORef (_merge_parentsRef m) $! newParents
18751935 return subscriptionsToKill
18761936
1877−{-# INLINE mergeCheap' #-}
1878−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)
1879−mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
1937+{-# INLINE mergeGCheap' #-}
1938+mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)
1939+ => MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)
1940+mergeGCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
18801941 initialParents <- readBehaviorUntracked $ dynamicCurrent d
18811942 accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
18821943 heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
@@ -1924,11 +1985,11 @@ mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
19241985 , occ
19251986 )
19261987
1927−mergeInt :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1988+mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
19281989mergeInt = cacheEvent . mergeIntCheap
19291990
19301991{-# INLINABLE mergeIntCheap #-}
1931−mergeIntCheap :: forall x a. (HasSpiderTimeline x) => Dynamic x (PatchIntMap (Event x a)) -> Event x (IntMap a)
1992+mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
19321993mergeIntCheap d = Event $ \sub -> do
19331994 initialParents <- readBehaviorUntracked $ dynamicCurrent d
19341995 accum <- liftIO $ FastMutableIntMap.newEmpty
@@ -2025,14 +2086,16 @@ mergeIntCheap d = Event $ \sub -> do
20252086 )
20262087
20272088newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
2089+newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }
20282090
2029−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2030−fan e =
2091+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v
2092+fanG e = unsafePerformIO $ do
2093+ ref <- newIORef Nothing
20312094 let f = Fan
20322095 { fanParent = e
2033− , fanSubscribed = unsafeNewIORef e Nothing
2096+ , fanSubscribed = ref
20342097 }
2035− in EventSelector $ \k -> eventFan k f
2098+ pure $ EventSelectorG $ \k -> eventFan k f
20362099
20372100runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
20382101runHoldInits holdInitRef dynInitRef mergeInitRef = do
@@ -2086,18 +2149,18 @@ clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeI
20862149-- | Run an event action outside of a frame
20872150runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
20882151runFrame a = SpiderHost $ do
2089− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2152+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
20902153 let go = do
20912154 result <- a
20922155 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
20932156 return result
20942157 result <- runEventM go
20952158 toClear <- readIORef $ eventEnvClears env
2096− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
2159+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
20972160 toClearInt <- readIORef $ eventEnvIntClears env
2098− forM_ toClearInt $ \(SomeIntClear ref) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2161+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
20992162 toClearRoot <- readIORef $ eventEnvRootClears env
2100− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2163+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
21012164 toAssign <- readIORef $ eventEnvAssignments env
21022165 toReconnectRef <- newIORef []
21032166 coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
@@ -2144,7 +2207,7 @@ runFrame a = SpiderHost $ do
21442207 myHeight <- readIORef $ switchSubscribedHeight subscribed
21452208 when (parentHeight /= myHeight) $ do
21462209 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2147− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2210+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
21482211 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
21492212 forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
21502213 unsubscribe subscription
@@ -2185,7 +2248,7 @@ invalidateCoincidenceHeight subscribed = do
21852248 oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
21862249 when (oldHeight /= invalidHeight) $ do
21872250 writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2188− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2251+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
21892252
21902253updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
21912254updateSwitchHeight new subscribed = do
@@ -2193,7 +2256,7 @@ updateSwitchHeight new subscribed = do
21932256 when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21942257 when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21952258 writeIORef (switchSubscribedHeight subscribed) $! new
2196− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2259+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
21972260
21982261recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
21992262recalculateCoincidenceHeight subscribed = do
@@ -2202,7 +2265,7 @@ recalculateCoincidenceHeight subscribed = do
22022265 height <- calculateCoincidenceHeight subscribed
22032266 when (height /= invalidHeight) $ do
22042267 writeIORef (coincidenceSubscribedHeight subscribed) $! height
2205− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2268+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
22062269
22072270calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
22082271calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
@@ -2297,7 +2360,7 @@ instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x))
22972360 fail _ = error "Dynamic does not support 'fail'"
22982361
22992362{-# INLINABLE newJoinDyn #-}
2300−newJoinDyn :: HasSpiderTimeline x => Reflex.Spider.Internal.Dynamic x (Identity (Reflex.Spider.Internal.Dynamic x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
2363+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)
23012364newJoinDyn d =
23022365 let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
23032366 eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
@@ -2307,9 +2370,13 @@ newJoinDyn d =
23072370 in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'
23082371
23092372instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where
2310− fmap f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2373+ fmap = mapDynamicSpider
23112374 x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d
23122375
2376+mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b
2377+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic
2378+{-# INLINE [1] mapDynamicSpider #-}
2379+
23132380instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where
23142381 pure = SpiderDynamic . dynamicConst
23152382#if MIN_VERSION_base(4,10,0)
@@ -2443,7 +2510,7 @@ unsafeNewSpiderTimelineEnv = do
24432510#ifdef DEBUG
24442511 depthRef <- newIORef 0
24452512#endif
2446− return $ SpiderTimelineEnv
2513+ return $ STE $ SpiderTimelineEnv
24472514 { _spiderTimeline_lock = lock
24482515 , _spiderTimeline_eventEnv = env
24492516#ifdef DEBUG
@@ -2453,19 +2520,19 @@ unsafeNewSpiderTimelineEnv = do
24532520
24542521-- | Create a new SpiderTimelineEnv
24552522newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2456−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2523+newSpiderTimeline = withSpiderTimeline (pure . Some)
24572524
2458−data LocalSpiderTimeline x s
2525+data LocalSpiderTimeline (x :: Type) s
24592526
24602527instance Reifies s (SpiderTimelineEnv x) =>
24612528 HasSpiderTimeline (LocalSpiderTimeline x s) where
2462− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2529+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
24632530
24642531localSpiderTimeline
2465− :: Proxy s
2532+ :: proxy s
24662533 -> SpiderTimelineEnv x
24672534 -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2468−localSpiderTimeline _ = unsafeCoerce
2535+localSpiderTimeline _ = coerce
24692536
24702537-- | Pass a new timeline to the given function.
24712538withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
@@ -2473,18 +2540,18 @@ withSpiderTimeline k = do
24732540 env <- unsafeNewSpiderTimelineEnv
24742541 reify env $ \s -> k $ localSpiderTimeline s env
24752542
2476−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2543+newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
24772544
24782545type ComputeM = EventM
24792546
2480−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2547+newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
24812548
24822549instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
24832550 {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
24842551 newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
24852552 newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2486− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2487− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
2553+ newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)
2554+ newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }
24882555 type PullM (SpiderTimeline x) = SpiderPullM x
24892556 type PushM (SpiderTimeline x) = SpiderPushM x
24902557 {-# INLINABLE never #-}
@@ -2497,10 +2564,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
24972564 pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
24982565 {-# INLINABLE pull #-}
24992566 pull = SpiderBehavior . pull . coerce
2500− {-# INLINABLE merge #-}
2501− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2502− {-# INLINABLE fan #-}
2503− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2567+ {-# INLINABLE fanG #-}
2568+ fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))
2569+ {-# INLINABLE mergeG #-}
2570+ mergeG
2571+ :: forall (k :: k2 -> *) q (v :: k2 -> *). GCompare k
2572+ => (forall a. q a -> R.Event (SpiderTimeline x) (v a))
2573+ -> DMap k q
2574+ -> R.Event (SpiderTimeline x) (DMap k v)
2575+ mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst
25042576 {-# INLINABLE switch #-}
25052577 switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
25062578 {-# INLINABLE coincidence #-}
@@ -2508,15 +2580,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25082580 {-# INLINABLE current #-}
25092581 current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
25102582 {-# INLINABLE updated #-}
2511− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2583+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
25122584 {-# INLINABLE unsafeBuildDynamic #-}
25132585 unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
25142586 {-# INLINABLE unsafeBuildIncremental #-}
25152587 unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2516− {-# INLINABLE mergeIncremental #-}
2517− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2518− {-# INLINABLE mergeIncrementalWithMove #-}
2519− mergeIncrementalWithMove = SpiderEvent . mergeWithMove . (unsafeCoerce :: Dynamic x (PatchDMapWithMove k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMapWithMove k (Event x))) . unSpiderIncremental
2588+ {-# INLINABLE mergeIncrementalG #-}
2589+ mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental
2590+ {-# INLINABLE mergeIncrementalWithMoveG #-}
2591+ mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental
25202592 {-# INLINABLE currentIncremental #-}
25212593 currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
25222594 {-# INLINABLE updatedIncremental #-}
@@ -2527,9 +2599,10 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25272599 return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
25282600 eventCoercion Coercion = Coercion
25292601 behaviorCoercion Coercion = Coercion
2530− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2602+ dynamicCoercion Coercion = Coercion
2603+ incrementalCoercion Coercion Coercion = Coercion
25312604 {-# INLINABLE mergeIntIncremental #-}
2532− mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2605+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
25332606 {-# INLINABLE fanInt #-}
25342607 fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
25352608
@@ -2554,7 +2627,7 @@ instance MonadAtomicRef (EventM x) where
25542627 atomicModifyRef r f = liftIO $ atomicModifyRef r f
25552628
25562629-- | The monad for actions that manipulate a Spider timeline identified by @x@
2557−newtype SpiderHost x a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2630+newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
25582631
25592632instance Monad (SpiderHost x) where
25602633 {-# INLINABLE (>>=) #-}
@@ -2576,7 +2649,7 @@ runSpiderHost (SpiderHost a) = a
25762649runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
25772650runSpiderHostForTimeline (SpiderHost a) _ = a
25782651
2579−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2652+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
25802653 deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
25812654
25822655instance Monad (SpiderHostFrame x) where