@@ -16,9 +16,15 @@
1616{-# LANGUAGE TypeFamilies #-}
1717{-# LANGUAGE TypeOperators #-}
1818{-# LANGUAGE UndecidableInstances #-}
19+{-# LANGUAGE PolyKinds #-}
20+{-# LANGUAGE DeriveFunctor #-}
21+{-# LANGUAGE StandaloneDeriving #-}
22+{-# LANGUAGE InstanceSigs #-}
23+
1924#ifdef USE_REFLEX_OPTIMIZER
2025{-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-}
2126#endif
27+{-# OPTIONS_GHC -Wunused-binds #-}
2228-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
2329-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
2430module Reflex.Spider.Internal (module Reflex.Spider.Internal) where
@@ -32,7 +38,10 @@ import Control.Monad hiding (forM, forM_, mapM, mapM_)
3238import Control.Monad.Exception
3339import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)
3440import Control.Monad.Primitive
35−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
3645import Control.Monad.Ref
3746import Data.Align
3847import Data.Coerce
@@ -48,6 +57,7 @@ import Data.GADT.Compare
4857import Data.IntMap.Strict (IntMap)
4958import qualified Data.IntMap.Strict as IntMap
5059import Data.IORef
60+import Data.Kind (Type)
5161import Data.Maybe hiding (mapMaybe)
5262import Data.Monoid ((<>))
5363import Data.Proxy
@@ -62,6 +72,15 @@ import System.IO.Unsafe
6272import System.Mem.Weak
6373import Unsafe.Coerce
6474
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+
6584#ifdef DEBUG_CYCLES
6685import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
6786import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
@@ -73,9 +92,9 @@ import Data.Tree (Forest, Tree (..), drawForest)
7392import Data.FastWeakBag (FastWeakBag)
7493import qualified Data.FastWeakBag as FastWeakBag
7594import Data.Reflection
76−import Data.Some (Some)
77−import qualified Data.Some as Some
95+import Data.Some (Some(Some))
7896import Data.Type.Coercion
97+import Data.Profunctor.Unsafe ((#.), (.#))
7998import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)
8099import qualified Data.WeakBag as WeakBag
81100import qualified Reflex.Class
@@ -84,6 +103,7 @@ import qualified Reflex.Host.Class
84103import Reflex.NotReady.Class
85104import Reflex.Patch
86105import qualified Reflex.Patch.DMapWithMove as PatchDMapWithMove
106+import Reflex.PerformEvent.Base (PerformEventT)
87107
88108#ifdef DEBUG_TRACE_EVENTS
89109import qualified Data.ByteString.Char8 as BS8
@@ -192,12 +212,6 @@ nextNodeIdRef = unsafePerformIO $ newIORef 1
192212
193213newNodeId :: IO Int
194214newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
195−
196−{-# NOINLINE unsafeNodeId #-}
197−unsafeNodeId :: a -> Int
198−unsafeNodeId a = unsafePerformIO $ do
199− touch a
200− newNodeId
201215#endif
202216
203217--------------------------------------------------------------------------------
@@ -301,9 +315,10 @@ cacheEvent e =
301315#else
302316 Event $
303317#endif
304− let mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
305− !mSubscribedRef = unsafeNewIORef e emptyFastWeak
306− in \sub -> {-# SCC "cacheEvent" #-} do
318+ unsafePerformIO $ do
319+ mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))
320+ <- newIORef emptyFastWeak
321+ pure $ \sub -> {-# SCC "cacheEvent" #-} do
307322#ifdef DEBUG_TRACE_EVENTS
308323 unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite
309324#endif
@@ -318,9 +333,9 @@ cacheEvent e =
318333 scheduleClear occRef
319334 propagateFast a subscribers
320335 , subscriberInvalidateHeight = \old -> do
321− FastWeakBag.traverse subscribers $ invalidateSubscriberHeight old
336+ FastWeakBag.traverse_ subscribers $ invalidateSubscriberHeight old
322337 , subscriberRecalculateHeight = \new -> do
323− FastWeakBag.traverse subscribers $ recalculateSubscriberHeight new
338+ FastWeakBag.traverse_ subscribers $ recalculateSubscriberHeight new
324339 }
325340 when (isJust occ) $ do
326341 liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing
@@ -369,7 +384,7 @@ eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed
369384eventNever :: Event x a
370385eventNever = Event $ \_ -> return (EventSubscription (return ()) eventSubscribedNever, Nothing)
371386
372−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)
373388eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
374389
375390eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
@@ -421,14 +436,14 @@ newSubscriberHold h = return $ Subscriber
421436 , subscriberRecalculateHeight = \_ -> return ()
422437 }
423438
424−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))
425440newSubscriberFan subscribed = return $ Subscriber
426441 { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
427442 subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
428443 tracePropagate (Proxy :: Proxy x) $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
429444 liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
430445 scheduleClear $ fanSubscribedOccurrence subscribed
431− let f _ (Pair (Identity v) subsubs) = do
446+ let f _ (Pair v subsubs) = do
432447 propagate v $ _fanSubscribedChildren_list subsubs
433448 return $ Constant ()
434449 _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
@@ -436,12 +451,12 @@ newSubscriberFan subscribed = return $ Subscriber
436451 , subscriberInvalidateHeight = \old -> do
437452 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
438453 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
439− 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
440455 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
441456 , subscriberRecalculateHeight = \new -> do
442457 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
443458 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
444− 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
445460 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
446461 }
447462
@@ -457,7 +472,7 @@ newSubscriberSwitch subscribed = return $ Subscriber
457472 oldHeight <- readIORef $ switchSubscribedHeight subscribed
458473 when (oldHeight /= invalidHeight) $ do
459474 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
460− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
475+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
461476 when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
462477 , subscriberRecalculateHeight = \new -> do
463478 when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
@@ -480,8 +495,8 @@ newSubscriberCoincidenceOuter subscribed = return $ Subscriber
480495 Nothing -> do
481496 when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
482497 writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
483− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
484− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
498+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
499+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
485500 Just o -> do -- Since it's already firing, no need to adjust height
486501 liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
487502 scheduleClear $ coincidenceSubscribedOccurrence subscribed
@@ -528,14 +543,14 @@ propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
528543propagate a subscribers = withIncreasedDepth $ do
529544 -- 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
530545 --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
531− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
546+ WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
532547
533548-- | Propagate everything at the current height
534549propagateFast :: a -> FastWeakBag (Subscriber x a) -> EventM x ()
535550propagateFast a subscribers = withIncreasedDepth $ do
536551 -- 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
537552 --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
538− FastWeakBag.traverse subscribers $ \s -> subscriberPropagate s a
553+ FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a
539554
540555--------------------------------------------------------------------------------
541556-- EventSubscribed
@@ -544,6 +559,11 @@ propagateFast a subscribers = withIncreasedDepth $ do
544559toAny :: a -> Any
545560toAny = unsafeCoerce
546561
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.
547567data EventSubscribed x = EventSubscribed
548568 { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
549569 , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
@@ -576,12 +596,12 @@ eventSubscribedNever = EventSubscribed
576596#endif
577597 }
578598
579−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
599+eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x
580600eventSubscribedFan !subscribed = EventSubscribed
581601 { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
582602 , eventSubscribedRetained = toAny subscribed
583603#ifdef DEBUG_CYCLES
584− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
604+ , eventSubscribedGetParents = return [Some $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
585605 , eventSubscribedHasOwnHeightRef = False
586606 , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
587607#endif
@@ -594,7 +614,7 @@ eventSubscribedSwitch !subscribed = EventSubscribed
594614#ifdef DEBUG_CYCLES
595615 , eventSubscribedGetParents = do
596616 s <- readIORef $ switchSubscribedCurrentParent subscribed
597− return [Some.This $ _eventSubscription_subscribed s]
617+ return [Some $ _eventSubscription_subscribed s]
598618 , eventSubscribedHasOwnHeightRef = True
599619 , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
600620#endif
@@ -607,8 +627,8 @@ eventSubscribedCoincidence !subscribed = EventSubscribed
607627#ifdef DEBUG_CYCLES
608628 , eventSubscribedGetParents = do
609629 innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
610− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
611− innerParents = maybeToList $ fmap Some.This innerSubscription
630+ let outerParent = Some $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
631+ innerParents = maybeToList $ fmap Some innerSubscription
612632 return $ outerParent : innerParents
613633 , eventSubscribedHasOwnHeightRef = True
614634 , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
@@ -624,13 +644,13 @@ whoCreatedEventSubscribed = eventSubscribedWhoCreated
624644
625645walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
626646walkInvalidHeightParents s0 = do
627− 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
628648 h <- liftIO $ readIORef $ eventSubscribedHeightRef s
629649 when (h == invalidHeight) $ do
630650 when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
631− modify (Some.This s :)
651+ modify (Some s :)
632652 mapM_ loop =<< liftIO (eventSubscribedGetParents s)
633− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
653+ forM_ subscribers $ \(Some s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
634654 return subscribers
635655#endif
636656
@@ -658,7 +678,7 @@ behaviorPull !p = Behavior $ do
658678 val <- liftIO $ readIORef $ pullValue p
659679 case val of
660680 Just subscribed -> do
661− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedPull subscribed)) :))
681+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
662682 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
663683 liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
664684 return $ pullSubscribedValue subscribed
@@ -667,7 +687,7 @@ behaviorPull !p = Behavior $ do
667687 wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
668688 parentsRef <- liftIO $ newIORef []
669689 holdInits <- askBehaviorHoldInits
670− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
690+ a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
671691 invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
672692 parents <- liftIO $ readIORef parentsRef
673693 let subscribed = PullSubscribed
@@ -677,7 +697,7 @@ behaviorPull !p = Behavior $ do
677697 , pullSubscribedParents = parents
678698 }
679699 liftIO $ writeIORef (pullValue p) $ Just subscribed
680− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedPull subscribed)) :))
700+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))
681701 return a
682702
683703behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)
@@ -688,7 +708,7 @@ readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)
688708readHoldTracked h = do
689709 result <- liftIO $ readIORef $ holdValue h
690710 askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
691− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some.This (BehaviorSubscribedHold h)) :))
711+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))
692712 liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected
693713 return result
694714
@@ -702,42 +722,46 @@ readBehaviorUntracked b = do
702722-- Dynamic
703723--------------------------------------------------------------------------------
704724
705−data Dynamic x p = Dynamic
706− { 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)
707729 , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?
708730 }
709731
710−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
711738dynamicHold !h = Dynamic
712739 { dynamicCurrent = behaviorHold h
713740 , dynamicUpdated = eventHold h
714741 }
715742
716−dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
743+dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)
717744dynamicHoldIdentity = dynamicHold
718745
719−dynamicConst :: PatchTarget p -> Dynamic x p
746+dynamicConst :: PatchTarget p -> DynamicS x p
720747dynamicConst !a = Dynamic
721748 { dynamicCurrent = behaviorConst a
722749 , dynamicUpdated = eventNever
723750 }
724751
725−dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Dynamic x p
752+dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p
726753dynamicDyn !d = Dynamic
727754 { dynamicCurrent = behaviorDyn d
728755 , dynamicUpdated = eventDyn d
729756 }
730757
731−dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> Dynamic x (Identity a)
758+dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
732759dynamicDynIdentity = dynamicDyn
733760
734761--------------------------------------------------------------------------------
735762-- Combinators
736763--------------------------------------------------------------------------------
737764
738−--TODO: Figure out why certain things are not 'representational', then make them
739−--representational so we can use coerce
740−
741765--type role Hold representational
742766data Hold x p
743767 = Hold { holdValue :: !(IORef (PatchTarget p))
@@ -758,20 +782,25 @@ globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv
758782
759783-- | Stores all global data relevant to a particular Spider timeline; only one
760784-- value should exist for each type @x@
761−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
762791 { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())
763792 , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)
764793#ifdef DEBUG
765794 , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)
766795#endif
767796 }
768−type role SpiderTimelineEnv nominal
797+type role SpiderTimelineEnv' phantom
769798
770799instance Eq (SpiderTimelineEnv x) where
771800 _ == _ = True -- Since only one exists of each type
772801
773802instance GEq SpiderTimelineEnv where
774− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
803+ a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)
775804 then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments
776805 else Nothing
777806
@@ -794,7 +823,7 @@ runEventM :: EventM x a -> IO a
794823runEventM = unEventM
795824
796825asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a
797−asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
826+asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))
798827
799828class MonadIO m => Defer a m where
800829 getDeferralQueue :: m (IORef [a])
@@ -861,7 +890,7 @@ instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where
861890
862891{-# INLINE scheduleClear #-}
863892scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()
864−scheduleClear r = defer $ Some.This $ Clear r
893+scheduleClear r = defer $ Some $ Clear r
865894
866895instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
867896 {-# INLINE getDeferralQueue #-}
@@ -869,7 +898,7 @@ instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where
869898
870899{-# INLINE scheduleIntClear #-}
871900scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
872−scheduleIntClear r = defer $ Some.This $ IntClear r
901+scheduleIntClear r = defer $ Some $ IntClear r
873902
874903instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
875904 {-# INLINE getDeferralQueue #-}
@@ -877,7 +906,7 @@ instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where
877906
878907{-# INLINE scheduleRootClear #-}
879908scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()
880−scheduleRootClear r = defer $ Some.This $ RootClear r
909+scheduleRootClear r = defer $ Some $ RootClear r
881910
882911instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where
883912 {-# INLINE getDeferralQueue #-}
@@ -932,9 +961,9 @@ getHoldEventSubscription h = do
932961
933962type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
934963
935−--type role BehaviorM representational
936964-- BehaviorM can sample behaviors
937−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))
938967
939968instance Monad (BehaviorM x) where
940969 {-# INLINE (>>=) #-}
@@ -985,7 +1014,7 @@ data RootSubscribed x a = forall k. GCompare k => RootSubscribed
9851014#endif
9861015 }
9871016
988−data Root x (k :: * -> *)
1017+data Root x k
9891018 = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
9901019 , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
9911020 , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
@@ -1055,25 +1084,25 @@ heightBagVerify b@(HeightBag s c) = if
10551084heightBagVerify = id
10561085#endif
10571086
1058−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1059− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1060− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1061− , _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)))
10621091 }
10631092
1064−data FanSubscribed (x :: *) k
1065− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1066− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1067− , 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
10681097 , fanSubscribedParent :: !(EventSubscription x)
10691098#ifdef DEBUG_NODEIDS
10701099 , fanSubscribedNodeId :: Int
10711100#endif
10721101 }
10731102
1074−data Fan x k
1075− = Fan { fanParent :: !(Event x (DMap k Identity))
1076− , 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)))
10771106 }
10781107
10791108data SwitchSubscribed x a
@@ -1135,19 +1164,27 @@ instance HasSpiderTimeline x => Align (Event x) where
11351164#if MIN_VERSION_these(0, 8, 0)
11361165instance HasSpiderTimeline x => Semialign (Event x) where
11371166#endif
1138− 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
11391176
11401177data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)
11411178 | BuildDyn !(EventM x (PatchTarget p), Event x p)
11421179 | HoldDyn !(Hold x p)
11431180
1144−newtype Dyn x p = Dyn { unDyn :: IORef (DynType x p) }
1181+newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }
11451182
1146−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)
11471184newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
11481185
11491186--TODO: Avoid the duplication between this and R.zipDynWith
1150−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)
11511188zipDynWith f da db =
11521189 let eab = align (dynamicUpdated da) (dynamicUpdated db)
11531190 ec = flip push eab $ \o -> do
@@ -1170,18 +1207,12 @@ buildDynamic readV0 v' = do
11701207 return d
11711208
11721209unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p
1173−unsafeBuildDynamic readV0 v' = Dyn $ unsafeNewIORef x $ UnsafeDyn x
1174− where x = (readV0, v')
1210+unsafeBuildDynamic readV0 v' =
1211+ Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')
11751212
11761213-- ResultM can read behaviors and events
11771214type ResultM = EventM
11781215
1179−{-# NOINLINE unsafeNewIORef #-}
1180−unsafeNewIORef :: a -> b -> IORef b
1181−unsafeNewIORef a b = unsafePerformIO $ do
1182− touch a
1183− newIORef b
1184−
11851216instance HasSpiderTimeline x => Functor (Event x) where
11861217 fmap f = push $ return . Just . f
11871218
@@ -1194,33 +1225,42 @@ push f e = cacheEvent (pushCheap f e)
11941225
11951226{-# INLINABLE pull #-}
11961227pull :: BehaviorM x a -> Behavior x a
1197−pull a = behaviorPull $ Pull
1198− { pullCompute = a
1199− , pullValue = unsafeNewIORef a Nothing
1228+pull a = unsafePerformIO $ do
1229+ ref <- newIORef Nothing
12001230#ifdef DEBUG_NODEIDS
1201− , pullNodeId = unsafeNodeId a
1231+ nid <- newNodeId
12021232#endif
1203− }
1233+ pure $ behaviorPull $ Pull
1234+ { pullCompute = a
1235+ , pullValue = ref
1236+#ifdef DEBUG_NODEIDS
1237+ , pullNodeId = nid
1238+#endif
1239+ }
12041240
12051241{-# INLINABLE switch #-}
12061242switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
1207−switch a = eventSwitch $ Switch
1208− { switchParent = a
1209− , switchSubscribed = unsafeNewIORef a Nothing
1210− }
1243+switch a = unsafePerformIO $ do
1244+ ref <- newIORef Nothing
1245+ pure $ eventSwitch $ Switch
1246+ { switchParent = a
1247+ , switchSubscribed = ref
1248+ }
12111249
12121250coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
1213−coincidence a = eventCoincidence $ Coincidence
1214− { coincidenceParent = a
1215− , coincidenceSubscribed = unsafeNewIORef a Nothing
1216− }
1251+coincidence a = unsafePerformIO $ do
1252+ ref <- newIORef Nothing
1253+ pure $ eventCoincidence $ Coincidence
1254+ { coincidenceParent = a
1255+ , coincidenceSubscribed = ref
1256+ }
12171257
12181258-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
12191259run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
12201260run roots after = do
12211261 tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"
12221262 let t = spiderTimeline :: SpiderTimelineEnv x
1223− result <- SpiderHost $ withMVar (_spiderTimeline_lock t) $ \_ -> unSpiderHost $ runFrame $ do
1263+ result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do
12241264 rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
12251265 occBefore <- liftIO $ do
12261266 occBefore <- readIORef occRef
@@ -1284,9 +1324,9 @@ type WeakList a = [Weak a]
12841324withIncreasedDepth :: CanTrace x m => m a -> m a
12851325withIncreasedDepth a = do
12861326 spiderTimeline <- askSpiderTimelineEnv
1287− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1327+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) succ
12881328 result <- a
1289− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1329+ liftIO $ modifyIORef' (_spiderTimeline_depth (unSTE spiderTimeline)) pred
12901330 return result
12911331#else
12921332withIncreasedDepth :: m a -> m a
@@ -1313,7 +1353,7 @@ traceMWhen _ b getMessage = when b $ do
13131353 message <- getMessage
13141354#ifdef DEBUG
13151355 spiderTimeline <- askSpiderTimelineEnv
1316− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1356+ d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE spiderTimeline
13171357#else
13181358 let d = 0
13191359#endif
@@ -1354,25 +1394,25 @@ propagateSubscriberHold h a = do
13541394data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
13551395
13561396runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1357−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1397+runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)
13581398
13591399askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
13601400askInvalidator = do
1361− (!m, _) <- BehaviorM ask
1401+ (!m, _) <- ask
13621402 case m of
13631403 Nothing -> return Nothing
13641404 Just (!wi, _) -> return $ Just wi
13651405
13661406askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
13671407askParentsRef = do
1368− (!m, _) <- BehaviorM ask
1408+ (!m, _) <- ask
13691409 case m of
13701410 Nothing -> return Nothing
13711411 Just (_, !p) -> return $ Just p
13721412
13731413askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
13741414askBehaviorHoldInits = do
1375− (_, !his) <- BehaviorM ask
1415+ (_, !his) <- ask
13761416 return his
13771417
13781418{-# INLINE getDynHold #-}
@@ -1417,6 +1457,9 @@ getRootSubscribed k r sub = do
14171457 when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
14181458 uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
14191459 writeIORef uninitRef $! uninit
1460+#ifdef DEBUG_NODEIDS
1461+ nid <- newNodeId
1462+#endif
14201463 let !subscribed = RootSubscribed
14211464 { rootSubscribedKey = k
14221465 , rootSubscribedCachedSubscribed = cached
@@ -1425,7 +1468,7 @@ getRootSubscribed k r sub = do
14251468 , rootSubscribedUninit = uninit
14261469 , rootSubscribedWeakSelf = weakSelf
14271470#ifdef DEBUG_NODEIDS
1428− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1471+ , rootSubscribedNodeId = nid
14291472#endif
14301473 }
14311474 -- If we die at the same moment that all our children die, they will
@@ -1474,16 +1517,10 @@ newFanInt = do
14741517 , _fanInt_occRef = occRef
14751518 }
14761519
1477−{-# NOINLINE unsafeNewFanInt #-}
1478−unsafeNewFanInt :: b -> FanInt x a
1479−unsafeNewFanInt b = unsafePerformIO $ do
1480− touch b
1481− newFanInt
1482−
14831520fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a
1484−fanInt p =
1485− let self = unsafeNewFanInt p
1486− in EventSelectorInt $ \k -> Event $ \sub -> do
1521+fanInt p = unsafePerformIO $ do
1522+ self <- newFanInt
1523+ pure $ EventSelectorInt $ \k -> Event $ \sub -> do
14871524 isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)
14881525 when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input
14891526 (subscription, parentOcc) <- subscribeAndRead p $ Subscriber
@@ -1491,15 +1528,15 @@ fanInt p =
14911528 liftIO $ writeIORef (_fanInt_occRef self) m
14921529 scheduleIntClear $ _fanInt_occRef self
14931530 FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v -> do --TODO: Do we need to know that no subscribers are being added as we traverse?
1494− FastWeakBag.traverse b $ \s -> do
1531+ FastWeakBag.traverse_ b $ \s -> do
14951532 subscriberPropagate s v
14961533 , subscriberInvalidateHeight = \old -> do
14971534 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1498− FastWeakBag.traverse b $ \s -> do
1535+ FastWeakBag.traverse_ b $ \s -> do
14991536 subscriberInvalidateHeight s old
15001537 , subscriberRecalculateHeight = \new -> do
15011538 FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b -> do
1502− FastWeakBag.traverse b $ \s -> do
1539+ FastWeakBag.traverse_ b $ \s -> do
15031540 subscriberRecalculateHeight s new
15041541 }
15051542 liftIO $ do
@@ -1519,7 +1556,7 @@ fanInt p =
15191556 return (EventSubscription (FastWeakBag.remove t) $! EventSubscribed heightRef $! toAny (_fanInt_subscriptionRef self, t), IntMap.lookup k currentOcc)
15201557
15211558{-# INLINABLE getFanSubscribed #-}
1522−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))
15231560getFanSubscribed k f sub = do
15241561 mSubscribed <- liftIO $ readIORef $ fanSubscribed f
15251562 case mSubscribed of
@@ -1537,13 +1574,16 @@ getFanSubscribed k f sub = do
15371574 subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
15381575 occRef <- liftIO $ newIORef parentOcc
15391576 when (isJust parentOcc) $ scheduleClear occRef
1577+#ifdef DEBUG_NODEIDS
1578+ nid <- liftIO newNodeId
1579+#endif
15401580 let subscribed = FanSubscribed
15411581 { fanSubscribedCachedSubscribed = fanSubscribed f
15421582 , fanSubscribedOccurrence = occRef
15431583 , fanSubscribedParent = subscription
15441584 , fanSubscribedSubscribers = subscribersRef
15451585#ifdef DEBUG_NODEIDS
1546− , fanSubscribedNodeId = unsafeNodeId f
1586+ , fanSubscribedNodeId = nid
15471587#endif
15481588 }
15491589 let !self = (k, subscribed)
@@ -1553,7 +1593,7 @@ getFanSubscribed k f sub = do
15531593 liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
15541594 return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
15551595
1556−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1596+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()
15571597cleanupFanSubscribed (k, subscribed) = do
15581598 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15591599 let reducedSubscribers = DMap.delete k subscribers
@@ -1565,7 +1605,7 @@ cleanupFanSubscribed (k, subscribed) = do
15651605 else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
15661606
15671607{-# INLINE subscribeFanSubscribed #-}
1568−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
15691609subscribeFanSubscribed k subscribed sub = do
15701610 subscribers <- readIORef $ fanSubscribedSubscribers subscribed
15711611 case DMap.lookup k subscribers of
@@ -1603,6 +1643,9 @@ getSwitchSubscribed s sub = do
16031643 when (isJust parentOcc) $ scheduleClear occRef
16041644 weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
16051645 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1646+#ifdef DEBUG_NODEIDS
1647+ nid <- liftIO newNodeId
1648+#endif
16061649 let !subscribed = SwitchSubscribed
16071650 { switchSubscribedCachedSubscribed = switchSubscribed s
16081651 , switchSubscribedOccurrence = occRef
@@ -1615,7 +1658,7 @@ getSwitchSubscribed s sub = do
16151658 , switchSubscribedCurrentParent = subscriptionRef
16161659 , switchSubscribedWeakSelf = weakSelf
16171660#ifdef DEBUG_NODEIDS
1618− , switchSubscribedNodeId = unsafeNodeId s
1661+ , switchSubscribedNodeId = nid
16191662#endif
16201663 }
16211664 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
@@ -1660,6 +1703,9 @@ getCoincidenceSubscribed c sub = do
16601703 scheduleClear innerSubdRef
16611704 weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
16621705 (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1706+#ifdef DEBUG_NODEIDS
1707+ nid <- liftIO newNodeId
1708+#endif
16631709 let subscribed = CoincidenceSubscribed
16641710 { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
16651711 , coincidenceSubscribedOccurrence = occRef
@@ -1670,7 +1716,7 @@ getCoincidenceSubscribed c sub = do
16701716 , coincidenceSubscribedInnerParent = innerSubdRef
16711717 , coincidenceSubscribedWeakSelf = weakSelf
16721718#ifdef DEBUG_NODEIDS
1673− , coincidenceSubscribedNodeId = unsafeNodeId c
1719+ , coincidenceSubscribedNodeId = nid
16741720#endif
16751721 }
16761722 liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
@@ -1687,26 +1733,34 @@ cleanupCoincidenceSubscribed subscribed = do
16871733subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
16881734subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
16891735
1690−{-# INLINE merge #-}
1691−merge :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1692−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)
16931741
16941742{-# INLINE mergeWithMove #-}
1695−mergeWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1696−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)
16971747
16981748{-# INLINE [1] mergeCheap #-}
1699−mergeCheap :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMap k (Event x)) -> Event x (DMap k Identity)
1700−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
17011755 where
1702− updateMe :: MergeUpdateFunc k x (PatchDMap k (Event x)) (MergeSubscribedParent x)
1756+ updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)
17031757 updateMe subscriber heightBagRef oldParents (PatchDMap p) = do
17041758 let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do
17051759 (mOldSubd, newPs) <- case me of
17061760 Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
17071761 Just e -> do
17081762 let s = subscriber $ return k
1709− subscription@(EventSubscription _ subd) <- subscribe e s
1763+ subscription@(EventSubscription _ subd) <- subscribe (nt e) s
17101764 newParentHeight <- liftIO $ getEventSubscribedHeight subd
17111765 let newParent = MergeSubscribedParent subscription
17121766 liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight
@@ -1716,28 +1770,33 @@ mergeCheap = mergeCheap' getInitialSubscribers updateMe destroy
17161770 liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight
17171771 return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)
17181772 foldM f ([], oldParents) $ DMap.toList p
1719− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParent x)
1773+
1774+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)
17201775 getInitialSubscribers initialParents subscriber = do
17211776 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17221777 let s = subscriber $ return k
1723− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1778+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17241779 height <- liftIO $ getEventSubscribedHeight parentSubd
1725− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription)
1780+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)
17261781 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17271782 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17281783 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17291784 )
1785+
17301786 destroy :: MergeDestroyFunc k (MergeSubscribedParent x)
17311787 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub
17321788
17331789{-# INLINE [1] mergeCheapWithMove #-}
1734−mergeCheapWithMove :: forall k x. (HasSpiderTimeline x, GCompare k) => Dynamic x (PatchDMapWithMove k (Event x)) -> Event x (DMap k Identity)
1735−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
17361795 where
1737− updateMe :: MergeUpdateFunc k x (PatchDMapWithMove k (Event x)) (MergeSubscribedParentWithMove x k)
1796+ updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)
17381797 updateMe subscriber heightBagRef oldParents p = do
17391798 -- Prepare new parents for insertion
1740− 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)
17411800 subscribeParent k e = do
17421801 keyRef <- liftIO $ newIORef k
17431802 let s = subscriber $ liftIO $ readIORef keyRef
@@ -1746,9 +1805,9 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17461805 newParentHeight <- getEventSubscribedHeight subd
17471806 modifyIORef' heightBagRef $ heightBagAdd newParentHeight
17481807 return $ MergeSubscribedParentWithMove subscription keyRef
1749− p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey subscribeParent p
1808+ p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p
17501809 -- Collect old parents for deletion and update the keys of moved parents
1751− 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
17521811 moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of
17531812 Nothing -> do
17541813 oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ _mergeSubscribedParentWithMove_subscription parent
@@ -1759,46 +1818,47 @@ mergeCheapWithMove = mergeCheap' getInitialSubscribers updateMe destroy
17591818 return Nothing
17601819 toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents
17611820 return (toDelete, applyAlways p' oldParents)
1762− getInitialSubscribers :: MergeInitFunc k x (MergeSubscribedParentWithMove x k)
1821+ getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)
17631822 getInitialSubscribers initialParents subscriber = do
17641823 subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
17651824 keyRef <- liftIO $ newIORef k
17661825 let s = subscriber $ liftIO $ readIORef keyRef
1767− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1826+ (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s
17681827 height <- liftIO $ getEventSubscribedHeight parentSubd
1769− return (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
1828+ return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)
17701829 return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
17711830 , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
17721831 , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
17731832 )
1833+
17741834 destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)
17751835 destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub
17761836
1777−type MergeUpdateFunc k x p s
1778− = (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))
17791839 -> IORef HeightBag
17801840 -> DMap k s
17811841 -> p
17821842 -> EventM x ([EventSubscription x], DMap k s)
17831843
1784−type MergeInitFunc k x s
1785− = DMap k (Event x)
1786− -> (forall a. EventM x (k a) -> Subscriber x a)
1787− -> 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)
17881848
17891849type MergeDestroyFunc k s
17901850 = DMap k s
17911851 -> IO ()
17921852
1793−data Merge x k s = Merge
1853+data Merge x k v s = Merge
17941854 { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))
17951855 , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)
17961856 , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)
1797− , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k Identity))
1798− , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k Identity))
1857+ , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))
1858+ , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))
17991859 }
18001860
1801−invalidateMergeHeight :: Merge x k s -> IO ()
1861+invalidateMergeHeight :: Merge x k v s -> IO ()
18021862invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)
18031863
18041864invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()
@@ -1808,8 +1868,7 @@ invalidateMergeHeight' heightRef sub = do
18081868 writeIORef heightRef $! invalidHeight
18091869 subscriberInvalidateHeight sub oldHeight
18101870
1811−
1812−revalidateMergeHeight :: Merge x k s -> IO ()
1871+revalidateMergeHeight :: Merge x k v s -> IO ()
18131872revalidateMergeHeight m = do
18141873 currentHeight <- readIORef $ _merge_heightRef m
18151874 when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
@@ -1825,19 +1884,19 @@ revalidateMergeHeight m = do
18251884 subscriberRecalculateHeight (_merge_sub m) height
18261885 GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"
18271886
1828−scheduleMergeSelf :: HasSpiderTimeline x => Merge x k s -> Height -> EventM x ()
1887+scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()
18291888scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do
18301889 vals <- liftIO $ readIORef $ _merge_accumRef m
18311890 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
18321891 --TODO: Assert that m is not empty
18331892 subscriberPropagate (_merge_sub m) vals
18341893
1835−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)
18361895mergeSubscriber m getKey = Subscriber
18371896 { subscriberPropagate = \a -> do
18381897 oldM <- liftIO $ readIORef $ _merge_accumRef m
18391898 k <- getKey
1840− 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
18411900 tracePropagate (Proxy :: Proxy x) $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
18421901 liftIO $ writeIORef (_merge_accumRef m) $! newM
18431902 when (DMap.null oldM) $ do -- Only schedule the firing once
@@ -1852,7 +1911,7 @@ mergeSubscriber m getKey = Subscriber
18521911 else liftIO $ do
18531912#ifdef DEBUG_CYCLES
18541913 nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
1855− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
1914+ stacks <- forM nodesInvolvedInCycle $ \(Some es) -> whoCreatedEventSubscribed es
18561915 let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
18571916#else
18581917 let cycleInfo = ""
@@ -1868,7 +1927,7 @@ mergeSubscriber m getKey = Subscriber
18681927 }
18691928
18701929--TODO: Be able to run as much of this as possible promptly
1871−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
18721931updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)
18731932 where updateMe = do
18741933 oldParents <- liftIO $ readIORef $ _merge_parentsRef m
@@ -1876,9 +1935,10 @@ updateMerge m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m)
18761935 liftIO $ writeIORef (_merge_parentsRef m) $! newParents
18771936 return subscriptionsToKill
18781937
1879−{-# INLINE mergeCheap' #-}
1880−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)
1881−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
18821942 initialParents <- readBehaviorUntracked $ dynamicCurrent d
18831943 accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"
18841944 heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"
@@ -1926,11 +1986,11 @@ mergeCheap' getInitialSubscribers updateFunc destroy d = Event $ \sub -> do
19261986 , occ
19271987 )
19281988
1929−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)
19301990mergeInt = cacheEvent . mergeIntCheap
19311991
19321992{-# INLINABLE mergeIntCheap #-}
1933−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)
19341994mergeIntCheap d = Event $ \sub -> do
19351995 initialParents <- readBehaviorUntracked $ dynamicCurrent d
19361996 accum <- liftIO $ FastMutableIntMap.newEmpty
@@ -2027,14 +2087,16 @@ mergeIntCheap d = Event $ \sub -> do
20272087 )
20282088
20292089newtype 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) }
20302091
2031−fan :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k Identity) -> EventSelector x k
2032−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
20332095 let f = Fan
20342096 { fanParent = e
2035− , fanSubscribed = unsafeNewIORef e Nothing
2097+ , fanSubscribed = ref
20362098 }
2037− in EventSelector $ \k -> eventFan k f
2099+ pure $ EventSelectorG $ \k -> eventFan k f
20382100
20392101runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()
20402102runHoldInits holdInitRef dynInitRef mergeInitRef = do
@@ -2088,18 +2150,18 @@ clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeI
20882150-- | Run an event action outside of a frame
20892151runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
20902152runFrame a = SpiderHost $ do
2091− let env = _spiderTimeline_eventEnv (spiderTimeline :: SpiderTimelineEnv x)
2153+ let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)
20922154 let go = do
20932155 result <- a
20942156 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
20952157 return result
20962158 result <- runEventM go
20972159 toClear <- readIORef $ eventEnvClears env
2098− forM_ toClear $ \(Some.This (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
2160+ forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing
20992161 toClearInt <- readIORef $ eventEnvIntClears env
2100− forM_ toClearInt $ \(Some.This (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
2162+ forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty
21012163 toClearRoot <- readIORef $ eventEnvRootClears env
2102− forM_ toClearRoot $ \(Some.This (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
2164+ forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
21032165 toAssign <- readIORef $ eventEnvAssignments env
21042166 toReconnectRef <- newIORef []
21052167 coincidenceInfos <- readIORef $ eventEnvResetCoincidences env
@@ -2146,7 +2208,7 @@ runFrame a = SpiderHost $ do
21462208 myHeight <- readIORef $ switchSubscribedHeight subscribed
21472209 when (parentHeight /= myHeight) $ do
21482210 writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
2149− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
2211+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
21502212 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
21512213 forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
21522214 unsubscribe subscription
@@ -2187,7 +2249,7 @@ invalidateCoincidenceHeight subscribed = do
21872249 oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
21882250 when (oldHeight /= invalidHeight) $ do
21892251 writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
2190− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
2252+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
21912253
21922254updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
21932255updateSwitchHeight new subscribed = do
@@ -2195,7 +2257,7 @@ updateSwitchHeight new subscribed = do
21952257 when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21962258 when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
21972259 writeIORef (switchSubscribedHeight subscribed) $! new
2198− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
2260+ WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
21992261
22002262recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
22012263recalculateCoincidenceHeight subscribed = do
@@ -2204,7 +2266,7 @@ recalculateCoincidenceHeight subscribed = do
22042266 height <- calculateCoincidenceHeight subscribed
22052267 when (height /= invalidHeight) $ do
22062268 writeIORef (coincidenceSubscribedHeight subscribed) $! height
2207− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
2269+ WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
22082270
22092271calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
22102272calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
@@ -2299,7 +2361,7 @@ instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x))
22992361 fail _ = error "Dynamic does not support 'fail'"
23002362
23012363{-# INLINABLE newJoinDyn #-}
2302−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)
23032365newJoinDyn d =
23042366 let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
23052367 eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
@@ -2449,7 +2511,7 @@ unsafeNewSpiderTimelineEnv = do
24492511#ifdef DEBUG
24502512 depthRef <- newIORef 0
24512513#endif
2452− return $ SpiderTimelineEnv
2514+ return $ STE $ SpiderTimelineEnv
24532515 { _spiderTimeline_lock = lock
24542516 , _spiderTimeline_eventEnv = env
24552517#ifdef DEBUG
@@ -2459,19 +2521,19 @@ unsafeNewSpiderTimelineEnv = do
24592521
24602522-- | Create a new SpiderTimelineEnv
24612523newSpiderTimeline :: IO (Some SpiderTimelineEnv)
2462−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
2524+newSpiderTimeline = withSpiderTimeline (pure . Some)
24632525
2464−data LocalSpiderTimeline x s
2526+data LocalSpiderTimeline (x :: Type) s
24652527
24662528instance Reifies s (SpiderTimelineEnv x) =>
24672529 HasSpiderTimeline (LocalSpiderTimeline x s) where
2468− spiderTimeline = localSpiderTimeline (Proxy :: Proxy s) $ reflect (Proxy :: Proxy s)
2530+ spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)
24692531
24702532localSpiderTimeline
2471− :: Proxy s
2533+ :: proxy s
24722534 -> SpiderTimelineEnv x
24732535 -> SpiderTimelineEnv (LocalSpiderTimeline x s)
2474−localSpiderTimeline _ = unsafeCoerce
2536+localSpiderTimeline _ = coerce
24752537
24762538-- | Pass a new timeline to the given function.
24772539withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r
@@ -2479,18 +2541,18 @@ withSpiderTimeline k = do
24792541 env <- unsafeNewSpiderTimelineEnv
24802542 reify env $ \s -> k $ localSpiderTimeline s env
24812543
2482−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)
24832545
24842546type ComputeM = EventM
24852547
2486−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)
24872549
24882550instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
24892551 {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}
24902552 newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
24912553 newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
2492− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
2493− 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 }
24942556 type PullM (SpiderTimeline x) = SpiderPullM x
24952557 type PushM (SpiderTimeline x) = SpiderPushM x
24962558 {-# INLINABLE never #-}
@@ -2503,10 +2565,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25032565 pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent
25042566 {-# INLINABLE pull #-}
25052567 pull = SpiderBehavior . pull . coerce
2506− {-# INLINABLE merge #-}
2507− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2508− {-# INLINABLE fan #-}
2509− 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
25102577 {-# INLINABLE switch #-}
25112578 switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
25122579 {-# INLINABLE coincidence #-}
@@ -2514,15 +2581,15 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25142581 {-# INLINABLE current #-}
25152582 current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
25162583 {-# INLINABLE updated #-}
2517− updated = coerce $ SpiderEvent . dynamicUpdated . unSpiderDynamic
2584+ updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic
25182585 {-# INLINABLE unsafeBuildDynamic #-}
25192586 unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'
25202587 {-# INLINABLE unsafeBuildIncremental #-}
25212588 unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv
2522− {-# INLINABLE mergeIncremental #-}
2523− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (PatchDMap k (Event x))) . unSpiderIncremental
2524− {-# INLINABLE mergeIncrementalWithMove #-}
2525− 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
25262593 {-# INLINABLE currentIncremental #-}
25272594 currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
25282595 {-# INLINABLE updatedIncremental #-}
@@ -2533,9 +2600,10 @@ instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where
25332600 return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'
25342601 eventCoercion Coercion = Coercion
25352602 behaviorCoercion Coercion = Coercion
2536− 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
25372605 {-# INLINABLE mergeIntIncremental #-}
2538− mergeIntIncremental = SpiderEvent . mergeInt . (unsafeCoerce :: Dynamic x (PatchIntMap (R.Event (SpiderTimeline x) a)) -> Dynamic x (PatchIntMap (Event x a))) . unSpiderIncremental
2606+ mergeIntIncremental = SpiderEvent . mergeInt . coerce
25392607 {-# INLINABLE fanInt #-}
25402608 fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))
25412609
@@ -2560,7 +2628,7 @@ instance MonadAtomicRef (EventM x) where
25602628 atomicModifyRef r f = liftIO $ atomicModifyRef r f
25612629
25622630-- | The monad for actions that manipulate a Spider timeline identified by @x@
2563−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)
25642632
25652633instance Monad (SpiderHost x) where
25662634 {-# INLINABLE (>>=) #-}
@@ -2582,7 +2650,7 @@ runSpiderHost (SpiderHost a) = a
25822650runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a
25832651runSpiderHostForTimeline (SpiderHost a) _ = a
25842652
2585−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
2653+newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }
25862654 deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
25872655
25882656instance Monad (SpiderHostFrame x) where
@@ -2638,3 +2706,11 @@ instance MonadAtomicRef (SpiderHostFrame x) where
26382706instance PrimMonad (SpiderHostFrame x) where
26392707 type PrimState (SpiderHostFrame x) = PrimState IO
26402708 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 ()