packages feed

reflex 0.9.4.1 → 0.10.0.0

raw patch · 69 files changed

+6421/−5599 lines, 69 filesdep +tastydep +tasty-expected-failuredep +tasty-hunitdep −bifunctorsdep −comonaddep −directorydep ~basedep ~bytestringdep ~constraints-extrassetup-changedPVP ok

version bump matches the API change (PVP)

Dependencies added: tasty, tasty-expected-failure, tasty-hunit

Dependencies removed: bifunctors, comonad, directory, filemanip, filepath, hlint

Dependency ranges changed: base, bytestring, constraints-extras, containers, dependent-map, dependent-sum, mtl, primitive, stm, template-haskell, time, transformers

API changes (from Hackage documentation)

- Data.FastWeakBag: _weakBag_children :: FastWeakBag a -> IORef (IntMap (Weak a))
- Data.FastWeakBag: data FastWeakBag a
- Data.FastWeakBag: data FastWeakBagTicket a
- Data.FastWeakBag: empty :: IO (FastWeakBag a)
- Data.FastWeakBag: insert :: a -> FastWeakBag a -> IO (FastWeakBagTicket a)
- Data.FastWeakBag: isEmpty :: FastWeakBag a -> IO Bool
- Data.FastWeakBag: remove :: FastWeakBagTicket a -> IO ()
- Data.FastWeakBag: traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
- Data.FastWeakBag: traverse_ :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()
- Data.WeakBag: _weakBag_children :: WeakBag a -> IORef (IntMap (Weak a))
- Data.WeakBag: singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)
- Reflex.EventWriter.Base: instance Data.GADT.Internal.GCompare (Reflex.EventWriter.Base.TellId w)
- Reflex.EventWriter.Base: instance Data.GADT.Internal.GEq (Reflex.EventWriter.Base.TellId w)
- Reflex.EventWriter.Base: instance GHC.Classes.Eq (Reflex.EventWriter.Base.TellId w x)
- Reflex.EventWriter.Base: instance GHC.Classes.Ord (Reflex.EventWriter.Base.TellId w x)
- Reflex.EventWriter.Base: instance GHC.Enum.Enum (Reflex.EventWriter.Base.TellId w x)
- Reflex.EventWriter.Base: instance GHC.Show.Show (Reflex.EventWriter.Base.TellId w x)
- Reflex.FastWeak: data FastWeakTicket a
- Reflex.FastWeak: emptyFastWeak :: FastWeak a
- Reflex.FastWeak: getFastWeakTicket :: FastWeak a -> IO (Maybe (FastWeakTicket a))
- Reflex.FastWeak: getFastWeakTicketValue :: FastWeakTicket a -> IO a
- Reflex.FastWeak: getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)
- Reflex.FastWeak: getFastWeakValue :: FastWeak a -> IO (Maybe a)
- Reflex.FastWeak: mkFastWeakTicket :: a -> IO (FastWeakTicket a)
- Reflex.FastWeak: type FastWeak a = Weak a
- Reflex.Spider: type SpiderEnv = SpiderTimeline :: k -> Type
- Reflex.Spider.Internal: Coincidence :: !Event x (Event x a) -> !IORef (Maybe (CoincidenceSubscribed x a)) -> Coincidence (x :: k) a
- Reflex.Spider.Internal: EventSubscribed :: {-# UNPACK #-} !IORef Height -> {-# NOUNPACK #-} !Any :: Type -> EventSubscribed (x :: k)
- Reflex.Spider.Internal: FanInt :: {-# UNPACK #-} !FastMutableIntMap (FastWeakBag (Subscriber x a)) -> {-# UNPACK #-} !IORef (EventSubscription x) -> {-# UNPACK #-} !IORef (IntMap a) -> FanInt (x :: k) a
- Reflex.Spider.Internal: FanSubscribedChildren :: !WeakBag (Subscriber x (v a)) -> {-# NOUNPACK #-} !(k2 a, FanSubscribed x k2 v) -> !IORef (Weak (k2 a, FanSubscribed x k2 v)) -> FanSubscribedChildren (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (a :: k1)
- Reflex.Spider.Internal: Height :: Int -> Height
- Reflex.Spider.Internal: HeightBag :: {-# UNPACK #-} !Int -> !IntMap Word -> HeightBag
- Reflex.Spider.Internal: IntClear :: IORef (IntMap a) -> IntClear a
- Reflex.Spider.Internal: Merge :: {-# UNPACK #-} !IORef (DMap k2 s) -> {-# UNPACK #-} !IORef HeightBag -> {-# UNPACK #-} !IORef Height -> {-# UNPACK #-} !Subscriber x (DMap k2 v) -> {-# UNPACK #-} !IORef (DMap k2 v) -> Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type)
- Reflex.Spider.Internal: SomeBehaviorSubscribed :: Some (BehaviorSubscribed x) -> SomeBehaviorSubscribed (x :: k)
- Reflex.Spider.Internal: SomeCoincidenceSubscribed :: !CoincidenceSubscribed x a -> SomeCoincidenceSubscribed (x :: k)
- Reflex.Spider.Internal: Switch :: !Behavior x (Event x a) -> !IORef (Maybe (SwitchSubscribed x a)) -> Switch (x :: k) a
- Reflex.Spider.Internal: [_eventSubscription_subscribed] :: EventSubscription (x :: k) -> {-# UNPACK #-} !EventSubscribed x
- Reflex.Spider.Internal: [_fanInt_occRef] :: FanInt (x :: k) a -> {-# UNPACK #-} !IORef (IntMap a)
- Reflex.Spider.Internal: [_fanInt_subscribers] :: FanInt (x :: k) a -> {-# UNPACK #-} !FastMutableIntMap (FastWeakBag (Subscriber x a))
- Reflex.Spider.Internal: [_fanInt_subscriptionRef] :: FanInt (x :: k) a -> {-# UNPACK #-} !IORef (EventSubscription x)
- Reflex.Spider.Internal: [_fanSubscribedChildren_list] :: FanSubscribedChildren (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (a :: k1) -> !WeakBag (Subscriber x (v a))
- Reflex.Spider.Internal: [_fanSubscribedChildren_self] :: FanSubscribedChildren (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (a :: k1) -> {-# NOUNPACK #-} !(k2 a, FanSubscribed x k2 v)
- Reflex.Spider.Internal: [_fanSubscribedChildren_weakSelf] :: FanSubscribedChildren (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (a :: k1) -> !IORef (Weak (k2 a, FanSubscribed x k2 v))
- Reflex.Spider.Internal: [_heightBag_contents] :: HeightBag -> !IntMap Word
- Reflex.Spider.Internal: [_heightBag_size] :: HeightBag -> {-# UNPACK #-} !Int
- Reflex.Spider.Internal: [_merge_accumRef] :: Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type) -> {-# UNPACK #-} !IORef (DMap k2 v)
- Reflex.Spider.Internal: [_merge_heightBagRef] :: Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type) -> {-# UNPACK #-} !IORef HeightBag
- Reflex.Spider.Internal: [_merge_heightRef] :: Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type) -> {-# UNPACK #-} !IORef Height
- Reflex.Spider.Internal: [_merge_parentsRef] :: Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type) -> {-# UNPACK #-} !IORef (DMap k2 s)
- Reflex.Spider.Internal: [_merge_sub] :: Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type) -> {-# UNPACK #-} !Subscriber x (DMap k2 v)
- Reflex.Spider.Internal: [coincidenceParent] :: Coincidence (x :: k) a -> !Event x (Event x a)
- Reflex.Spider.Internal: [coincidenceSubscribedCachedSubscribed] :: CoincidenceSubscribed (x :: k) a -> !IORef (Maybe (CoincidenceSubscribed x a))
- Reflex.Spider.Internal: [coincidenceSubscribedHeight] :: CoincidenceSubscribed (x :: k) a -> !IORef Height
- Reflex.Spider.Internal: [coincidenceSubscribedOccurrence] :: CoincidenceSubscribed (x :: k) a -> !IORef (Maybe a)
- Reflex.Spider.Internal: [coincidenceSubscribedOuter] :: CoincidenceSubscribed (x :: k) a -> {-# NOUNPACK #-}Subscriber x (Event x a)
- Reflex.Spider.Internal: [coincidenceSubscribedSubscribers] :: CoincidenceSubscribed (x :: k) a -> !WeakBag (Subscriber x a)
- Reflex.Spider.Internal: [coincidenceSubscribedWeakSelf] :: CoincidenceSubscribed (x :: k) a -> !IORef (Weak (CoincidenceSubscribed x a))
- Reflex.Spider.Internal: [coincidenceSubscribed] :: Coincidence (x :: k) a -> !IORef (Maybe (CoincidenceSubscribed x a))
- Reflex.Spider.Internal: [eventEnvIntClears] :: EventEnv x -> !IORef [Some IntClear]
- Reflex.Spider.Internal: [eventEnvInvalidatedCoincidences] :: EventEnv x -> !IORef [SomeCoincidenceSubscribed x]
- Reflex.Spider.Internal: [eventSubscribedHeightRef] :: EventSubscribed (x :: k) -> {-# UNPACK #-} !IORef Height
- Reflex.Spider.Internal: [eventSubscribedRetained] :: EventSubscribed (x :: k) -> {-# NOUNPACK #-} !Any :: Type
- Reflex.Spider.Internal: [fanParent] :: Fan (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !Event x (DMap k2 v)
- Reflex.Spider.Internal: [fanSubscribedCachedSubscribed] :: FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !IORef (Maybe (FanSubscribed x k2 v))
- Reflex.Spider.Internal: [fanSubscribed] :: Fan (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !IORef (Maybe (FanSubscribed x k2 v))
- Reflex.Spider.Internal: [holdEvent] :: Hold (x :: k) p -> Event x p
- Reflex.Spider.Internal: [holdInvalidators] :: Hold (x :: k) p -> !IORef (InvalidatorList x)
- Reflex.Spider.Internal: [holdParent] :: Hold (x :: k) p -> !IORef (Maybe (EventSubscription x))
- Reflex.Spider.Internal: [rootSubscribedCachedSubscribed] :: RootSubscribed (x :: k) a -> !IORef (DMap k1 (RootSubscribed x))
- Reflex.Spider.Internal: [rootSubscribedKey] :: RootSubscribed (x :: k) a -> !k1 a
- Reflex.Spider.Internal: [rootSubscribedOccurrence] :: RootSubscribed (x :: k) a -> !IO (Maybe a)
- Reflex.Spider.Internal: [rootSubscribedUninit] :: RootSubscribed (x :: k) a -> IO ()
- Reflex.Spider.Internal: [rootSubscribedWeakSelf] :: RootSubscribed (x :: k) a -> !IORef (Weak (RootSubscribed x a))
- Reflex.Spider.Internal: [switchParent] :: Switch (x :: k) a -> !Behavior x (Event x a)
- Reflex.Spider.Internal: [switchSubscribedBehaviorParents] :: SwitchSubscribed (x :: k) a -> !IORef [SomeBehaviorSubscribed x]
- Reflex.Spider.Internal: [switchSubscribedCachedSubscribed] :: SwitchSubscribed (x :: k) a -> !IORef (Maybe (SwitchSubscribed x a))
- Reflex.Spider.Internal: [switchSubscribedCurrentParent] :: SwitchSubscribed (x :: k) a -> !IORef (EventSubscription x)
- Reflex.Spider.Internal: [switchSubscribedHeight] :: SwitchSubscribed (x :: k) a -> !IORef Height
- Reflex.Spider.Internal: [switchSubscribedOccurrence] :: SwitchSubscribed (x :: k) a -> !IORef (Maybe a)
- Reflex.Spider.Internal: [switchSubscribedOwnWeakInvalidator] :: SwitchSubscribed (x :: k) a -> !IORef (Weak (Invalidator x))
- Reflex.Spider.Internal: [switchSubscribedParent] :: SwitchSubscribed (x :: k) a -> !Behavior x (Event x a)
- Reflex.Spider.Internal: [switchSubscribedSubscribers] :: SwitchSubscribed (x :: k) a -> !WeakBag (Subscriber x a)
- Reflex.Spider.Internal: [switchSubscribedWeakSelf] :: SwitchSubscribed (x :: k) a -> !IORef (Weak (SwitchSubscribed x a))
- Reflex.Spider.Internal: [switchSubscribed] :: Switch (x :: k) a -> !IORef (Maybe (SwitchSubscribed x a))
- Reflex.Spider.Internal: [unEvent] :: Event (x :: k) a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
- Reflex.Spider.Internal: [unHeight] :: Height -> Int
- Reflex.Spider.Internal: askBehaviorHoldInits :: forall {k} (x :: k). BehaviorM x (IORef [SomeHoldInit x])
- Reflex.Spider.Internal: askInvalidator :: forall {k} (x :: k). BehaviorM x (Maybe (Weak (Invalidator x)))
- Reflex.Spider.Internal: askParentsRef :: forall {k} (x :: k). BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
- Reflex.Spider.Internal: behaviorHoldIdentity :: forall {k} (x :: k) a. Hold x (Identity a) -> Behavior x a
- Reflex.Spider.Internal: cacheSubscription :: forall {k} (x :: k) a. Subscriber x a -> IORef (FastWeak (CacheSubscribed x a)) -> FastWeakTicket (CacheSubscribed x a) -> IO (EventSubscription x, Maybe a)
- Reflex.Spider.Internal: calculateSwitchHeight :: forall {k} (x :: k) a. SwitchSubscribed x a -> IO Height
- Reflex.Spider.Internal: class HasSpiderTimeline x => HasCurrentHeight x (m :: Type -> Type) | m -> x
- Reflex.Spider.Internal: cleanupCoincidenceSubscribed :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> IO ()
- Reflex.Spider.Internal: cleanupFanSubscribed :: forall {k1} {k2} k3 (a :: k1) (x :: k2) (v :: k1 -> Type). GCompare k3 => (k3 a, FanSubscribed x k3 v) -> IO ()
- Reflex.Spider.Internal: cleanupRootSubscribed :: forall {k} (x :: k) a. RootSubscribed x a -> IO ()
- Reflex.Spider.Internal: cleanupSwitchSubscribed :: forall {k} (x :: k) a. SwitchSubscribed x a -> IO ()
- Reflex.Spider.Internal: data BehaviorSubscribed (x :: k) a
- Reflex.Spider.Internal: data Coincidence (x :: k) a
- Reflex.Spider.Internal: data EventSubscribed (x :: k)
- Reflex.Spider.Internal: data Fan (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type)
- Reflex.Spider.Internal: data FanInt (x :: k) a
- Reflex.Spider.Internal: data FanSubscribedChildren (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (a :: k1)
- Reflex.Spider.Internal: data HeightBag
- Reflex.Spider.Internal: data Merge (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type)
- Reflex.Spider.Internal: data SomeCoincidenceSubscribed (x :: k)
- Reflex.Spider.Internal: data Switch (x :: k) a
- Reflex.Spider.Internal: debugSubscriber' :: forall {k} (x :: k) a. String -> Subscriber x a -> Subscriber x a
- Reflex.Spider.Internal: dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)
- Reflex.Spider.Internal: dynamicHoldIdentity :: forall {k} (x :: k) a. Hold x (Identity a) -> DynamicS x (Identity a)
- Reflex.Spider.Internal: eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a
- Reflex.Spider.Internal: eventSubscribedCoincidence :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> EventSubscribed x
- Reflex.Spider.Internal: eventSubscribedFan :: forall {k1} {k2} (x :: k1) (k3 :: k2 -> Type) (v :: k2 -> Type). FanSubscribed x k3 v -> EventSubscribed x
- Reflex.Spider.Internal: eventSubscribedNever :: forall {k} (x :: k). EventSubscribed x
- Reflex.Spider.Internal: eventSubscribedNow :: forall {k} (x :: k). EventSubscribed x
- Reflex.Spider.Internal: eventSubscribedRoot :: forall {k} (x :: k) a. RootSubscribed x a -> EventSubscribed x
- Reflex.Spider.Internal: eventSubscribedSwitch :: forall {k} (x :: k) a. SwitchSubscribed x a -> EventSubscribed x
- Reflex.Spider.Internal: eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a
- Reflex.Spider.Internal: fanIntSubscribed :: forall {k1} k2 (x :: k1) a. FastWeakBagTicket k2 -> FanInt x a -> IO (EventSubscribed x)
- Reflex.Spider.Internal: getCoincidenceSubscribed :: HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
- Reflex.Spider.Internal: getEventSubscribedHeight :: forall {k} (x :: k). EventSubscribed x -> IO Height
- Reflex.Spider.Internal: getFanSubscribed :: forall {k1} x k2 (a :: k1) v. (HasSpiderTimeline x, GCompare k2) => k2 a -> Fan x k2 v -> Subscriber x (v a) -> EventM x (WeakBagTicket, FanSubscribed x k2 v, Maybe (v a))
- Reflex.Spider.Internal: getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)
- Reflex.Spider.Internal: getRootSubscribed :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
- Reflex.Spider.Internal: getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)
- Reflex.Spider.Internal: heightBagAdd :: Height -> HeightBag -> HeightBag
- Reflex.Spider.Internal: heightBagEmpty :: HeightBag
- Reflex.Spider.Internal: heightBagFromList :: [Height] -> HeightBag
- Reflex.Spider.Internal: heightBagMax :: HeightBag -> Height
- Reflex.Spider.Internal: heightBagRemove :: Height -> HeightBag -> HeightBag
- Reflex.Spider.Internal: heightBagRemoveMaybe :: Height -> HeightBag -> Maybe HeightBag
- Reflex.Spider.Internal: heightBagSize :: HeightBag -> Int
- Reflex.Spider.Internal: heightBagVerify :: HeightBag -> HeightBag
- Reflex.Spider.Internal: instance GHC.Classes.Eq Reflex.Spider.Internal.Height
- Reflex.Spider.Internal: instance GHC.Classes.Eq Reflex.Spider.Internal.HeightBag
- Reflex.Spider.Internal: instance GHC.Classes.Ord Reflex.Spider.Internal.Height
- Reflex.Spider.Internal: instance GHC.Classes.Ord Reflex.Spider.Internal.HeightBag
- Reflex.Spider.Internal: instance GHC.Enum.Bounded Reflex.Spider.Internal.Height
- Reflex.Spider.Internal: instance GHC.Read.Read Reflex.Spider.Internal.Height
- Reflex.Spider.Internal: instance GHC.Read.Read Reflex.Spider.Internal.HeightBag
- Reflex.Spider.Internal: instance GHC.Show.Show Reflex.Spider.Internal.Height
- Reflex.Spider.Internal: instance GHC.Show.Show Reflex.Spider.Internal.HeightBag
- Reflex.Spider.Internal: instance Reflex.Spider.Internal.HasSpiderTimeline x => Reflex.Spider.Internal.Defer (Data.Some.Newtype.Some Reflex.Spider.Internal.IntClear) (Reflex.Spider.Internal.EventM x)
- Reflex.Spider.Internal: instance Reflex.Spider.Internal.HasSpiderTimeline x => Reflex.Spider.Internal.HasCurrentHeight x (Reflex.Spider.Internal.EventM x)
- Reflex.Spider.Internal: invalidHeight :: Height
- Reflex.Spider.Internal: invalidateMergeHeight :: forall {k1} {k2} (x :: k1) (k3 :: k2 -> Type) (v :: k2 -> Type) (s :: k2 -> Type). Merge x k3 v s -> IO ()
- Reflex.Spider.Internal: invalidateMergeHeight' :: forall {k} (x :: k) a. IORef Height -> Subscriber x a -> IO ()
- Reflex.Spider.Internal: invalidateSubscriberHeight :: forall {k} (x :: k) a. Height -> Subscriber x a -> IO ()
- Reflex.Spider.Internal: mergeGCheap' :: forall {k1} k2 v x p (s :: k1 -> Type) (q :: k1 -> Type). (HasSpiderTimeline x, GCompare k2, PatchTarget p ~ DMap k2 q) => MergeGetSubscription x s -> MergeInitFunc k2 v q x s -> MergeUpdateFunc k2 v x p s -> MergeDestroyFunc k2 s -> DynamicS x p -> Event x (DMap k2 v)
- Reflex.Spider.Internal: mergeSubscriber :: forall {k1} x k2 v (s :: k1 -> Type) (a :: k1). (HasSpiderTimeline x, GCompare k2) => EventSubscribed x -> Merge x k2 v s -> EventM x (k2 a) -> Subscriber x (v a)
- Reflex.Spider.Internal: newFanInt :: forall {k} (x :: k) a. IO (FanInt x a)
- Reflex.Spider.Internal: newSubscriberFan :: forall {k1} x (k2 :: k1 -> Type) (v :: k1 -> Type). (HasSpiderTimeline x, GCompare k2) => FanSubscribed x k2 v -> IO (Subscriber x (DMap k2 v))
- Reflex.Spider.Internal: newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)
- Reflex.Spider.Internal: newSubscriberSwitch :: HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)
- Reflex.Spider.Internal: newtype Height
- Reflex.Spider.Internal: newtype IntClear a
- Reflex.Spider.Internal: newtype SomeBehaviorSubscribed (x :: k)
- Reflex.Spider.Internal: propagateFast :: forall {k} (x :: k) a. a -> FastWeakBag (Subscriber x a) -> EventM x ()
- Reflex.Spider.Internal: propagateSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()
- Reflex.Spider.Internal: recalculateSubscriberHeight :: forall {k} (x :: k) a. Height -> Subscriber x a -> IO ()
- Reflex.Spider.Internal: revalidateMergeHeight :: forall {k1} {k2} (x :: k1) (k3 :: k2 -> Type) (v :: k2 -> Type) (s :: k2 -> Type). Merge x k3 v s -> IO ()
- Reflex.Spider.Internal: scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()
- Reflex.Spider.Internal: scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()
- Reflex.Spider.Internal: scheduleMergeSelf :: forall {k1} x (k2 :: k1 -> Type) (v :: k1 -> Type) (s :: k1 -> Type). HasSpiderTimeline x => Merge x k2 v s -> Height -> EventM x ()
- Reflex.Spider.Internal: subscribeAndRead :: forall {k} (x :: k) a. Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
- Reflex.Spider.Internal: subscribeAndReadHead :: forall {k} (x :: k) a. Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)
- Reflex.Spider.Internal: subscribeCoincidenceSubscribed :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
- Reflex.Spider.Internal: subscribeFanSubscribed :: forall {k1} {k2} k3 (a :: k1) (x :: k2) v. GCompare k3 => k3 a -> FanSubscribed x k3 v -> Subscriber x (v a) -> IO WeakBagTicket
- Reflex.Spider.Internal: subscribeRootSubscribed :: forall {k} (x :: k) a. RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
- Reflex.Spider.Internal: subscribeSwitchSubscribed :: forall {k} (x :: k) a. SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
- Reflex.Spider.Internal: succHeight :: Height -> Height
- Reflex.Spider.Internal: type BehaviorEnv (x :: k) = (Maybe (Weak Invalidator x, IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
- Reflex.Spider.Internal: type ComputeM = EventM :: k -> Type -> Type
- Reflex.Spider.Internal: type MergeDestroyFunc (k1 :: k -> Type) (s :: k -> Type) = DMap k1 s -> IO ()
- Reflex.Spider.Internal: type ResultM = EventM :: k -> Type -> Type
- Reflex.Spider.Internal: type SpiderEnv = SpiderTimeline :: k -> Type
- Reflex.Spider.Internal: updateMerge :: forall {k1} x k2 v (s :: k1 -> Type) p. (HasSpiderTimeline x, GCompare k2) => EventSubscribed x -> Merge x k2 v s -> MergeUpdateFunc k2 v x p s -> p -> SomeMergeUpdate x
- Reflex.Spider.Internal: updateSwitchHeight :: forall {k} (x :: k) a. Height -> SwitchSubscribed x a -> IO ()
- Reflex.Spider.Internal: wrap :: forall {k} m t (x :: k) a. MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
- Reflex.Spider.Internal: zeroHeight :: Height
- Reflex.Spider.Internal: zeroRef :: IORef Height
+ Data.WeakBag: isEmpty :: WeakBag a -> IO Bool
+ Data.WeakBag: traverseWeakIntMap_ :: forall a m. MonadIO m => IntMap (Weak a) -> (a -> m ()) -> m ()
+ Reflex.Spider.Height: coincidenceHeight :: Height -> Height -> Height
+ Reflex.Spider.Height: compareHeight :: Height -> Height -> Ordering
+ Reflex.Spider.Height: data Height
+ Reflex.Spider.Height: data HeightBag
+ Reflex.Spider.Height: data HeightQueue a
+ Reflex.Spider.Height: heightBagAddParent :: Height -> HeightBag -> HeightBag
+ Reflex.Spider.Height: heightBagEmpty :: HeightBag
+ Reflex.Spider.Height: heightBagHeight :: HeightBag -> Height
+ Reflex.Spider.Height: heightBagInvalidateParent :: Height -> HeightBag -> HeightBag
+ Reflex.Spider.Height: heightBagParentCount :: HeightBag -> Int
+ Reflex.Spider.Height: heightBagRecalculateParent :: Height -> HeightBag -> HeightBag
+ Reflex.Spider.Height: heightBagRemoveParent :: Height -> HeightBag -> HeightBag
+ Reflex.Spider.Height: heightBagSuccHeight :: HeightBag -> Height
+ Reflex.Spider.Height: heightQueueEmpty :: HeightQueue a
+ Reflex.Spider.Height: heightQueueInsert :: Height -> a -> HeightQueue a -> HeightQueue a
+ Reflex.Spider.Height: heightQueueNext :: HeightQueue a -> Maybe (Height, [a], HeightQueue a)
+ Reflex.Spider.Height: heightSlotPassed :: Height -> Height -> Bool
+ Reflex.Spider.Height: instance GHC.Classes.Eq Reflex.Spider.Height.HeightBag
+ Reflex.Spider.Height: instance GHC.Classes.Eq a => GHC.Classes.Eq (Reflex.Spider.Height.HeightQueue a)
+ Reflex.Spider.Height: instance GHC.Classes.Ord Reflex.Spider.Height.HeightBag
+ Reflex.Spider.Height: instance GHC.Classes.Ord a => GHC.Classes.Ord (Reflex.Spider.Height.HeightQueue a)
+ Reflex.Spider.Height: instance GHC.Read.Read Reflex.Spider.Height.HeightBag
+ Reflex.Spider.Height: instance GHC.Read.Read a => GHC.Read.Read (Reflex.Spider.Height.HeightQueue a)
+ Reflex.Spider.Height: instance GHC.Show.Show Reflex.Spider.Height.Height
+ Reflex.Spider.Height: instance GHC.Show.Show Reflex.Spider.Height.HeightBag
+ Reflex.Spider.Height: instance GHC.Show.Show a => GHC.Show.Show (Reflex.Spider.Height.HeightQueue a)
+ Reflex.Spider.Height: invalidHeight :: Height
+ Reflex.Spider.Height: invalidHeightBeingTraversed :: Height
+ Reflex.Spider.Height: isUnmarkedInvalidHeight :: Height -> Bool
+ Reflex.Spider.Height: maxHeight :: Height
+ Reflex.Spider.Height: pattern InvalidHeight :: Height
+ Reflex.Spider.Height: pattern ValidHeight :: Height
+ Reflex.Spider.Height: pattern ZeroHeight :: Height
+ Reflex.Spider.Height: raiseHeight :: Height -> Height -> Maybe Height
+ Reflex.Spider.Height: zeroHeight :: Height
+ Reflex.Spider.Internal: BehaviorEnv :: !Maybe (Weak (Invalidator x)) -> !Maybe (IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> BehaviorEnv (x :: k)
+ Reflex.Spider.Internal: EventNode :: {-# UNPACK #-} !IORef Height -> !IfDebugCycles (IO [EventNode x]) -> !IfDebugCycles (IO [String]) -> EventNode (x :: k)
+ Reflex.Spider.Internal: FanSubscribers :: IntMap (Weak (Subscriber x (v a))) -> FanSubscribers (x :: k) (v :: k1 -> Type) (a :: k1)
+ Reflex.Spider.Internal: HeadEStateInitial :: Event x a -> HeadEState (x :: k) a
+ Reflex.Spider.Internal: HeadEStateOccurred :: {-# UNPACK #-} !IORef (Maybe a) -> HeadEState (x :: k) a
+ Reflex.Spider.Internal: HeadEStateSubscribed :: !HeadESubscribed x a -> HeadEState (x :: k) a
+ Reflex.Spider.Internal: HeadESubscribed :: {-# UNPACK #-} !WeakBag (Subscriber x a) -> !EventSubscription x -> {-# UNPACK #-} !IORef (Maybe a) -> {-# NOUNPACK #-} !EventNode x -> HeadESubscribed (x :: k) a
+ Reflex.Spider.Internal: HoldLive :: Event x p -> !IORef (InvalidatorList x) -> !Maybe (EventSubscription x) -> HoldState (x :: k) p
+ Reflex.Spider.Internal: IntMapOf :: IntMap (v a) -> IntMapOf (a :: k) (v :: k -> Type)
+ Reflex.Spider.Internal: MergeChangeNotSubscribed :: MergeChangeSubscription (x :: k)
+ Reflex.Spider.Internal: MergeChangeSubscribed :: !EventSubscription x -> MergeChangeSubscription (x :: k)
+ Reflex.Spider.Internal: MergeChangeUnsubscribed :: MergeChangeSubscription (x :: k)
+ Reflex.Spider.Internal: RootKey :: {-# UNPACK #-} !Weak (RootSubscribed x a) -> {-# UNPACK #-} !MVar (Maybe (IO ())) -> RootKey (x :: k) a
+ Reflex.Spider.Internal: SomeRaisedCoincidence :: CoincidenceSubscribed x a -> SomeRaisedCoincidence (x :: k)
+ Reflex.Spider.Internal: SomeRecalculateHeight :: IO () -> SomeRecalculateHeight (x :: k)
+ Reflex.Spider.Internal: SubscribeResult :: EventSubscription x -> Maybe a -> SubscribeResult (x :: k) a
+ Reflex.Spider.Internal: SwitchLive :: !Behavior x (Event x a) -> !IORef [SomeBehaviorSubscribed x] -> !Weak (Invalidator x) -> !EventSubscription x -> SwitchState (x :: k) a
+ Reflex.Spider.Internal: SwitchParentUnsubscribed :: SwitchState (x :: k) a
+ Reflex.Spider.Internal: [_cacheSubscribed_nodeId] :: CacheSubscribed (x :: k) a -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [_eventSubscription_node] :: EventSubscription (x :: k) -> {-# NOUNPACK #-} !EventNode x
+ Reflex.Spider.Internal: [_eventSubscription_retained] :: EventSubscription (x :: k) -> {-# NOUNPACK #-} !Any :: Type
+ Reflex.Spider.Internal: [_spiderTimeline_depth] :: SpiderTimelineEnv' x -> {-# UNPACK #-} !TraceDepthRef
+ Reflex.Spider.Internal: [behaviorEnvHoldInits] :: BehaviorEnv (x :: k) -> IORef [SomeHoldInit x]
+ Reflex.Spider.Internal: [behaviorEnvInvalidator] :: BehaviorEnv (x :: k) -> !Maybe (Weak (Invalidator x))
+ Reflex.Spider.Internal: [behaviorEnvParents] :: BehaviorEnv (x :: k) -> !Maybe (IORef [SomeBehaviorSubscribed x])
+ Reflex.Spider.Internal: [coincidenceSubscribedNodeId] :: CoincidenceSubscribed (x :: k) a -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [coincidenceSubscribedNode] :: CoincidenceSubscribed (x :: k) a -> {-# NOUNPACK #-} !EventNode x
+ Reflex.Spider.Internal: [coincidenceSubscribedSubscriber] :: CoincidenceSubscribed (x :: k) a -> !Subscriber x a
+ Reflex.Spider.Internal: [eventEnvPendingRecalculations] :: EventEnv x -> !IORef [SomeRecalculateHeight x]
+ Reflex.Spider.Internal: [eventNodeGetParents] :: EventNode (x :: k) -> !IfDebugCycles (IO [EventNode x])
+ Reflex.Spider.Internal: [eventNodeHeightRef] :: EventNode (x :: k) -> {-# UNPACK #-} !IORef Height
+ Reflex.Spider.Internal: [eventNodeWhoCreated] :: EventNode (x :: k) -> !IfDebugCycles (IO [String])
+ Reflex.Spider.Internal: [fanSubscribedNextId] :: FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type) -> {-# UNPACK #-} !IORef Int
+ Reflex.Spider.Internal: [fanSubscribedNodeId] :: FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type) -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [headESubscribedNode] :: HeadESubscribed (x :: k) a -> {-# NOUNPACK #-} !EventNode x
+ Reflex.Spider.Internal: [headESubscribedOccurrence] :: HeadESubscribed (x :: k) a -> {-# UNPACK #-} !IORef (Maybe a)
+ Reflex.Spider.Internal: [headESubscribedParent] :: HeadESubscribed (x :: k) a -> !EventSubscription x
+ Reflex.Spider.Internal: [headESubscribedSubscribers] :: HeadESubscribed (x :: k) a -> {-# UNPACK #-} !WeakBag (Subscriber x a)
+ Reflex.Spider.Internal: [holdNodeId] :: Hold (x :: k) p -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [holdState] :: Hold (x :: k) p -> !IORef (HoldState x p)
+ Reflex.Spider.Internal: [pullNodeId] :: Pull (x :: k) a -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [rootKeySubscribed] :: RootKey (x :: k) a -> {-# UNPACK #-} !Weak (RootSubscribed x a)
+ Reflex.Spider.Internal: [rootKeyTeardown] :: RootKey (x :: k) a -> {-# UNPACK #-} !MVar (Maybe (IO ()))
+ Reflex.Spider.Internal: [rootNode] :: Root (x :: k) (k1 :: Type -> Type) -> {-# NOUNPACK #-} !EventNode x
+ Reflex.Spider.Internal: [rootSubscribedNodeId] :: RootSubscribed (x :: k) a -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [subscribeAndRead] :: Event (x :: k) a -> Subscriber x a -> EventM x (SubscribeResult x a)
+ Reflex.Spider.Internal: [subscribeOccurrence] :: SubscribeResult (x :: k) a -> Maybe a
+ Reflex.Spider.Internal: [subscribeSubscription] :: SubscribeResult (x :: k) a -> EventSubscription x
+ Reflex.Spider.Internal: [switchSubscribedNodeId] :: SwitchSubscribed (x :: k) a -> {-# UNPACK #-} !NodeId
+ Reflex.Spider.Internal: [switchSubscribedNode] :: SwitchSubscribed (x :: k) a -> {-# NOUNPACK #-} !EventNode x
+ Reflex.Spider.Internal: [switchSubscribedState] :: SwitchSubscribed (x :: k) a -> !IORef (SwitchState x a)
+ Reflex.Spider.Internal: [switchSubscribedSubscriber] :: SwitchSubscribed (x :: k) a -> !Subscriber x a
+ Reflex.Spider.Internal: cacheEventImpl :: HasSpiderTimeline x => Event x a -> Event x a
+ Reflex.Spider.Internal: checkRecordNotReleased :: String -> IORef (Maybe (Weak r)) -> (r -> Bool) -> IO ()
+ Reflex.Spider.Internal: class IsMap (map :: i -> Type -> Type) where {
+ Reflex.Spider.Internal: coincidenceSubscribedHeight :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> IORef Height
+ Reflex.Spider.Internal: coincidenceUncached :: HasSpiderTimeline x => Event x (Event (SpiderTimeline x) a) -> Event x a
+ Reflex.Spider.Internal: coincidenceUncachedImpl :: HasSpiderTimeline x => Event x (Event (SpiderTimeline x) a) -> Event x a
+ Reflex.Spider.Internal: composePush :: forall {k} b (x :: k) c a. (b -> EventM x (Maybe c)) -> (a -> EventM x (Maybe b)) -> a -> EventM x (Maybe c)
+ Reflex.Spider.Internal: data BehaviorEnv (x :: k)
+ Reflex.Spider.Internal: data EventNode (x :: k)
+ Reflex.Spider.Internal: data HeadEState (x :: k) a
+ Reflex.Spider.Internal: data HeadESubscribed (x :: k) a
+ Reflex.Spider.Internal: data HoldState (x :: k) p
+ Reflex.Spider.Internal: data MergeChangeSubscription (x :: k)
+ Reflex.Spider.Internal: data RootKey (x :: k) a
+ Reflex.Spider.Internal: data SomeBehaviorSubscribed (x :: k)
+ Reflex.Spider.Internal: data SomeRaisedCoincidence (x :: k)
+ Reflex.Spider.Internal: data SubscribeResult (x :: k) a
+ Reflex.Spider.Internal: data SwitchState (x :: k) a
+ Reflex.Spider.Internal: debugEnabled :: Bool
+ Reflex.Spider.Internal: debugFrame :: Bool
+ Reflex.Spider.Internal: debugOccurrence :: Applicative m => String -> Maybe a -> m ()
+ Reflex.Spider.Internal: deferRecalculateHeight :: HasSpiderTimeline x => SomeRecalculateHeight x -> IO ()
+ Reflex.Spider.Internal: eventSubscriptionHeight :: forall {k} (x :: k). EventSubscription x -> IO Height
+ Reflex.Spider.Internal: eventSubscriptionHeightRef :: forall {k} (x :: k). EventSubscription x -> IORef Height
+ Reflex.Spider.Internal: eventSubscriptionNever :: forall {k} (x :: k). EventSubscription x
+ Reflex.Spider.Internal: forgetMergeParentHeight :: forall {k} (x :: k). IORef HeightBag -> EventSubscription x -> IO ()
+ Reflex.Spider.Internal: genericMergeCheap :: forall {k} map v x p (s :: k -> Type). (HasSpiderTimeline x, IsMap map) => MergeGetSubscription x s -> MergeInitFunc map v (PatchTarget p) x s -> MergeUpdateFunc map v x p s -> DynamicS x p -> Event x (map v)
+ Reflex.Spider.Internal: getEventNodeHeight :: forall {k} (x :: k). EventNode x -> IO Height
+ Reflex.Spider.Internal: holdBehavior :: forall {k} (x :: k) m a. Defer (SomeHoldInit x) m => a -> Event x a -> m (Behavior x a)
+ Reflex.Spider.Internal: ifDebugCycles :: a -> IfDebugCycles a
+ Reflex.Spider.Internal: initMergeParents :: forall {k1} {k2} map q v (x :: k2) s. IsMap map => (forall (a :: k1). () => q a -> Event x (v a)) -> (forall (a :: k1). () => MapKey map a -> EventM x (EventM x (MapKey map a), EventSubscription x -> s a)) -> MergeInitFunc map v (map q) x s
+ Reflex.Spider.Internal: instance forall i (a :: i). Reflex.Spider.Internal.IsMap (Reflex.Spider.Internal.IntMapOf a)
+ Reflex.Spider.Internal: instance forall i (k :: i -> *). Data.GADT.Internal.GCompare k => Reflex.Spider.Internal.IsMap (Data.Dependent.Map.Internal.DMap k)
+ Reflex.Spider.Internal: invalidateBagHeight :: forall {k} (x :: k) a. WeakBag (Subscriber x a) -> Height -> IO ()
+ Reflex.Spider.Internal: invalidateCoincidenceSubscribers :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> Height -> IO ()
+ Reflex.Spider.Internal: invalidateOwnHeight :: IORef Height -> (Height -> IO ()) -> IO ()
+ Reflex.Spider.Internal: mapDeleteLookup :: forall (a :: i) v. IsMap map => MapKey map a -> map v -> (Maybe (v a), map v)
+ Reflex.Spider.Internal: mapEmpty :: forall (v :: i -> Type). IsMap map => map v
+ Reflex.Spider.Internal: mapForIntersection_ :: (IsMap map, Monad m) => map v -> map w -> (forall (a :: i). () => v a -> w a -> m ()) -> m ()
+ Reflex.Spider.Internal: mapFor_ :: (IsMap map, Monad m) => map v -> (forall (a :: i). () => v a -> m ()) -> m ()
+ Reflex.Spider.Internal: mapFromDistinctAscList :: forall (v :: i -> Type). IsMap map => [DSum (MapKey map) v] -> map v
+ Reflex.Spider.Internal: mapInsert :: forall (a :: i) v. IsMap map => MapKey map a -> v a -> map v -> map v
+ Reflex.Spider.Internal: mapInsertLookup :: forall (a :: i) v. IsMap map => MapKey map a -> v a -> map v -> (Maybe (v a), map v)
+ Reflex.Spider.Internal: mapInsertWith :: forall v (a :: i). IsMap map => (v a -> v a -> v a) -> MapKey map a -> v a -> map v -> map v
+ Reflex.Spider.Internal: mapLookup :: forall (a :: i) v. IsMap map => MapKey map a -> map v -> Maybe (v a)
+ Reflex.Spider.Internal: mapNull :: forall (v :: i -> Type). IsMap map => map v -> Bool
+ Reflex.Spider.Internal: mapSize :: forall (v :: i -> Type). IsMap map => map v -> Int
+ Reflex.Spider.Internal: mapToList :: forall (v :: i -> Type). IsMap map => map v -> [DSum (MapKey map) v]
+ Reflex.Spider.Internal: mapUpdate :: forall v (a :: i). IsMap map => (v a -> Maybe (v a)) -> MapKey map a -> map v -> map v
+ Reflex.Spider.Internal: mergeCheapImpl :: forall {k1} (k2 :: k1 -> Type) x q v. (HasSpiderTimeline x, GCompare k2) => (forall (a :: k1). () => q a -> Event x (v a)) -> DynamicS x (PatchDMap k2 q) -> Event x (DMap k2 v)
+ Reflex.Spider.Internal: mergeCheapWithMoveImpl :: forall {k1} (k2 :: k1 -> Type) x v q. (HasSpiderTimeline x, GCompare k2) => (forall (a :: k1). () => q a -> Event x (v a)) -> DynamicS x (PatchDMapWithMove k2 q) -> Event x (DMap k2 v)
+ Reflex.Spider.Internal: mergeIntCheapImpl :: HasSpiderTimeline x => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)
+ Reflex.Spider.Internal: mkEventNode :: forall {k} m (x :: k). MonadIO m => Height -> IO [EventNode x] -> IO [String] -> m (EventNode x)
+ Reflex.Spider.Internal: neverNode :: forall {k} (x :: k). EventNode x
+ Reflex.Spider.Internal: newFan :: forall {k1} {k2} (x :: k1) (map :: (k2 -> Type) -> Type) (v :: k2 -> Type). IO (Fan x map v)
+ Reflex.Spider.Internal: newNodeId :: IO NodeId
+ Reflex.Spider.Internal: newTraceDepthRef :: IO TraceDepthRef
+ Reflex.Spider.Internal: newtype Fan (x :: k) (map :: k1 -> Type -> Type) (v :: k1 -> Type)
+ Reflex.Spider.Internal: newtype FanSubscribers (x :: k) (v :: k1 -> Type) (a :: k1)
+ Reflex.Spider.Internal: newtype IntMapOf (a :: k) (v :: k -> Type)
+ Reflex.Spider.Internal: newtype SomeRecalculateHeight (x :: k)
+ Reflex.Spider.Internal: ownHeightSubscriber :: forall {k} a (x :: k). IORef Height -> (Height -> IO ()) -> (Height -> IO ()) -> (a -> EventM x ()) -> Subscriber x a
+ Reflex.Spider.Internal: printCallSite :: () -> IO ()
+ Reflex.Spider.Internal: pushCheapImpl :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b
+ Reflex.Spider.Internal: pushCoincidence :: HasSpiderTimeline x => (a -> EventM x (Maybe c)) -> Event x (Event (SpiderTimeline x) a) -> Event x c
+ Reflex.Spider.Internal: pushMergeG :: forall {k1} (k2 :: k1 -> Type) q x v c. (HasSpiderTimeline x, GCompare k2) => (DMap k2 v -> EventM x (Maybe c)) -> (forall (a :: k1). () => q a -> Event x (v a)) -> DynamicS x (PatchDMap k2 q) -> Event x c
+ Reflex.Spider.Internal: pushMergeInt :: HasSpiderTimeline x => (IntMap a -> EventM x (Maybe b)) -> DynamicS x (PatchIntMap (Event x a)) -> Event x b
+ Reflex.Spider.Internal: pushMergeWithMove :: forall {k1} (k2 :: k1 -> Type) q x v c. (HasSpiderTimeline x, GCompare k2) => (DMap k2 v -> EventM x (Maybe c)) -> (forall (a :: k1). () => q a -> Event x (v a)) -> DynamicS x (PatchDMapWithMove k2 q) -> Event x c
+ Reflex.Spider.Internal: pushSwitch :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Behavior x (Event x a) -> Event x b
+ Reflex.Spider.Internal: recalculateBagHeight :: forall {k} (x :: k) a. WeakBag (Subscriber x a) -> Height -> IO ()
+ Reflex.Spider.Internal: recalculateCoincidenceSubscribers :: forall {k} (x :: k) a. CoincidenceSubscribed x a -> Height -> IO ()
+ Reflex.Spider.Internal: recalculateOwnHeight :: IORef Height -> (Height -> IO ()) -> IO Height -> IO ()
+ Reflex.Spider.Internal: runPendingRecalculations :: EventEnv x -> IO ()
+ Reflex.Spider.Internal: setOccurrence :: HasSpiderTimeline x => String -> IORef (Maybe a) -> a -> EventM x ()
+ Reflex.Spider.Internal: spiderEventEnv :: HasSpiderTimeline x => EventEnv x
+ Reflex.Spider.Internal: subscribeAndReadRoot :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Subscriber x a -> IO (SubscribeResult x a)
+ Reflex.Spider.Internal: subscribeCached :: forall {k} r (x :: k) b. IORef (Maybe (Weak r)) -> String -> EventM x r -> (r -> EventM x (SubscribeResult x b)) -> EventM x (SubscribeResult x b)
+ Reflex.Spider.Internal: subscribeMergeParent :: forall {k} (x :: k) a. IORef HeightBag -> Event x a -> Subscriber x a -> EventM x (SubscribeResult x a)
+ Reflex.Spider.Internal: subscribeSwitchCurrentParent :: forall {k} (x :: k) a. SwitchSubscribed x a -> Behavior x (Event x a) -> IORef [SomeBehaviorSubscribed x] -> IORef [SomeHoldInit x] -> (Event x a -> Subscriber x a -> IO (SubscribeResult x a)) -> IO (SubscribeResult x a)
+ Reflex.Spider.Internal: switchSubscribedHeight :: forall {k} (x :: k) a. SwitchSubscribed x a -> IORef Height
+ Reflex.Spider.Internal: switchUncached :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
+ Reflex.Spider.Internal: switchUncachedImpl :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a
+ Reflex.Spider.Internal: throwEventLoopException :: forall {k} (x :: k) a. EventNode x -> IO a
+ Reflex.Spider.Internal: trackRead :: forall {k} (x :: k). IORef (InvalidatorList x) -> SomeBehaviorSubscribed x -> BehaviorM x ()
+ Reflex.Spider.Internal: type IfDebugCycles (a :: k) = ()
+ Reflex.Spider.Internal: type MapKey (map :: i -> Type -> Type) :: i -> Type;
+ Reflex.Spider.Internal: type NodeId = ()
+ Reflex.Spider.Internal: type TraceDepthRef = ()
+ Reflex.Spider.Internal: type family MapKey (map :: i -> Type -> Type) :: i -> Type
+ Reflex.Spider.Internal: updateMergeParents :: forall {k1} {k2} map q v (x :: k2). IsMap map => (forall (a :: k1). () => q a -> Event x (v a)) -> MergeUpdateFunc map v x (map (ComposeMaybe q)) (MergeSubscribedParent x :: k1 -> Type)
+ Reflex.Spider.Internal: withStackOneLine :: (() -> a) -> a
+ Reflex.Spider.Internal: }
- Data.WeakBag: insert :: a -> WeakBag a -> IORef (Weak b) -> (b -> IO ()) -> IO WeakBagTicket
+ Data.WeakBag: insert :: a -> WeakBag a -> IO WeakBagTicket
- Data.WeakBag: traverse_ :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()
+ Data.WeakBag: traverse_ :: forall a m. MonadIO m => WeakBag a -> (a -> m ()) -> m ()
- Reflex.EventWriter.Base: EventWriterT :: StateT (EventWriterState t w) m a -> EventWriterT t w (m :: Type -> Type) a
+ Reflex.EventWriter.Base: EventWriterT :: StateT [Event t w] m a -> EventWriterT t w (m :: Type -> Type) a
- Reflex.EventWriter.Base: [unEventWriterT] :: EventWriterT t w (m :: Type -> Type) a -> StateT (EventWriterState t w) m a
+ Reflex.EventWriter.Base: [unEventWriterT] :: EventWriterT t w (m :: Type -> Type) a -> StateT [Event t w] m a
- Reflex.Spider.Internal: BehaviorSubscribedHold :: Hold x p -> BehaviorSubscribed (x :: k) a
+ Reflex.Spider.Internal: BehaviorSubscribedHold :: Hold x p -> SomeBehaviorSubscribed (x :: k)
- Reflex.Spider.Internal: BehaviorSubscribedPull :: PullSubscribed x a -> BehaviorSubscribed (x :: k) a
+ Reflex.Spider.Internal: BehaviorSubscribedPull :: PullSubscribed x a -> SomeBehaviorSubscribed (x :: k)
- Reflex.Spider.Internal: CacheSubscribed :: {-# UNPACK #-} !FastWeakBag (Subscriber x a) -> {-# UNPACK #-} !EventSubscription x -> {-# UNPACK #-} !IORef (Maybe a) -> CacheSubscribed (x :: k) a
+ Reflex.Spider.Internal: CacheSubscribed :: {-# UNPACK #-} !WeakBag (Subscriber x a) -> {-# UNPACK #-} !EventSubscription x -> {-# UNPACK #-} !IORef (Maybe a) -> {-# UNPACK #-} !NodeId -> CacheSubscribed (x :: k) a
- Reflex.Spider.Internal: CoincidenceSubscribed :: !IORef (Maybe (CoincidenceSubscribed x a)) -> !IORef (Maybe a) -> !WeakBag (Subscriber x a) -> !IORef Height -> {-# NOUNPACK #-}Subscriber x (Event x a) -> !EventSubscription x -> !IORef (Maybe (EventSubscribed x)) -> !IORef (Weak (CoincidenceSubscribed x a)) -> CoincidenceSubscribed (x :: k) a
+ Reflex.Spider.Internal: CoincidenceSubscribed :: {-# NOUNPACK #-} !EventNode x -> !Subscriber x a -> !IORef (Maybe (EventSubscription x)) -> !IORef (Maybe (EventNode x)) -> {-# UNPACK #-} !NodeId -> CoincidenceSubscribed (x :: k) a
- Reflex.Spider.Internal: Event :: (Subscriber x a -> EventM x (EventSubscription x, Maybe a)) -> Event (x :: k) a
+ Reflex.Spider.Internal: Event :: (Subscriber x a -> EventM x (SubscribeResult x a)) -> Event (x :: k) a
- Reflex.Spider.Internal: EventEnv :: !IORef [SomeAssignment x] -> !IORef [SomeHoldInit x] -> !IORef [SomeDynInit x] -> !IORef [SomeMergeUpdate x] -> !IORef [SomeMergeInit x] -> !IORef [Some Clear] -> !IORef [Some IntClear] -> !IORef [Some RootClear] -> !IORef Height -> !IORef [SomeResetCoincidence x] -> !IORef [SomeCoincidenceSubscribed x] -> !IORef (IntMap [EventM x ()]) -> EventEnv x
+ Reflex.Spider.Internal: EventEnv :: !IORef [SomeAssignment x] -> !IORef [SomeHoldInit x] -> !IORef [SomeDynInit x] -> !IORef [SomeMergeUpdate x] -> !IORef [SomeMergeInit x] -> !IORef [Some Clear] -> !IORef [Some RootClear] -> !IORef Height -> !IORef [SomeResetCoincidence x] -> !IORef [SomeRecalculateHeight x] -> !IORef (HeightQueue (EventM x ())) -> EventEnv x
- Reflex.Spider.Internal: EventSubscription :: !IO () -> {-# UNPACK #-} !EventSubscribed x -> EventSubscription (x :: k)
+ Reflex.Spider.Internal: EventSubscription :: !IO () -> {-# NOUNPACK #-} !Any :: Type -> {-# NOUNPACK #-} !EventNode x -> EventSubscription (x :: k)
- Reflex.Spider.Internal: Fan :: !Event x (DMap k2 v) -> !IORef (Maybe (FanSubscribed x k2 v)) -> Fan (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type)
+ Reflex.Spider.Internal: Fan :: IORef (Maybe (Weak (FanSubscribed x map v))) -> Fan (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type)
- Reflex.Spider.Internal: FanSubscribed :: !IORef (Maybe (FanSubscribed x k2 v)) -> !IORef (Maybe (DMap k2 v)) -> !IORef (DMap k2 (FanSubscribedChildren x k2 v)) -> !EventSubscription x -> FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type)
+ Reflex.Spider.Internal: FanSubscribed :: {-# UNPACK #-} !IORef (map (FanSubscribers x v)) -> {-# UNPACK #-} !IORef Int -> {-# UNPACK #-} !IORef (Maybe (map v)) -> {-# UNPACK #-} !EventSubscription x -> {-# UNPACK #-} !NodeId -> FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type)
- Reflex.Spider.Internal: Hold :: !IORef (PatchTarget p) -> !IORef (InvalidatorList x) -> Event x p -> !IORef (Maybe (EventSubscription x)) -> Hold (x :: k) p
+ Reflex.Spider.Internal: Hold :: !IORef (PatchTarget p) -> !IORef (HoldState x p) -> {-# UNPACK #-} !NodeId -> Hold (x :: k) p
- Reflex.Spider.Internal: HoldDyn :: !Hold x p -> DynType (x :: k) p
+ Reflex.Spider.Internal: HoldDyn :: {-# NOUNPACK #-} !Hold x p -> DynType (x :: k) p
- Reflex.Spider.Internal: Pull :: !IORef (Maybe (PullSubscribed x a)) -> !BehaviorM x a -> Pull (x :: k) a
+ Reflex.Spider.Internal: Pull :: !IORef (Maybe (PullSubscribed x a)) -> !BehaviorM x a -> {-# UNPACK #-} !NodeId -> Pull (x :: k) a
- Reflex.Spider.Internal: ReadPhase :: ResultM x a -> ReadPhase (x :: k) a
+ Reflex.Spider.Internal: ReadPhase :: EventM x a -> ReadPhase (x :: k) a
- Reflex.Spider.Internal: Root :: !IORef (DMap k1 Identity) -> !IORef (DMap k1 (RootSubscribed x)) -> !forall a. () => k1 a -> RootTrigger x a -> IO (IO ()) -> Root (x :: k) (k1 :: Type -> Type)
+ Reflex.Spider.Internal: Root :: !IORef (DMap k1 Identity) -> !IORef (DMap k1 (RootKey x)) -> !forall a. () => k1 a -> RootTrigger x a -> IO (IO ()) -> {-# NOUNPACK #-} !EventNode x -> Root (x :: k) (k1 :: Type -> Type)
- Reflex.Spider.Internal: RootSubscribed :: !k1 a -> !IORef (DMap k1 (RootSubscribed x)) -> !WeakBag (Subscriber x a) -> !IO (Maybe a) -> IO () -> !IORef (Weak (RootSubscribed x a)) -> RootSubscribed (x :: k) a
+ Reflex.Spider.Internal: RootSubscribed :: {-# UNPACK #-} !WeakBag (Subscriber x a) -> {-# UNPACK #-} !NodeId -> RootSubscribed (x :: k) a
- Reflex.Spider.Internal: SpiderPushM :: ComputeM x a -> SpiderPushM x a
+ Reflex.Spider.Internal: SpiderPushM :: EventM x a -> SpiderPushM x a
- Reflex.Spider.Internal: SpiderTimelineEnv :: {-# UNPACK #-} !MVar () -> {-# UNPACK #-} !EventEnv x -> SpiderTimelineEnv' x
+ Reflex.Spider.Internal: SpiderTimelineEnv :: {-# UNPACK #-} !MVar () -> {-# UNPACK #-} !EventEnv x -> {-# UNPACK #-} !TraceDepthRef -> SpiderTimelineEnv' x
- Reflex.Spider.Internal: SwitchSubscribed :: !IORef (Maybe (SwitchSubscribed x a)) -> !IORef (Maybe a) -> !IORef Height -> !WeakBag (Subscriber x a) -> {-# NOUNPACK #-} !Invalidator x -> !IORef (Weak (Invalidator x)) -> !IORef [SomeBehaviorSubscribed x] -> !Behavior x (Event x a) -> !IORef (EventSubscription x) -> !IORef (Weak (SwitchSubscribed x a)) -> SwitchSubscribed (x :: k) a
+ Reflex.Spider.Internal: SwitchSubscribed :: {-# NOUNPACK #-} !EventNode x -> !Subscriber x a -> !IORef (Invalidator x) -> !IORef (SwitchState x a) -> {-# UNPACK #-} !NodeId -> SwitchSubscribed (x :: k) a
- Reflex.Spider.Internal: [_cacheSubscribed_subscribers] :: CacheSubscribed (x :: k) a -> {-# UNPACK #-} !FastWeakBag (Subscriber x a)
+ Reflex.Spider.Internal: [_cacheSubscribed_subscribers] :: CacheSubscribed (x :: k) a -> {-# UNPACK #-} !WeakBag (Subscriber x a)
- Reflex.Spider.Internal: [coincidenceSubscribedInnerParent] :: CoincidenceSubscribed (x :: k) a -> !IORef (Maybe (EventSubscribed x))
+ Reflex.Spider.Internal: [coincidenceSubscribedInnerParent] :: CoincidenceSubscribed (x :: k) a -> !IORef (Maybe (EventNode x))
- Reflex.Spider.Internal: [coincidenceSubscribedOuterParent] :: CoincidenceSubscribed (x :: k) a -> !EventSubscription x
+ Reflex.Spider.Internal: [coincidenceSubscribedOuterParent] :: CoincidenceSubscribed (x :: k) a -> !IORef (Maybe (EventSubscription x))
- Reflex.Spider.Internal: [eventEnvDelayedMerges] :: EventEnv x -> !IORef (IntMap [EventM x ()])
+ Reflex.Spider.Internal: [eventEnvDelayedMerges] :: EventEnv x -> !IORef (HeightQueue (EventM x ()))
- Reflex.Spider.Internal: [fanSubscribedOccurrence] :: FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !IORef (Maybe (DMap k2 v))
+ Reflex.Spider.Internal: [fanSubscribedOccurrence] :: FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type) -> {-# UNPACK #-} !IORef (Maybe (map v))
- Reflex.Spider.Internal: [fanSubscribedParent] :: FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !EventSubscription x
+ Reflex.Spider.Internal: [fanSubscribedParent] :: FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type) -> {-# UNPACK #-} !EventSubscription x
- Reflex.Spider.Internal: [fanSubscribedSubscribers] :: FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type) -> !IORef (DMap k2 (FanSubscribedChildren x k2 v))
+ Reflex.Spider.Internal: [fanSubscribedSubscribers] :: FanSubscribed (x :: k) (map :: (k1 -> Type) -> Type) (v :: k1 -> Type) -> {-# UNPACK #-} !IORef (map (FanSubscribers x v))
- Reflex.Spider.Internal: [rootSubscribedSubscribers] :: RootSubscribed (x :: k) a -> !WeakBag (Subscriber x a)
+ Reflex.Spider.Internal: [rootSubscribedSubscribers] :: RootSubscribed (x :: k) a -> {-# UNPACK #-} !WeakBag (Subscriber x a)
- Reflex.Spider.Internal: [rootSubscribed] :: Root (x :: k) (k1 :: Type -> Type) -> !IORef (DMap k1 (RootSubscribed x))
+ Reflex.Spider.Internal: [rootSubscribed] :: Root (x :: k) (k1 :: Type -> Type) -> !IORef (DMap k1 (RootKey x))
- Reflex.Spider.Internal: [switchSubscribedOwnInvalidator] :: SwitchSubscribed (x :: k) a -> {-# NOUNPACK #-} !Invalidator x
+ Reflex.Spider.Internal: [switchSubscribedOwnInvalidator] :: SwitchSubscribed (x :: k) a -> !IORef (Invalidator x)
- Reflex.Spider.Internal: checkCycle :: forall {k} (x :: k). EventSubscribed x -> EventM x ()
+ Reflex.Spider.Internal: checkCycle :: HasSpiderTimeline x => EventNode x -> EventM x ()
- Reflex.Spider.Internal: coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a
+ Reflex.Spider.Internal: coincidence :: HasSpiderTimeline x => Event x (Event (SpiderTimeline x) a) -> Event x a
- Reflex.Spider.Internal: data FanSubscribed (x :: k) (k2 :: k1 -> Type) (v :: k1 -> Type)
+ Reflex.Spider.Internal: data FanSubscribed (x :: k) (map :: k1 -> Type -> Type) (v :: k1 -> Type)
- Reflex.Spider.Internal: debugSubscriber :: forall {k} (x :: k) a. String -> Subscriber x a -> IO (Subscriber x a)
+ Reflex.Spider.Internal: debugSubscriber :: forall {k} (x :: k) a. String -> Subscriber x a -> Subscriber x a
- Reflex.Spider.Internal: eventFan :: forall {k1} k2 x (a :: k1) v. (GCompare k2, HasSpiderTimeline x) => k2 a -> Fan x k2 v -> Event x (v a)
+ Reflex.Spider.Internal: eventFan :: forall {k} x map v (a :: k). (HasSpiderTimeline x, IsMap map) => MapKey map a -> Event x (map v) -> Fan x map v -> Event x (v a)
- Reflex.Spider.Internal: getCurrentHeight :: HasCurrentHeight x m => m Height
+ Reflex.Spider.Internal: getCurrentHeight :: HasSpiderTimeline x => EventM x Height
- Reflex.Spider.Internal: headE :: forall {k} (x :: k) m a. Defer (SomeMergeInit x) m => Event x a -> m (Event x a)
+ Reflex.Spider.Internal: headE :: (HasSpiderTimeline x, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)
- Reflex.Spider.Internal: newSubscriberCoincidenceInner :: HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)
+ Reflex.Spider.Internal: newSubscriberCoincidenceInner :: HasSpiderTimeline x => CoincidenceSubscribed x a -> Subscriber x a
- Reflex.Spider.Internal: newSubscriberCoincidenceOuter :: HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
+ Reflex.Spider.Internal: newSubscriberCoincidenceOuter :: HasSpiderTimeline x => CoincidenceSubscribed x b -> Subscriber x (Event x b)
- Reflex.Spider.Internal: propagate :: forall {k} (x :: k) a. a -> WeakBag (Subscriber x a) -> EventM x ()
+ Reflex.Spider.Internal: propagate :: HasSpiderTimeline x => a -> WeakBag (Subscriber x a) -> EventM x ()
- Reflex.Spider.Internal: push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
+ Reflex.Spider.Internal: push :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b
- Reflex.Spider.Internal: pushCheap :: forall {k} a (x :: k) b. (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
+ Reflex.Spider.Internal: pushCheap :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b
- Reflex.Spider.Internal: run :: HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
+ Reflex.Spider.Internal: run :: HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> EventM x b -> SpiderHost x b
- Reflex.Spider.Internal: runBehaviorM :: forall {k} (x :: k) a. BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
+ Reflex.Spider.Internal: runBehaviorM :: forall {k} (x :: k) a. BehaviorM x a -> BehaviorEnv x -> IO a
- Reflex.Spider.Internal: scheduleMerge :: HasCurrentHeight x m => Height -> EventM x () -> m ()
+ Reflex.Spider.Internal: scheduleMerge :: HasSpiderTimeline x => Height -> EventM x () -> EventM x ()
- Reflex.Spider.Internal: showNodeId' :: Int -> String
+ Reflex.Spider.Internal: showNodeId' :: NodeId -> String
- Reflex.Spider.Internal: subscribeAndReadNever :: forall {k} (x :: k) a. EventM x (EventSubscription x, Maybe a)
+ Reflex.Spider.Internal: subscribeAndReadNever :: forall {k} (x :: k) a. EventM x (SubscribeResult x a)
- Reflex.Spider.Internal: subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)
+ Reflex.Spider.Internal: subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Maybe Height, EventNode x)
- Reflex.Spider.Internal: subscribeHoldEvent :: forall {k} (x :: k) p. Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)
+ Reflex.Spider.Internal: subscribeHoldEvent :: forall {k} (x :: k) p. Hold x p -> Subscriber x p -> EventM x (SubscribeResult x p)
- Reflex.Spider.Internal: type MergeInitFunc (k2 :: k -> Type) (v :: k -> Type) (q :: k -> Type) (x :: k1) (s :: k -> Type) = DMap k2 q -> forall (a :: k). () => EventM x k2 a -> Subscriber x v a -> EventM x (DMap k2 v, [Height], DMap k2 s)
+ Reflex.Spider.Internal: type MergeInitFunc (map :: k -> Type -> Type) (v :: k -> Type) t (x :: k1) (s :: k -> Type) = t -> forall (a :: k). () => EventM x MapKey map a -> Subscriber x v a -> IORef HeightBag -> EventM x (map v, map s)

Files

ChangeLog.md view
@@ -1,5 +1,49 @@ # Revision history for reflex +## 0.10.0.0++### Breaking changes+Not expected to affect any user code:++* The modules `Reflex.FastWeak` and `Data.FastWeakBag` and the `fast-weak` cabal flag are removed. On GHCJS, Spider now always uses `System.Mem.Weak`.+* `Data.WeakBag`: `insert` no longer takes a weak reference and a callback, `singleton` and `_weakBag_children` are removed, and `isEmpty` and `traverseWeakIntMap_` are new.+* Many changes to `Reflex.Spider.Internal`. The height code moved to the new module `Reflex.Spider.Height`.+* `EventWriterT` now wraps `StateT [Event t w] m`.+* The deprecated type synonym `SpiderEnv` is removed. Use `SpiderTimeline` instead.++### Deprecations++* `mergeIntMap` and `mergeIntMapIncremental` are deprecated in favour of `mergeInt` and `mergeIntIncremental` ([#537](https://github.com/reflex-frp/reflex/pull/537)).++### Fixes++* Fix a space leak in `fanInt`: it stayed subscribed to its parent for as long as its `EventSelectorInt` was retained. `fan` and `fanInt` now share one implementation ([#554](https://github.com/reflex-frp/reflex/pull/554)).+* Fix `cacheEvent` storing a thunk instead of a weak reference, which kept its subscription alive until the thunk was evaluated ([#552](https://github.com/reflex-frp/reflex/pull/552)).+* `newFanEventWithTrigger` can now fire multiple keys in one frame ([#555](https://github.com/reflex-frp/reflex/pull/555)).+* Fix incremental merges not initializing the holds and merges that are created when a patch adds a parent ([#552](https://github.com/reflex-frp/reflex/pull/552)).+* `merge` and the other `DMap` merges now check for causality loops on every parent occurrence, not only on the first one in a frame ([#556](https://github.com/reflex-frp/reflex/pull/556)).+* Fix races between the finalizer thread and the frame thread in root events.+* Fix lost occurrences in `TriggerEventT`'s `newEventWithLazyTriggerWithOnComplete`: an occurrence queued before the event was torn down and set up again didn't reach the new subscribers.+* Fix a race between the finalizer thread and the frame thread in `fan`: the per-key subscriber map is now updated atomically.+* Fix a race in `switch`: if a finalizer unsubscribed a switch during a frame, the switch still subscribed to its new parent and unsubscribed from its old parent twice.+* Incremental merges no longer subscribe to new parents from patches after they are unsubscribed.+* Correct the `Dynamic` `Monad` instance in `Reflex.Pure` ([#549](https://github.com/reflex-frp/reflex/pull/549)).++### Improvements++* All event nodes in Spider are now garbage collected together with the last subscriber instead of being unsubscribed by a finalizer.+* Spider now has its own `headE` implementation instead of using `slowHeadE` ([#546](https://github.com/reflex-frp/reflex/pull/546)).+* Reconnecting switches at the end of a frame does less work ([#548](https://github.com/reflex-frp/reflex/pull/548)).+* `EventWriterT` now uses `mergeInt`, which is more efficient ([#539](https://github.com/reflex-frp/reflex/pull/539)).+* All Spider merges now share one implementation, and a merge only invalidates its subscribers' heights when its own height changes ([#556](https://github.com/reflex-frp/reflex/pull/556)).+* Wide int-based merges no longer take quadratic time when all their parents change height.+* Rewrite RULES are rewritten and more comprehensive ([#556](https://github.com/reflex-frp/reflex/pull/556)).+* Spider's `ReflexHost`, `MonadReflexHost`, `MonadSample` and `MonadHold` instances are now specialized at `Global` ([#555](https://github.com/reflex-frp/reflex/pull/555)).+* With GHC 9.12 and later, reflex is built with `-fexpose-overloaded-unfoldings`, so its overloaded functions can be specialized in user code ([#556](https://github.com/reflex-frp/reflex/pull/556)).+* Smaller optimizations in fans, holds, weak bags, height bags, merges and `cacheEvent`.+* New `debug-frame` cabal flag guarding frame invariants, for use during development or debugging, or simply as extra precaution ([#551](https://github.com/reflex-frp/reflex/pull/551)).+* Support for GHC 9.14 by @ymeister in [#528](https://github.com/reflex-frp/reflex/pull/528).+ ## 0.9.4.1  * Bug fix for `CausalityLoopException`s caused by incorrect coincidence and merge height invalidation by @parenthetical in [#536](https://github.com/reflex-frp/reflex/pull/536).
Setup.hs view
@@ -1,2 +1,3 @@ import Distribution.Simple+ main = defaultMain
bench/Main.hs view
@@ -3,7 +3,6 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-}- -- The instance for NFData (TVar a) is an orphan, but necessary here {-# OPTIONS_GHC -fno-warn-orphans #-} @@ -13,21 +12,22 @@ import Control.DeepSeq import Control.Exception (evaluate) import Control.Monad-import Control.Monad.Identity import Control.Monad.IO.Class+import Control.Monad.Identity import Criterion.Main import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap import Data.Dependent.Sum import Data.Functor.Misc import Data.IORef-import Data.Maybe (fromJust)+ import Reflex import Reflex.Host.Class  main :: IO ()-main = defaultMain-  [ bgroup "micro" micros ]+main =+  defaultMain+    [bgroup "micro" micros]  instance NFData (TVar a) where   rnf x = seq x ()@@ -50,57 +50,85 @@   , env (newIORef (42 :: Int)) (bench "readIORef" . whnfIO . readIORef)   , bench "newTVar" $ whnfIO $ void $ newTVarIO ()   , env (newTVarIO (42 :: Int)) (bench "readTVar" . whnfIO . readTVarIO)-  , bench "newEventWithTrigger" $ whnfIO . void $ runSpiderHost $ newEventWithTrigger $-      \trigger -> return () <$ evaluate trigger+  , bench "newEventWithTrigger" $+      whnfIO . void $+        runSpiderHost $+          newEventWithTrigger $+            \trigger -> return () <$ evaluate trigger   , bench "newEventWithTriggerRef" $ whnfIO . void $ runSpiderHost newEventWithTriggerRef   , withSetupWHNF "subscribeEvent" newEventWithTriggerRef $ subscribeEvent . fst-  , withSetupWHNF "subscribeSwitch"-    (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)-    (subscribeEvent . switch)-  , withSetupWHNF "subscribeMerge(1)" (setupMerge 1) $ \(ev,_) -> subscribeEvent ev-  , withSetupWHNF "subscribeMerge(100)" (setupMerge 100) (subscribeEvent . fst)-  , withSetupWHNF "subscribeMerge(10000)" (setupMerge 10000) (subscribeEvent . fst)+  , withSetupWHNF+      "subscribeSwitch"+      (join $ hold <$> fmap fst newEventWithTriggerRef <*> fmap fst newEventWithTriggerRef)+      (subscribeEvent . switch)+  , bench "subscribeMerge(1)" $ subscribeMergeBuild 1+  , bench "subscribeMerge(100)" $ subscribeMergeBuild 100+  , bench "subscribeMerge(10000)" $ subscribeMergeBuild 10000   , bench "runHostFrame" $ whnfIO $ runSpiderHost $ runHostFrame $ return ()-  , withSetupWHNF "fireEventsAndRead(single/single)"-    (newEventWithTriggerRef >>= subscribePair)-    (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)-  , withSetupWHNF "fireEventsOnly"-    (newEventWithTriggerRef >>= subscribePair)-    (\(_, trigger) -> do-        key <- fromJust <$> liftIO (readIORef trigger)-        fireEvents [key :=> Identity (42 :: Int)])-  , withSetupWHNF "fireEventsAndRead(head/merge1)"-    (setupMerge 1 >>= subscribePair)-    (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)-  , withSetupWHNF "fireEventsAndRead(head/merge100)"-    (setupMerge 100 >>= subscribePair)-    (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)-  , withSetupWHNF "fireEventsAndRead(head/merge10000)"+  , withSetupWHNF+      "fireEventsAndRead(single/single)"+      (newEventWithTriggerRef >>= subscribePair)+      (\(subd, trigger) -> fireAndRead trigger (42 :: Int) subd)+  , withSetupWHNF+      "fireEventsOnly"+      (newEventWithTriggerRef >>= subscribePair)+      ( \(_, trigger) -> do+          Just key <- liftIO (readIORef trigger)+          fireEvents [key :=> Identity (42 :: Int)]+      )+  , withSetupWHNF+      "fireEventsAndRead(head/merge1)"+      (setupMerge 1 >>= subscribePair)+      (\(subd, triggers) -> fireAndRead (firstTrigger triggers) (42 :: Int) subd)+  , withSetupWHNF+      "fireEventsAndRead(head/merge100)"+      (setupMerge 100 >>= subscribePair)+      (\(subd, triggers) -> fireAndRead (firstTrigger triggers) (42 :: Int) subd)+  , withSetupWHNF+      "fireEventsAndRead(head/merge10000)"       (setupMerge 10000 >>= subscribePair)-      (\(subd, t:_) -> fireAndRead t (42 :: Int) subd)-  , withSetupWHNF "fireEventsOnly(head/merge100)"-    (setupMerge 100 >>= subscribePair)-    (\(_, t:_) -> do-        key <- fromJust <$> liftIO (readIORef t)-        fireEvents [key :=> Identity (42 :: Int)])+      (\(subd, triggers) -> fireAndRead (firstTrigger triggers) (42 :: Int) subd)+  , withSetupWHNF+      "fireEventsOnly(head/merge100)"+      (setupMerge 100 >>= subscribePair)+      ( \(_, triggers) -> do+          Just key <- liftIO (readIORef (firstTrigger triggers))+          fireEvents [key :=> Identity (42 :: Int)]+      )   , withSetupWHNF "hold" newEventWithTriggerRef $ \(ev, _) -> hold (42 :: Int) ev   , withSetupWHNF "sample" (newEventWithTriggerRef >>= hold (42 :: Int) . fst) sample+  , withSetupWHNF "headE" newEventWithTriggerRef $ \(ev, _) -> runHostFrame (headE ev)+  , withSetupWHNF "subscribeHeadE" (newEventWithTriggerRef >>= runHostFrame . headE . fst) subscribeEvent   ] -setupMerge :: Int-           -> SpiderHost Global ( Event (SpiderTimeline Global) (DMap (Const2 Int a) Identity)-                                , [IORef (Maybe (EventTrigger Spider a))]-                                )+setupMerge+  :: Int+  -> SpiderHost+       Global+       ( Event (SpiderTimeline Global) (DMap (Const2 Int a) Identity)+       , [IORef (Maybe (EventTrigger Spider a))]+       ) setupMerge num = do   (evs, triggers) <- unzip <$> replicateM num newEventWithTriggerRef-  let !m = DMap.fromList [Const2 i :=> v | (i,v) <- zip [0..] evs]+  let !m = DMap.fromList [Const2 i :=> v | (i, v) <- zip [0 ..] evs]   pure (merge m, triggers) +firstTrigger :: [trigger] -> trigger+firstTrigger (trigger : _) = trigger+firstTrigger [] = error "firstTrigger: setupMerge created no events"++subscribeMergeBuild :: Int -> Benchmarkable+subscribeMergeBuild n = perRunEnv (WHNF . fst <$> runSpiderHost (setupMerge n)) $+  \(WHNF ev) -> WHNF <$> runSpiderHost (runHostFrame (subscribeEvent ev))+ subscribePair :: (Event (SpiderTimeline Global) a, b) -> SpiderHost Global (EventHandle (SpiderTimeline Global) a, b) subscribePair (ev, b) = (,b) <$> subscribeEvent ev -fireAndRead :: IORef (Maybe (EventTrigger (SpiderTimeline Global) a)) -> a -> EventHandle (SpiderTimeline Global) b-            -> SpiderHost Global (Maybe b)+fireAndRead+  :: IORef (Maybe (EventTrigger (SpiderTimeline Global) a))+  -> a+  -> EventHandle (SpiderTimeline Global) b+  -> SpiderHost Global (Maybe b) fireAndRead trigger val subd = do-  key <- fromJust <$> liftIO (readIORef trigger)+  Just key <- liftIO (readIORef trigger)   fireEventsAndRead [key :=> Identity val] $ readEvent subd >>= sequence
bench/RunAll.hs view
@@ -11,59 +11,50 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-}-{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-}  module Main where -import Criterion.Main-import Criterion.Types--import Reflex-import Reflex.Host.Class--import Reflex.Plan.Reflex-import Reflex.TestPlan--import qualified Reflex.Bench.Focused as Focused-import Reflex.Spider.Internal (SpiderEventHandle)- import Control.Applicative-import Control.DeepSeq (NFData (..))--import Prelude-import System.IO-import System.Mem- import Control.Arrow import Control.Concurrent import Control.Concurrent.STM+import Control.DeepSeq (NFData (..)) import Control.Exception import Control.Monad import Control.Monad.Trans+import Criterion.Main+import Criterion.Types import Data.Bool import Data.Function-import Data.Int import Data.IORef+import Data.Int+import Data.Map (Map)+import qualified Data.Map as Map import Data.Monoid import Data.Time.Clock import Debug.Trace.LocationTH import GHC.Stats import System.Environment+import System.IO+import System.Mem import System.Mem.Weak import System.Process import Text.Read- import Unsafe.Coerce+import Prelude -import Data.Map (Map)-import qualified Data.Map as Map+import Reflex+import qualified Reflex.Bench.Focused as Focused+import Reflex.Host.Class+import Reflex.Plan.Reflex+import Reflex.Spider.Internal (SpiderEventHandle)+import Reflex.TestPlan  type MonadReflexHost' t m = (MonadReflexHost t m, MonadIORef m, MonadIORef (HostFrame t)) --setupFiring ::   (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t)+setupFiring :: (MonadReflexHost t m, MonadIORef m) => Plan t (Event t a) -> m (EventHandle t a, Schedule t) setupFiring p = do   (e, s) <- runPlan p   h <- subscribeEvent e@@ -87,14 +78,14 @@ benchFiring :: forall t m. (MonadReflexHost' t m, MonadSample t m) => (forall a. m a -> IO a) -> TestCase -> Int -> IO () benchFiring runHost tc n = runHost $ do   let runIterations :: m a -> m ()-      runIterations test = replicateM_ (10*n) $ do+      runIterations test = replicateM_ (10 * n) $ do         result <- test         liftIO $ evaluate result   case tc of-    TestE p -> do+    TestE _ p -> do       (h, s) <- setupFiring p       runIterations $ readSchedule_ s $ readEvent' h-    TestB p -> do+    TestB _ p -> do       (b, s) <- runPlan p       runIterations $ readSchedule_ (makeDense s) $ sample b @@ -117,26 +108,38 @@     implGroup :: (MonadReflexHost' t m, MonadSample t m) => String -> (forall a. m a -> IO a) -> [(String, TestCase)] -> [(String, Int -> IO ())]     implGroup name runHost = group name . fmap (second (benchFiring runHost))     group name = fmap $ first ((name <> "/") <>)-    sub n frames = group ("subscribing " ++ show (n, frames)) $ Focused.subscribing n frames-    firing n     = group ("firing "    <> show n) $ Focused.firing n-    merging n    = group ("merging "   <> show n) $ Focused.merging n-    dynamics n   = group ("dynamics "  <> show n) $ Focused.dynamics n-    shared w     = group ("sharedInvalidators " <> show w) $ Focused.sharedInvalidators w-    cases = concat-      [ sub 100 40-      , dynamics 100-      , dynamics 1000-      , firing 1000-      , firing 10000-      , merging 10-      , merging 50-      , merging 100-      , merging 200-      , shared 30-      , shared 100-      , shared 300-      , shared 1000-      ]+    sub n frames = group ("subscribing " <> show (n, frames)) $ Focused.subscribing n frames+    headEs n frames = group ("headE " <> show (n, frames)) $ Focused.headEs n frames+    firing n = group ("firing " <> show n) $ Focused.firing n+    merging n = group ("merging " <> show n) $ Focused.merging n+    fans n = group ("fans " <> show n) $ Focused.fans n+    mergePatches n = group ("mergePatches " <> show n) $ Focused.mergePatches n+    dynamics n = group ("dynamics " <> show n) $ Focused.dynamics n+    shared w = group ("sharedInvalidators " <> show w) $ Focused.sharedInvalidators w+    eventWriter w = group ("eventWriter " <> show w) $ Focused.eventWriters w+    cases =+      concat+        [ sub 100 40+        , headEs 100 40+        , dynamics 100+        , dynamics 1000+        , firing 1000+        , firing 10000+        , merging 10+        , merging 50+        , merging 100+        , merging 200+        , fans 10+        , fans 100+        , mergePatches 100+        , mergePatches 1000+        , shared 30+        , shared 100+        , shared 300+        , shared 1000+        , eventWriter 100+        , eventWriter 1000+        ]  pattern RunTestCaseFlag = "--run-test-case" @@ -155,8 +158,9 @@       [name, readMaybe -> Just count] -> do         case lookup name benchmarks of           Just testCase -> testCase count+          Nothing -> $failure $ "--run-test-case: unknown test case " <> name         performGC         fix $ \loop -> bool (return ()) (yield >> loop) =<< myCapabilityHasOtherRunnableThreads         return ()       _ -> $failure "--run-test-case: expected test name and iteration count to follow"-    _ -> defaultMainWith (defaultConfig { timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html" }) $ fmap (spawnBenchmark . fst) benchmarks+    _ -> defaultMainWith (defaultConfig {timeLimit = 20, csvFile = Just "dmap-original.csv", reportFile = Just "report.html"}) $ fmap (spawnBenchmark . fst) benchmarks
reflex.cabal view
@@ -1,13 +1,13 @@ cabal-version:      1.22 name:               reflex-version:            0.9.4.1+version:            0.10.0.0 license:            BSD3 license-file:       LICENSE maintainer:         ryan.trinkle@gmail.com author:             Ryan Trinkle stability:          Experimental tested-with:-    ghc ==8.4.4 || ==8.6.5 || ==8.8.1 || ==8.10.7 || ==9.0.1 || ==9.2.5 || ==9.4.5 || ==9.6.1 || ==9.8.2 || ==9.10.1 || ==9.12.2+    ghc ==8.4.4 || ==8.6.5 || ==8.8.4 || ==8.10.7 || ==9.0.2 || ==9.2.8 || ==9.4.8 || ==9.6.7 || ==9.8.4 || ==9.10.3 || ==9.12.4 || ==9.14.1  homepage:           https://reflex-frp.org bug-reports:        https://github.com/reflex-frp/reflex/issues@@ -42,13 +42,6 @@     default:     False     manual:      True -flag fast-weak-    description:-        Use the primitive implementation of FastWeak in GHCJS; note that this requires GHCJS to be built with FastWeak and FastWeakBag present in the RTS, which is not the default--    default:     False-    manual:      True- flag debug-propagation     description: Enable debugging of spider internals     default:     False@@ -59,6 +52,11 @@     default:     False     manual:      True +flag debug-frame+    description: Check frame hygiene+    default:     False+    manual:      True+ flag split-these     description: Use split these/semialign packages     manual:      False@@ -69,7 +67,6 @@         Control.Monad.ReaderIO         Data.AppendMap         Data.FastMutableIntMap-        Data.FastWeakBag         Data.Map.Misc         Data.WeakBag         Reflex@@ -87,7 +84,6 @@         Reflex.EventWriter         Reflex.EventWriter.Base         Reflex.EventWriter.Class-        Reflex.FastWeak         Reflex.FunctorMaybe         Reflex.Host.Class         Reflex.Host.Headless@@ -105,6 +101,7 @@         Reflex.Requester.Base.Internal         Reflex.Requester.Class         Reflex.Spider+        Reflex.Spider.Height         Reflex.Spider.Internal         Reflex.Time         Reflex.TriggerEvent.Base@@ -130,13 +127,10 @@      build-depends:         MemoTrie == 0.6.*-      , base >= 4.11 && < 4.22-      , bifunctors >= 5.2 && < 5.7-      , comonad >= 5.0.4 && < 5.1+      , base >= 4.11 && < 4.23       , commutative-semigroups >= 0.1 && <0.3       , constraints >= 0.10 && <0.15-      , constraints-extras >= 0.3 && < 0.5-      , containers >= 0.6 && < 0.8+      , containers >= 0.6 && < 0.9       , data-default >= 0.5 && < 0.9       , dependent-map >= 0.3 && < 0.5       , dependent-sum >= 0.6 && < 0.8@@ -153,15 +147,14 @@       , ref-tf >= 0.4 && < 0.6       , reflection == 2.1.*       , semigroupoids >= 4.0 && < 7-      , stm >= 2.4 && < 2.6       , syb >= 0.5 && < 0.8-      , time >= 1.4 && < 1.15+      , time >= 1.4 && < 1.16       , transformers >= 0.5 && < 0.7       , unbounded-delays >= 0.1.0.0 && < 0.2       , witherable >= 0.4 && < 0.6       , haskell-src-exts >= 1.16 && < 1.24       , haskell-src-meta >= 0.6 && < 0.9-      , template-haskell >= 2.9 && < 2.24+      , template-haskell >= 2.9 && < 2.25      other-extensions:       TemplateHaskell@@ -179,7 +172,7 @@      if flag(debug-trace-events)         cpp-options:   -DDEBUG_TRACE_EVENTS-        build-depends: bytestring >=0.10.8 && <0.11+        build-depends: bytestring >=0.10.8 && <0.13      if flag(debug-propagation)         cpp-options:@@ -188,12 +181,15 @@     if flag(debug-cycles)         cpp-options: -DDEBUG_CYCLES -    if flag(fast-weak) && impl(ghcjs >=0)-        cpp-options: -DGHCJS_FAST_WEAK+    if flag(debug-frame)+        cpp-options: -DDEBUG_FRAME      if impl(ghcjs)         build-depends: ghcjs-base >=0.2 && <0.3 +    if impl(ghc >= 9.12)+        ghc-options: -fexpose-overloaded-unfoldings+ test-suite semantics     type:             exitcode-stdio-1.0     main-is:          semantics.hs@@ -209,8 +205,7 @@     default-language: Haskell2010     ghc-options:      -O2 -Wall -rtsopts     build-depends:-        base >= 4.11 && < 4.22-      , bifunctors+        base >= 4.11 && < 4.23       , containers       , deepseq       , dependent-map@@ -219,54 +214,26 @@       , ref-tf       , reflex       , split+      , tasty+      , tasty-expected-failure+      , tasty-hunit       , transformers  test-suite CrossImpl     type:             exitcode-stdio-1.0     main-is:          Reflex/Test/CrossImpl.hs     hs-source-dirs:   test-    other-modules:-        Reflex.Test-        Reflex.TestPlan-        Reflex.Plan.Reflex-        Reflex.Plan.Pure      default-language: Haskell2010     ghc-options:      -O2 -Wall -rtsopts     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers-      , dependent-map       , dependent-sum-      , deepseq       , mtl-      , transformers       , ref-tf       , reflex -test-suite hlint-    type:             exitcode-stdio-1.0-    main-is:          hlint.hs-    hs-source-dirs:   test-    default-language: Haskell2010-    build-depends:-        base >= 4.11 && < 4.22-      , directory-      , filepath-      , filemanip--    if impl(ghc >=9.6)-        buildable: False--    if impl(ghc <9.2)-        build-depends: hlint (<2.1 || >=2.2.2) && <3.5--    else-        build-depends: hlint >=3.5 && <3.6--    if impl(ghcjs >=0) || arch(javascript)-        buildable: False- test-suite EventWriterT     type:             exitcode-stdio-1.0     main-is:          EventWriterT.hs@@ -274,15 +241,12 @@     other-modules:    Test.Run     default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers-      , deepseq       , dependent-map       , dependent-sum       , lens-      , mtl       , these-      , transformers       , reflex       , ref-tf @@ -297,16 +261,12 @@     default-language: Haskell2010     ghc-options:      -threaded     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers-      , deepseq-      , dependent-map       , dependent-sum       , hspec       , lens-      , mtl       , these-      , transformers       , reflex       , ref-tf       , witherable@@ -327,7 +287,7 @@      default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , constraints       , constraints-extras       , containers@@ -340,7 +300,6 @@       , reflex       , text       , these-      , transformers      if flag(split-these)         build-depends: these-lens@@ -351,7 +310,7 @@     hs-source-dirs:   test     default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , reflex  test-suite Adjustable@@ -361,7 +320,7 @@     other-modules:    Test.Run     default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers       , dependent-sum       , reflex@@ -380,10 +339,9 @@      default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , commutative-semigroups       , containers-      , dependent-map       , dependent-sum       , deepseq       , lens@@ -393,7 +351,6 @@       , ref-tf       , reflex       , these-      , transformers      if flag(split-these)         build-depends:@@ -412,7 +369,7 @@      default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers       , dependent-sum       , dependent-map@@ -420,7 +377,6 @@       , mtl       , patch       , these-      , transformers       , reflex       , ref-tf @@ -438,7 +394,7 @@      default-language: Haskell2010     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers       , deepseq       , dependent-sum@@ -447,6 +403,34 @@       , ref-tf       , these +test-suite runHostFrame+    type:             exitcode-stdio-1.0+    main-is:          runHostFrame.hs+    hs-source-dirs:   test+    default-language: Haskell2010+    ghc-options:      -Wall+    build-depends:+        base >= 4.11 && < 4.23+      , containers+      , reflex+      , tasty+      , tasty-expected-failure+      , tasty-hunit++test-suite newFanEventWithTrigger+    type:             exitcode-stdio-1.0+    main-is:          newFanEventWithTrigger.hs+    hs-source-dirs:   test+    default-language: Haskell2010+    ghc-options:      -Wall+    build-depends:+        base >= 4.11 && < 4.23+      , containers+      , dependent-sum+      , reflex+      , tasty+      , tasty-hunit+ test-suite behaviorLeak     type:             exitcode-stdio-1.0     main-is:          behaviorLeak.hs@@ -454,12 +438,27 @@     default-language: Haskell2010     ghc-options:      -Wall -O2 -rtsopts "-with-rtsopts=-T"     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , dependent-sum       , reflex       , ref-tf       , primitive +test-suite collectedSubscriber+    type:             exitcode-stdio-1.0+    main-is:          collectedSubscriber.hs+    hs-source-dirs:   test+    default-language: Haskell2010+    ghc-options:      -Wall -O2 -rtsopts+    build-depends:+        base >= 4.11 && < 4.23+      , containers+      , dependent-sum+      , reflex+      , tasty+      , tasty-hunit+    other-modules:+ benchmark spider-bench     type:             exitcode-stdio-1.0     main-is:          Main.hs@@ -472,7 +471,7 @@     default-language: Haskell2010     ghc-options:      -Wall -O2 -rtsopts     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers       , criterion       , deepseq@@ -480,7 +479,6 @@       , dependent-sum       , ref-tf       , mtl-      , primitive       , reflex       , split       , stm@@ -502,7 +500,7 @@     default-language: Haskell2010     ghc-options:      -Wall -O2 -rtsopts -threaded     build-depends:-        base >= 4.11 && < 4.22+        base >= 4.11 && < 4.23       , containers       , criterion       , deepseq@@ -510,7 +508,6 @@       , dependent-sum       , loch-th       , mtl-      , primitive       , process       , ref-tf       , reflex
src/Control/Monad/ReaderIO.hs view
@@ -1,22 +1,23 @@-{-# language RoleAnnotations #-}-{-# language MultiParamTypeClasses #-}-{-# language FlexibleInstances #-}-{-# language CPP #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE RoleAnnotations #-}  module Control.Monad.ReaderIO   ( ReaderIO (..)   ) where -import Control.Monad.Fix import Control.Monad-import Control.Monad.Reader.Class+import Control.Monad.Fix import Control.Monad.IO.Class+import Control.Monad.Reader.Class  -- | An approximate clone of @RIO@ from the @rio@ package, but not based on -- @ReaderT@. The trouble with @ReaderT@ is that its third type argument has a -- @nominal@ role, so we can't coerce through it when it's wrapped in some -- other @data@ type. Ugh.-newtype ReaderIO e a = ReaderIO { runReaderIO :: e -> IO a }+newtype ReaderIO e a = ReaderIO {runReaderIO :: e -> IO a}+ type role ReaderIO representational representational  instance Functor (ReaderIO e) where@@ -44,7 +45,7 @@   {-# INLINE mfix #-}  instance MonadIO (ReaderIO e) where-  liftIO m = ReaderIO $ \_ -> m+  liftIO m = ReaderIO $ const m   {-# INLINE liftIO #-}  instance MonadReader e (ReaderIO e) where
src/Data/AppendMap.hs view
@@ -21,20 +21,20 @@   , module Data.Map.Monoidal   ) where -import Prelude hiding (null)- import Data.Coerce import Data.Default import Data.Map (Map) import qualified Data.Map.Internal.Debug as Map (showTree, showTreeWith) import Data.Map.Monoidal-+import Prelude hiding (null)  {-# DEPRECATED AppendMap "Use 'MonoidalMap' instead" #-}+ -- | AppendMap is a synonym for 'Data.Map.Monoidal.MonoidalMap' type AppendMap = MonoidalMap  {-# DEPRECATED _unAppendMap "Use 'getMonoidalMap' instead" #-}+ -- | A synonym for 'getMonoidalMap' _unAppendMap :: MonoidalMap k v -> Map k v _unAppendMap = getMonoidalMap@@ -52,9 +52,10 @@        else Just deleted  -- | Like 'mapMaybe' but indicates whether the resulting container is empty-mapMaybeNoNull :: (a -> Maybe b)-               -> MonoidalMap token a-               -> Maybe (MonoidalMap token b)+mapMaybeNoNull+  :: (a -> Maybe b)+  -> MonoidalMap token a+  -> Maybe (MonoidalMap token b) mapMaybeNoNull f as =   let bs = mapMaybe f as   in if null bs@@ -62,6 +63,7 @@        else Just bs  -- TODO: Move instances to `Data.Patch`+ -- | Displays a 'MonoidalMap' as a tree. See 'Data.Map.Lazy.showTree' for details. showTree :: forall k a. (Show k, Show a) => MonoidalMap k a -> String showTree = coerce (Map.showTree :: Map k a -> String)
src/Data/FastMutableIntMap.hs view
@@ -25,19 +25,18 @@   , toList   ) where ---TODO: Pure JS version---TODO: Fast copy to FastIntMap---TODO: Fast patch type--import Prelude hiding (lookup)+-- TODO: Pure JS version+-- TODO: Fast copy to FastIntMap+-- TODO: Fast patch type  import Control.Monad.IO.Class import Data.Foldable (traverse_)+import Data.IORef import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap-import Data.IORef import Data.Patch.Class import Data.Patch.IntMap+import Prelude hiding (lookup)  -- | A 'FastMutableIntMap' holds a map of values of type @a@ and allows low-overhead modifications via IO. -- Operations on 'FastMutableIntMap' run in IO.
− src/Data/FastWeakBag.hs
@@ -1,159 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE ExistentialQuantification #-}-#ifdef GHCJS_FAST_WEAK-{-# LANGUAGE ForeignFunctionInterface #-}-{-# LANGUAGE JavaScriptFFI #-}-#endif---- | This module defines the 'FastWeakBag' type, which represents a mutable--- collection of items that does not cause the items to be retained in memory.--- This is useful for situations where a value needs to be inspected or modified--- if it is still alive, but can be ignored if it is dead.-module Data.FastWeakBag-  ( FastWeakBag-  , FastWeakBagTicket-  , empty-  , isEmpty-  , insert-  , traverse-  , traverse_-  , remove-  -- * Internal functions-  -- These will not always be available.-#ifndef GHCJS_FAST_WEAK-  , _weakBag_children --TODO: Don't export this-#endif-  ) where--import Prelude hiding (traverse)--import Control.Monad-import Control.Monad.IO.Class--#ifdef GHCJS_FAST_WEAK-import GHCJS.Types-import Reflex.FastWeak (js_isNull, unsafeFromRawJSVal, unsafeToRawJSVal)-#else-import Control.Exception-import Data.IntMap.Strict (IntMap)-import qualified Data.IntMap.Strict as IntMap-import Data.IORef-import System.Mem.Weak-#endif---- | A 'FastWeakBag' holds a set of values of type @/a/@, but does not retain them ---- that is, they can still be garbage-collected.  As long as the @/a/@ values remain--- alive, the 'FastWeakBag' will continue to refer to them.-#ifdef GHCJS_FAST_WEAK-newtype FastWeakBag a = FastWeakBag JSVal-#else-data FastWeakBag a = FastWeakBag-  { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?-  , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ Map of items contained by the 'FastWeakBag'-  }-#endif---- | When inserting an item into a 'FastWeakBag', a 'FastWeakBagTicket' is returned.  If--- the caller retains the ticket, the item is guranteed to stay in memory (and--- thus in the 'FastWeakBag').  The ticket can also be used to remove the item from--- the 'FastWeakBag' prematurely (i.e. while it is still alive), using 'remove'.-#ifdef GHCJS_FAST_WEAK-newtype FastWeakBagTicket a = FastWeakBagTicket JSVal-#else-data FastWeakBagTicket a = FastWeakBagTicket-  { _weakBagTicket_weakItem :: {-# UNPACK #-} !(Weak a)-  , _weakBagTicket_item :: {-# NOUNPACK #-} !a-  }-#endif---- | Insert an item into a 'FastWeakBag'.-{-# INLINE insert #-}-insert :: a -- ^ The item-       -> FastWeakBag a -- ^ The 'FastWeakBag' to insert into-       -> IO (FastWeakBagTicket a) -- ^ Returns a 'FastWeakBagTicket' that ensures the item-                           -- is retained and allows the item to be removed.-#ifdef GHCJS_FAST_WEAK-insert a wb = js_insert (unsafeToRawJSVal a) wb-foreign import javascript unsafe "$r = new h$FastWeakBagTicket($2, $1);" js_insert :: JSVal -> FastWeakBag a -> IO (FastWeakBagTicket a)-#else-insert a (FastWeakBag nextId children) = {-# SCC "insert" #-} do-  a' <- evaluate a-  myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)-  let cleanup = atomicModifyIORef' children $ \cs -> (IntMap.delete myId cs, ())-  wa <- mkWeakPtr a' $ Just cleanup-  atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())-  return $ FastWeakBagTicket-    { _weakBagTicket_weakItem = wa-    , _weakBagTicket_item = a'-    }-#endif---- | Create an empty 'FastWeakBag'.-{-# INLINE empty #-}-empty :: IO (FastWeakBag a)-#ifdef GHCJS_FAST_WEAK-empty = js_empty-foreign import javascript unsafe "$r = new h$FastWeakBag();" js_empty :: IO (FastWeakBag a)-#else-empty = {-# SCC "empty" #-} do-  nextId <- newIORef 1-  children <- newIORef IntMap.empty-  let bag = FastWeakBag-        { _weakBag_nextId = nextId-        , _weakBag_children = children-        }-  return bag-#endif---- | Check whether a 'FastWeakBag' is empty.-{-# INLINE isEmpty #-}-isEmpty :: FastWeakBag a -> IO Bool-#ifdef GHCJS_FAST_WEAK-isEmpty = js_isEmpty-foreign import javascript unsafe "(function(){ for(var i = 0; i < $1.tickets.length; i++) { if($1.tickets[i] !== null) { return false; } }; return true; })()" js_isEmpty :: FastWeakBag a -> IO Bool --TODO: Clean up as we go along so this isn't O(n) every time-#else-isEmpty bag = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef (_weakBag_children bag)-#endif--{-# INLINE traverse_ #-}--- | Visit every node in the given list.  If new nodes are appended during the--- traversal, they will not be visited.  Every live node that was in the list--- when the traversal began will be visited exactly once; however, no guarantee--- is made about the order of the traversal.-traverse_ :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()-#ifdef GHCJS_FAST_WEAK-traverse_ wb f = do-  let go cursor = when (not $ js_isNull cursor) $ do-        val <- liftIO $ js_getTicketValue cursor-        f $ unsafeFromRawJSVal val-        go =<< liftIO (js_getNext (FastWeakBagTicket cursor))-  go =<< liftIO (js_getInitial wb)-foreign import javascript unsafe "(function(){ for(var i = $1.tickets.length - 1; i >= 0; i--) { if($1.tickets[i] !== null) { return $1.tickets[i]; } }; return null; })()" js_getInitial :: FastWeakBag a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a-foreign import javascript unsafe "$r = $1.val;" js_getTicketValue :: JSVal -> IO JSVal---TODO: Fix the race condition where if a cursor is deleted (presumably using 'remove', below) while we're holding it, it can't find its way back to the correct bag-foreign import javascript unsafe "(function(){ for(var i = $1.pos - 1; i >= 0; i--) { if($1.bag.tickets[i] !== null) { return $1.bag.tickets[i]; } }; return null; })()" js_getNext :: FastWeakBagTicket a -> IO JSVal --TODO: Clean up as we go along so this isn't O(n) every time -- Result can be null or a FastWeakBagTicket a-#else-traverse_ (FastWeakBag _ children) f = {-# SCC "traverse_" #-} do-  cs <- liftIO $ readIORef children-  forM_ cs $ \c -> do-    ma <- liftIO $ deRefWeak c-    mapM_ f ma-#endif--{-# DEPRECATED traverse "Use 'traverse_' instead" #-}-traverse :: forall a m. MonadIO m => FastWeakBag a -> (a -> m ()) -> m ()-traverse = traverse_---- | Remove an item from the 'FastWeakBag'; does nothing if invoked multiple times--- on the same 'FastWeakBagTicket'.-{-# INLINE remove #-}-remove :: FastWeakBagTicket a -> IO ()-#ifdef GHCJS_FAST_WEAK-remove = js_remove-foreign import javascript unsafe "$1.bag.tickets[$1.pos] = null; $1.bag = new h$FastWeakBag(); $1.bag.tickets.push($1); $1.pos = 0;" js_remove :: FastWeakBagTicket a -> IO () --TODO: Don't bother with the new surrogate FastWeakBag; instead, make the GC check for bag === null, and then null it out here-#else-remove (FastWeakBagTicket w _) = {-# SCC "remove" #-} finalize w-#endif---TODO: Should 'remove' also drop the reference to the item?----TODO: can/should we provide a null FastWeakBagTicket?
src/Data/Map/Misc.hs view
@@ -2,8 +2,7 @@  -- | Additional functions for manipulating 'Map's. module Data.Map.Misc-  (-  -- * Working with Maps+  ( -- * Working with Maps     diffMapNoEq   , diffMap   , applyMap@@ -19,21 +18,21 @@ import qualified Data.Set as Set import Data.These --- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new@ respectively. @Just@ represents an association present in @new@ and @Nothing@--- represents an association only present in @old@ but no longer present in @new@.+-- | Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new@ respectively. @Just@ represents an association present in @new@ and @Nothing@+--  represents an association only present in @old@ but no longer present in @new@. ----- Similar to 'diffMap' but doesn't require 'Eq' on the values, thus can't tell if a value has changed or not.-diffMapNoEq :: (Ord k) => Map k v -> Map k v -> Map k (Maybe v)+--  Similar to 'diffMap' but doesn't require 'Eq' on the values, thus can't tell if a value has changed or not.+diffMapNoEq :: Ord k => Map k v -> Map k v -> Map k (Maybe v) diffMapNoEq olds news = flip Map.mapMaybe (align olds news) $ \case   This _ -> Just Nothing   These _ new -> Just $ Just new   That new -> Just $ Just new --- |Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new respectively. @Just@ represents an association present in @new@ and either not--- present in @old@ or where the value has changed. @Nothing@ represents an association only present in @old@ but no longer present in @new@.+-- | Produce a @'Map' k (Maybe v)@ by comparing two @'Map' k v@s, @old@ and @new respectively. @Just@ represents an association present in @new@ and either not+--  present in @old@ or where the value has changed. @Nothing@ represents an association only present in @old@ but no longer present in @new@. ----- See also 'diffMapNoEq' for a similar but weaker version which does not require 'Eq' on the values but thus can't indicated a value not changing between--- @old@ and @new@ with @Nothing@.+--  See also 'diffMapNoEq' for a similar but weaker version which does not require 'Eq' on the values but thus can't indicated a value not changing between+--  @old@ and @new@ with @Nothing@. diffMap :: (Ord k, Eq v) => Map k v -> Map k v -> Map k (Maybe v) diffMap olds news = flip Map.mapMaybe (align olds news) $ \case   This _ -> Just Nothing@@ -42,31 +41,32 @@     | otherwise -> Just $ Just new   That new -> Just $ Just new --- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new map from the given input @'Map' k v@.+-- | Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new map from the given input @'Map' k v@. ----- See also 'Data.Patch.Map' and 'Data.Patch.MapWithMove'.+--  See also 'Data.Patch.Map' and 'Data.Patch.MapWithMove'. applyMap :: Ord k => Map k (Maybe v) -> Map k v -> Map k v applyMap patch old = insertions `Map.union` (old `Map.difference` deletions)-  where (deletions, insertions) = Map.mapEither maybeToEither patch-        maybeToEither = \case-          Nothing -> Left ()-          Just r -> Right r+  where+    (deletions, insertions) = Map.mapEither maybeToEither patch+    maybeToEither = \case+      Nothing -> Left ()+      Just r -> Right r --- |Split a @'Map' k (Either a b)@ into @Map k a@ and @Map k b@, equivalent to @'Map.mapEither' id@+-- | Split a @'Map' k (Either a b)@ into @Map k a@ and @Map k b@, equivalent to @'Map.mapEither' id@ {-# DEPRECATED mapPartitionEithers "Use 'mapEither' instead" #-} mapPartitionEithers :: Map k (Either a b) -> (Map k a, Map k b) mapPartitionEithers = Map.mapEither id --- |Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new @'Set' k@ from the given input set.+-- | Given a @'Map' k (Maybe v)@ representing keys to insert/update (@Just@) or delete (@Nothing@), produce a new @'Set' k@ from the given input set. ----- Equivalent to:+--  Equivalent to: ----- @---     applyMapKeysSet patch ('Map.keysSet' m) == 'Map.keysSet' ('applyMap' patch m)--- @+--  @+--      applyMapKeysSet patch ('Map.keysSet' m) == 'Map.keysSet' ('applyMap' patch m)+--  @ ----- but avoids the intervening @Map@ and needs no values.+--  but avoids the intervening @Map@ and needs no values. applyMapKeysSet :: Ord k => Map k (Maybe v) -> Set k -> Set k applyMapKeysSet patch old = Map.keysSet insertions `Set.union` (old `Set.difference` Map.keysSet deletions)-  where (insertions, deletions) = Map.partition isJust patch-+  where+    (insertions, deletions) = Map.partition isJust patch
src/Data/WeakBag.hs view
@@ -1,6 +1,8 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ScopedTypeVariables #-}  -- | This module defines the 'WeakBag' type, which represents a mutable -- collection of items that does not cause the items to be retained in memory.@@ -10,32 +12,34 @@   ( WeakBag   , WeakBagTicket   , empty-  , singleton   , insert+  , isEmpty   , traverse   , traverse_+  , traverseWeakIntMap_   , remove-  -- * Internal functions-  -- These will not always be available.-  , _weakBag_children --TODO: Don't export this   ) where -import Prelude hiding (traverse)- import Control.Exception-import Control.Monad import Control.Monad.IO.Class-import Data.IntMap.Strict (IntMap)-import qualified Data.IntMap.Strict as IntMap+import Data.Functor (void) import Data.IORef+import Data.IntMap.Internal (IntMap (Nil, Tip))+import qualified Data.IntMap.Internal as IntMap.Internal+import qualified Data.IntMap.Strict as IntMap+import Prelude hiding (traverse)+#if MIN_VERSION_base(4,13,0)+import GHC.IORef (atomicModifyIORef'_)+#endif import System.Mem.Weak  -- | A 'WeakBag' holds a set of values of type @/a/@, but does not retain them - -- that is, they can still be garbage-collected.  As long as the @/a/@ values remain -- alive, the 'WeakBag' will continue to refer to them. data WeakBag a = WeakBag-  { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) --TODO: what if this wraps around?-  , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a))) -- ^ The items referenced by the WeakBag+  { _weakBag_nextId :: {-# UNPACK #-} !(IORef Int) -- TODO: what if this wraps around?+  , _weakBag_children :: {-# UNPACK #-} !(IORef (IntMap (Weak a)))+  -- ^ The items referenced by the WeakBag   }  -- | When inserting an item into a 'WeakBag', a 'WeakBagTicket' is returned.  If@@ -47,69 +51,84 @@   , _weakBagTicket_item :: {-# NOUNPACK #-} !a   } --- | Insert an item into a 'WeakBag'.+-- | Insert an item into a 'WeakBag'. The removal of the item, by garbage+-- collection or by 'remove', deletes it from the bag. {-# INLINE insert #-}-insert :: a -- ^ The item-       -> WeakBag a -- ^ The 'WeakBag' to insert into-       -> IORef (Weak b) -- ^ An arbitrary value to be used in the following-                         -- callback-       -> (b -> IO ()) -- ^ A callback to be invoked when the item is removed-                       -- (whether automatically by the item being garbage-                       -- collected or manually via 'remove')-       -> IO WeakBagTicket -- ^ Returns a 'WeakBagTicket' that ensures the item-                           -- is retained and allows the item to be removed.-insert a (WeakBag nextId children) wbRef finalizer = {-# SCC "insert" #-} do-  a' <- evaluate a-  wbRef' <- evaluate wbRef-  myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)-  let cleanup = do-        wb <- readIORef wbRef'-        mb <- deRefWeak wb-        forM_ mb $ \b -> do-          csWithoutMe <- atomicModifyIORef children $ \cs ->-            let !csWithoutMe = IntMap.delete myId cs-            in (csWithoutMe, csWithoutMe)-          when (IntMap.null csWithoutMe) $ finalizer b-  wa <- mkWeakPtr a' $ Just cleanup-  atomicModifyIORef' children $ \cs -> (IntMap.insert myId wa cs, ())-  return $ WeakBagTicket-    { _weakBagTicket_weakItem = wa-    , _weakBagTicket_item = a'-    }+insert :: a -> WeakBag a -> IO WeakBagTicket+insert a (WeakBag nextId children) =+  {-# SCC "insert" #-}+  do+    a' <- evaluate a+    myId <- atomicModifyIORef' nextId $ \n -> (succ n, n)+    wa <- mkWeakPtr a' $ Just $ void $ atomicModifyIORef'_ children $ IntMap.delete myId+    void $ atomicModifyIORef'_ children $ IntMap.insert myId wa+    return $+      WeakBagTicket+        { _weakBagTicket_weakItem = wa+        , _weakBagTicket_item = a'+        } +#if !MIN_VERSION_base(4,13,0)+-- | 'GHC.IORef.atomicModifyIORef'_', which base < 4.13 does not have.+atomicModifyIORef'_ :: IORef a -> (a -> a) -> IO (a, a)+atomicModifyIORef'_ ref f = atomicModifyIORef' ref $ \old -> let !new = f old in (new, (old, new))+#endif+ -- | Create an empty 'WeakBag'. {-# INLINE empty #-} empty :: IO (WeakBag a)-empty = {-# SCC "empty" #-} do-  nextId <- newIORef 1-  children <- newIORef IntMap.empty-  let bag = WeakBag-        { _weakBag_nextId = nextId-        , _weakBag_children = children-        }-  return bag+empty =+  {-# SCC "empty" #-}+  do+    nextId <- newIORef 1+    children <- newIORef IntMap.empty+    let bag =+          WeakBag+            { _weakBag_nextId = nextId+            , _weakBag_children = children+            }+    return bag --- | Create a 'WeakBag' with one item; equivalent to creating the 'WeakBag' with--- 'empty', then using 'insert'.-{-# INLINE singleton #-}-singleton :: a -> IORef (Weak b) -> (b -> IO ()) -> IO (WeakBag a, WeakBagTicket)-singleton a wbRef finalizer = {-# SCC "singleton" #-} do-  bag <- empty-  ticket <- insert a bag wbRef finalizer-  return (bag, ticket)+-- | Whether the bag has no entry. The entry of an item that the garbage+-- collector removed is deleted by the finalizer of the item's weak pointer, so+-- the bag can be non-empty for a while after its last live item is gone.+{-# INLINE isEmpty #-}+isEmpty :: WeakBag a -> IO Bool+isEmpty (WeakBag _ children) = {-# SCC "isEmpty" #-} IntMap.null <$> readIORef children  {-# INLINE traverse_ #-}+ -- | Visit every node in the given list.  If new nodes are appended during the -- traversal, they will not be visited.  Every live node that was in the list -- when the traversal began will be visited exactly once; however, no guarantee -- is made about the order of the traversal.-traverse_ :: MonadIO m => WeakBag a -> (a -> m ()) -> m ()-traverse_ (WeakBag _ children) f = {-# SCC "traverse" #-} do-  cs <- liftIO $ readIORef children-  forM_ cs $ \c -> do-    ma <- liftIO $ deRefWeak c-    mapM_ f ma+traverse_ :: forall a m. MonadIO m => WeakBag a -> (a -> m ()) -> m ()+traverse_ (WeakBag _ children) f =+  {-# SCC "traverse" #-}+  do+    cs <- liftIO $ readIORef children+    traverseWeakIntMap_ cs f +{-# INLINE traverseWeakIntMap_ #-}+traverseWeakIntMap_ :: forall a m. MonadIO m => IntMap (Weak a) -> (a -> m ()) -> m ()+traverseWeakIntMap_ items f = go items+  where+    -- This is a very hot function in Reflex and directly recursing over the+    -- internal data structure is a noticable improvement over using forM_:+    go :: IntMap (Weak a) -> m ()+    go (IntMapBin l r) = go l >> go r+    go (Tip _ c) = mapM_ f =<< liftIO (deRefWeak c)+    go Nil = pure ()++pattern IntMapBin :: IntMap a -> IntMap a -> IntMap a+#if MIN_VERSION_containers(0,8,0)+pattern IntMapBin l r <- IntMap.Internal.Bin _ l r+#else+pattern IntMapBin l r <- IntMap.Internal.Bin _ _ l r+#endif++{-# COMPLETE IntMapBin, Tip, Nil #-}+ {-# DEPRECATED traverse "Use 'traverse_' instead" #-} traverse :: MonadIO m => WeakBag a -> (a -> m ()) -> m () traverse = traverse_@@ -119,6 +138,7 @@ {-# INLINE remove #-} remove :: WeakBagTicket -> IO () remove (WeakBagTicket w _) = {-# SCC "remove" #-} finalize w---TODO: Should 'remove' also drop the reference to the item? ---TODO: can/should we provide a null WeakBagTicket?+-- TODO: Should 'remove' also drop the reference to the item?++-- TODO: can/should we provide a null WeakBagTicket?
src/Reflex.hs view
@@ -6,18 +6,18 @@   ( module X   ) where -import Reflex.Class as X import Reflex.Adjustable.Class as X import Reflex.BehaviorWriter.Base as X import Reflex.BehaviorWriter.Class as X+import Reflex.Class as X import Reflex.Collection as X import Reflex.Dynamic as X-import Reflex.EventWriter.Base as X-import Reflex.EventWriter.Class as X import Reflex.Dynamic.TH as X import Reflex.Dynamic.Uniq as X import Reflex.DynamicWriter.Base as X import Reflex.DynamicWriter.Class as X+import Reflex.EventWriter.Base as X+import Reflex.EventWriter.Class as X import Reflex.NotReady.Class as X import Reflex.PerformEvent.Base as X import Reflex.PerformEvent.Class as X
src/Reflex/Adjustable/Class.hs view
@@ -16,29 +16,29 @@ --   such that, when observed after the firing of any such 'Event', the result --   is as though the action was originally run with the 'Event's value. module Reflex.Adjustable.Class-  (-  -- * The Adjustable typeclass-    Adjustable(..)+  ( -- * The Adjustable typeclass+    Adjustable (..)   , sequenceDMapWithAdjust   , sequenceDMapWithAdjustWithMove   , mapMapWithAdjustWithMove-  -- * Deprecated aliases++    -- * Deprecated aliases   , MonadAdjust   ) where  import Control.Monad.Identity import Control.Monad.Reader import Data.Dependent.Map (DMap)-import Data.GADT.Compare (GCompare(..)) import qualified Data.Dependent.Map as DMap import Data.Functor.Constant import Data.Functor.Misc+import Data.GADT.Compare (GCompare (..)) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Map (Map)+import Data.Patch.DMapWithMove  import Reflex.Class-import Data.Patch.DMapWithMove  -- | A 'Monad' that supports adjustment over time.  After an action has been -- run, if the given events fire, it will adjust itself so that its net effect@@ -64,19 +64,21 @@     -> DMap k v     -> Event t (PatchDMap k v)     -> m (DMap k v', Event t (PatchDMap k v'))-  {-# INLINABLE traverseDMapWithKeyWithAdjust #-}-  traverseDMapWithKeyWithAdjust f dm0 dm' = fmap (fmap (fmap fromPatchWithMove)) $-    traverseDMapWithKeyWithAdjustWithMove f dm0 $ fmap toPatchWithMove dm'-   where-    toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m-    toNodeInfoWithMove = \case-      ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing-      ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing-    fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m-    fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of-      From_Insert v -> Just v-      From_Delete -> Nothing-      From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move"+  {-# INLINEABLE traverseDMapWithKeyWithAdjust #-}+  traverseDMapWithKeyWithAdjust f dm0 dm' =+    fmap (fmap (fmap fromPatchWithMove))+      $ traverseDMapWithKeyWithAdjustWithMove f dm0+      $ fmap toPatchWithMove dm'+    where+      toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m+      toNodeInfoWithMove = \case+        ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing+        ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing+      fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m+      fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of+        From_Insert v -> Just v+        From_Delete -> Nothing+        From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move"    traverseDMapWithKeyWithAdjustWithMove     :: GCompare k@@ -120,7 +122,8 @@ -- | Traverses a 'Map', running the provided 'Adjustable' action. The provided 'Event' of patches to the 'Map' -- can add, remove, update, move, or swap values. mapMapWithAdjustWithMove-  :: forall t m k v v'. (Adjustable t m, Ord k)+  :: forall t m k v v'+   . (Adjustable t m, Ord k)   => (k -> v -> m v')   -> Map k v   -> Event t (PatchMapWithMove k v)@@ -134,5 +137,6 @@ --------------------------------------------------------------------------------  {-# DEPRECATED MonadAdjust "Use Adjustable instead" #-}+ -- | Synonym for 'Adjustable' type MonadAdjust = Adjustable
src/Reflex/BehaviorWriter/Base.hs view
@@ -1,7 +1,3 @@-{-|-Module: Reflex.BehaviorWriter.Base-Description: Implementation of BehaviorWriter--} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-}@@ -9,11 +5,14 @@ {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE StandaloneDeriving #-} +-- |+-- Module: Reflex.BehaviorWriter.Base+-- Description: Implementation of BehaviorWriter module Reflex.BehaviorWriter.Base   ( BehaviorWriterT (..)   , runBehaviorWriterT@@ -21,7 +20,7 @@   ) where  import Control.Monad-import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.IO.Class@@ -42,9 +41,9 @@ import Control.Monad.Identity #endif -import Reflex.Class import Reflex.Adjustable.Class import Reflex.BehaviorWriter.Class+import Reflex.Class import Reflex.Host.Class import Reflex.PerformEvent.Class import Reflex.PostBuild.Class@@ -53,21 +52,21 @@ import Reflex.TriggerEvent.Class  -- | A basic implementation of 'BehaviorWriter'.-newtype BehaviorWriterT t w m a = BehaviorWriterT { unBehaviorWriterT :: StateT [Behavior t w] m a }+newtype BehaviorWriterT t w m a = BehaviorWriterT {unBehaviorWriterT :: StateT [Behavior t w] m a}   -- The list is kept in reverse order   deriving-    ( Functor-    , Applicative-    , Monad-    , MonadTrans+    ( Applicative+    , Functor     , MFunctor-    , MonadIO-    , MonadFix+    , Monad     , MonadAsyncException-    , MonadException     , MonadCatch-    , MonadThrow+    , MonadException+    , MonadFix+    , MonadIO     , MonadMask+    , MonadThrow+    , MonadTrans     )  -- | Run a 'BehaviorWriterT' action.  The behavior writer output will be provided@@ -78,10 +77,11 @@   return (result, mconcat $ reverse ws)  -- | Map a function over the output of a 'BehaviorWriterT'.-withBehaviorWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)-                   => (w -> w')-                   -> BehaviorWriterT t w m a-                   -> BehaviorWriterT t w' m a+withBehaviorWriterT+  :: (Monoid w, Monoid w', Reflex t, MonadHold t m)+  => (w -> w')+  -> BehaviorWriterT t w m a+  -> BehaviorWriterT t w' m a withBehaviorWriterT f dw = do   (r, d) <- lift $ do     (r, d) <- runBehaviorWriterT dw@@ -151,8 +151,8 @@   traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith  traverseIntMapWithKeyWithAdjustImpl-  :: forall t w v' p p' v m.-     ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)+  :: forall t w v' p p' v m+   . ( PatchTarget (p' (Behavior t w)) ~ IntMap (Behavior t w)      , Patch (p' (Behavior t w))      , Monoid w      , Reflex t@@ -160,10 +160,10 @@      , Functor p      , p ~ p'      )-  => (   (IntMap.Key -> v -> m (v', Behavior t w))-      -> IntMap v-      -> Event t (p v)-      -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))+  => ( (IntMap.Key -> v -> m (v', Behavior t w))+       -> IntMap v+       -> Event t (p v)+       -> m (IntMap (v', Behavior t w), Event t (p (v', Behavior t w)))      )   -> (IntMap.Key -> v -> BehaviorWriterT t w m v')   -> IntMap v@@ -185,17 +185,17 @@ newtype BehaviorWriterTLoweredResult t w v a = BehaviorWriterTLoweredResult (v a, Behavior t w)  traverseDMapWithKeyWithAdjustImpl-  :: forall t w k v' p p' v m.-     ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)+  :: forall t w k v' p p' v m+   . ( PatchTarget (p' (Some k) (Behavior t w)) ~ Map (Some k) (Behavior t w)      , Patch (p' (Some k) (Behavior t w))      , Monoid w      , Reflex t      , MonadHold t m      )-  => (   (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))-      -> DMap k v-      -> Event t (p k v)-      -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))+  => ( (forall a. k a -> v a -> m (BehaviorWriterTLoweredResult t w v' a))+       -> DMap k v+       -> Event t (p k v)+       -> m (DMap k (BehaviorWriterTLoweredResult t w v'), Event t (p k (BehaviorWriterTLoweredResult t w v')))      )   -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> v' a) -> p k (BehaviorWriterTLoweredResult t w v') -> p k v')   -> ((forall a. BehaviorWriterTLoweredResult t w v' a -> Behavior t w) -> p k (BehaviorWriterTLoweredResult t w v') -> p' (Some k) (Behavior t w))
src/Reflex/BehaviorWriter/Class.hs view
@@ -1,22 +1,23 @@-{-|-Module: Reflex.BehaviorWriter.Class-Description: This module defines the 'BehaviorWriter' class--} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} +-- |+-- Module: Reflex.BehaviorWriter.Class+-- Description: This module defines the 'BehaviorWriter' class module Reflex.BehaviorWriter.Class   ( MonadBehaviorWriter-  , BehaviorWriter(..)+  , BehaviorWriter (..)   ) where  import Control.Monad.Reader (ReaderT, lift)+ import Reflex.Class (Behavior)  {-# DEPRECATED MonadBehaviorWriter "Use 'BehaviorWriter' instead" #-}+ -- | Type synonym for 'BehaviorWriter' type MonadBehaviorWriter = BehaviorWriter 
src/Reflex/Class.hs view
@@ -7,16 +7,16 @@ {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-}-{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE Trustworthy #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE Trustworthy #-}+{-# LANGUAGE NoMonomorphismRestriction #-}  -- | -- Module:@@ -27,6 +27,7 @@ --   signals. module Reflex.Class   ( module Data.Patch+     -- * Primitives   , Reflex (..)   , mergeInt@@ -36,13 +37,16 @@   , coerceIncremental   , MonadSample (..)   , MonadHold (..)+     -- ** 'fan' related types   , EventSelector (..)   , EventSelectorG (..)   , EventSelectorInt (..)+     -- * Convenience functions   , constDyn   , pushAlways+     -- ** Combining 'Event's   , leftmost   , merge@@ -60,6 +64,7 @@   , mergeWith   , difference   , alignEventWithMaybe+     -- ** Breaking up 'Event's   , splitE   , fan@@ -72,19 +77,23 @@   , dsumToEither   , factorEvent   , filterEventKey+     -- ** Collapsing 'Event . Event'   , switchHold   , switchHoldPromptly   , switchHoldPromptOnly   , switchHoldPromptOnlyIncremental+     -- ** Using 'Event's to sample 'Behavior's   , tag   , tagMaybe   , attach   , attachWith   , attachWithMaybe+     -- ** Blocking an 'Event' based on a 'Behavior'   , gate+     -- ** Combining 'Dynamic's   , distributeDMapOverDynPure   , distributeDMapOverDynPureG@@ -92,6 +101,7 @@   , distributeListOverDynWith   , zipDyn   , zipDynWith+     -- ** Accumulating state   , Accumulator (..)   , accumDyn@@ -135,12 +145,15 @@   , dropWhileE   , takeDropWhileJustE   , switcher+     -- * Debugging functions   , traceEvent   , traceEventWith+     -- * Unsafe functions   , unsafeDynamic   , unsafeMapIncremental+     -- * 'Filterable' convenience functions   , FunctorMaybe -- fmapMaybe is purposely not exported from deprecated 'FunctorMaybe' and the new alias is exported instead   , mapMaybe -- Re-exported for convenience@@ -149,14 +162,17 @@   , ffilter   , filterLeft   , filterRight+     -- * Miscellaneous convenience functions   , ffor   , ffor2   , ffor3+     -- * Deprecated functions   , switchPromptly   , switchPromptOnly-  -- * "Cheap" functions++    -- * "Cheap" functions   , fmapMaybeCheap   , mapMaybeCheap   , fmapCheap@@ -166,6 +182,7 @@   , tagCheap   , mergeWithCheap   , mergeWithCheap'+     -- * Slow, but general, implementations   , slowHeadE   ) where@@ -196,88 +213,106 @@ import Data.Coerce import Data.Default import Data.Dependent.Map (DMap)-import Data.Dependent.Sum (DSum (..)) import qualified Data.Dependent.Map as DMap-import Data.Functor.Compose-import Data.Functor.Product-import Data.GADT.Compare (GEq (..), GCompare (..))+import Data.Dependent.Sum (DSum (..)) import Data.Foldable import Data.Functor.Bind+import Data.Functor.Compose import Data.Functor.Misc import Data.Functor.Plus+import Data.Functor.Product+import Data.GADT.Compare (GCompare (..), GEq (..)) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Kind (Type) import Data.List.NonEmpty (NonEmpty (..)) import Data.Map (Map)+import Data.Patch+import qualified Data.Patch.MapWithMove as PatchMapWithMove import Data.Semigroup (Semigroup (..))-import Data.Some (Some(Some))+import Data.Some (Some (Some)) import Data.String import Data.These import Data.Type.Coercion import Data.Type.Equality ((:~:) (..))-import Reflex.FunctorMaybe (FunctorMaybe)-import qualified Reflex.FunctorMaybe-import Data.Patch-import qualified Data.Patch.MapWithMove as PatchMapWithMove-import Witherable (Filterable(..))+import Debug.Trace (trace)+import Witherable (Filterable (..)) import qualified Witherable as W -import Debug.Trace (trace)+import Reflex.FunctorMaybe (FunctorMaybe)+import qualified Reflex.FunctorMaybe  -- | The 'Reflex' class contains all the primitive functionality needed for -- Functional Reactive Programming (FRP).  The @/t/@ type parameter indicates -- which "timeline" is in use.  Timelines are fully-independent FRP contexts, -- and the type of the timeline determines the FRP engine to be used.  For most -- purposes, the 'Reflex.Spider' implementation is recommended.-class ( MonadHold t (PushM t)-      , MonadSample t (PullM t)-      , MonadFix (PushM t)-      , Functor (Dynamic t)-      , Applicative (Dynamic t) -- Necessary for GHC <= 7.8-      , Monad (Dynamic t)-      ) => Reflex t where+class+  ( MonadHold t (PushM t)+  , MonadSample t (PullM t)+  , MonadFix (PushM t)+  , Functor (Dynamic t)+  , Applicative (Dynamic t) -- Necessary for GHC <= 7.8+  , Monad (Dynamic t)+  ) =>+  Reflex t+  where   -- | A container for a value that can change over time.  'Behavior's can be   -- sampled at will, but it is not possible to be notified when they change   data Behavior t :: Type -> Type+   -- | A stream of occurrences.  During any given frame, an 'Event' is either   -- occurring or not occurring; if it is occurring, it will contain a value of   -- the given type (its "occurrence type")   data Event t :: Type -> Type+   -- | A container for a value that can change over time and allows   -- notifications on changes.  Basically a combination of a 'Behavior' and an   -- 'Event', with a rule that the 'Behavior' will change if and only if the   -- 'Event' fires.   data Dynamic t :: Type -> Type+   -- | An 'Incremental' is a more general form of  a 'Dynamic'.   -- Instead of always fully replacing the value, only parts of it can be patched.   -- This is only needed for performance critical code via `mergeIncremental` to make small   -- changes to large values.   data Incremental t :: Type -> Type+   -- | A monad for doing complex push-based calculations efficiently   type PushM t :: Type -> Type+   -- | A monad for doing complex pull-based calculations efficiently   type PullM t :: Type -> Type+   -- | An 'Event' with no occurrences   never :: Event t a+   -- | Create a 'Behavior' that always has the given value-  constant :: a -> Behavior t a --TODO: Refactor to use 'pure' from Applicative instead; however, we need to make sure that encouraging Applicative-style use of 'Behavior's doesn't have a negative performance impact+  constant :: a -> Behavior t a -- TODO: Refactor to use 'pure' from Applicative instead; however, we need to make sure that encouraging Applicative-style use of 'Behavior's doesn't have a negative performance impact+   -- | Create an 'Event' from another 'Event'; the provided function can sample   -- 'Behavior's and hold 'Event's, and use the results to produce a occurring   -- (Just) or non-occurring (Nothing) result   push :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b+   -- | Like 'push' but intended for functions that the implementation can consider cheap to compute for performance considerations. WARNING: The function passed to 'pushCheap' may be run multiple times without any caching.   pushCheap :: (a -> PushM t (Maybe b)) -> Event t a -> Event t b+   -- | Create a 'Behavior' by reading from other 'Behavior's; the result will be   -- recomputed whenever any of the read 'Behavior's changes   pull :: PullM t a -> Behavior t a+   -- | Merge a collection of events; the resulting 'Event' will only occur if at   -- least one input event is occurring, and will contain all of the input keys   -- that are occurring simultaneously -   --TODO: Generalize to get rid of DMap use --TODO: Provide a type-level guarantee that the result is not empty-  mergeG :: GCompare k => (forall a. q a -> Event t (v a))-         -> DMap k q -> Event t (DMap k v)+  -- TODO: Generalize to get rid of DMap use+  -- TODO: Provide a type-level guarantee that the result is not empty+  mergeG+    :: GCompare k+    => (forall a. q a -> Event t (v a))+    -> DMap k q+    -> Event t (DMap k v)    -- | Efficiently fan-out an event to many destinations.  You should save the   -- result in a @let@-binding, and then repeatedly 'selectG' on the result to@@ -287,64 +322,85 @@   -- | Create an 'Event' that will occur whenever the currently-selected input   -- 'Event' occurs   switch :: Behavior t (Event t a) -> Event t a+   -- | Create an 'Event' that will occur whenever the input event is occurring -- and its occurrence value, another 'Event', is also occurring.   --   You maybe looking for '@switchHold@ @never@' instead.   coincidence :: Event t (Event t a) -> Event t a+   -- | Extract the 'Behavior' of a 'Dynamic'.   current :: Dynamic t a -> Behavior t a+   -- | Extract the 'Event' of the 'Dynamic'.   updated :: Dynamic t a -> Event t a+   -- | Create a new 'Dynamic'.  The given 'PullM' must always return the most   -- recent firing of the given 'Event', if any.   unsafeBuildDynamic :: PullM t a -> Event t a -> Dynamic t a+   -- | Create a new 'Incremental'.  The given "PullM"'s value must always change   -- in the same way that the accumulated application of patches would change   -- that value.   unsafeBuildIncremental :: Patch p => PullM t (PatchTarget p) -> Event t p -> Incremental t p+   -- | Create a merge whose parents can change over time-  mergeIncrementalG :: GCompare k+  mergeIncrementalG+    :: GCompare k     => (forall a. q a -> Event t (v a))     -> Incremental t (PatchDMap k q)     -> Event t (DMap k v)+   -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental-  mergeIncrementalWithMoveG :: GCompare k+  mergeIncrementalWithMoveG+    :: GCompare k     => (forall a. q a -> Event t (v a))-    -> Incremental t (PatchDMapWithMove k q) -> Event t (DMap k v)+    -> Incremental t (PatchDMapWithMove k q)+    -> Event t (DMap k v)+   -- | Extract the 'Behavior' component of an 'Incremental'   currentIncremental :: Patch p => Incremental t p -> Behavior t (PatchTarget p)+   -- | Extract the 'Event' component of an 'Incremental'   updatedIncremental :: Patch p => Incremental t p -> Event t p+   -- | Convert an 'Incremental' to a 'Dynamic'   incrementalToDynamic :: Patch p => Incremental t p -> Dynamic t (PatchTarget p)+   -- | Construct a 'Coercion' for a 'Behavior' given an 'Coercion' for its   -- occurrence type   behaviorCoercion :: Coercion a b -> Coercion (Behavior t a) (Behavior t b)+   -- | Construct a 'Coercion' for an 'Event' given an 'Coercion' for its   -- occurrence type   eventCoercion :: Coercion a b -> Coercion (Event t a) (Event t b)+   -- | Construct a 'Coercion' for a 'Dynamic' given an 'Coercion' for its   -- occurrence type   dynamicCoercion :: Coercion a b -> Coercion (Dynamic t a) (Dynamic t b)+   -- | Construct a 'Coercion' for an 'Incremental' given 'Coercion's for its   -- patch target and patch types.   incrementalCoercion     :: Coercion (PatchTarget a) (PatchTarget b) -> Coercion a b -> Coercion (Incremental t a) (Incremental t b)+   mergeIntIncremental :: Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)   fanInt :: Event t (IntMap a) -> EventSelectorInt t a  -- | Efficiently fan-out an event to many destinations. You should save the -- result in a @let@-binding, and then repeatedly 'select' on the result to -- create child events-fan :: forall t k. (Reflex t, GCompare k)-    => Event t (DMap k Identity) -> EventSelector t k-    --TODO: Can we help enforce the partial application discipline here?  The combinator is worthless without it+fan+  :: forall t k+   . (Reflex t, GCompare k)+  => Event t (DMap k Identity) -> EventSelector t k+-- TODO: Can we help enforce the partial application discipline here?  The combinator is worthless without it fan e = EventSelector (fixup (selectG (fanG e) :: k a -> Event t (Identity a)) :: forall a. k a -> Event t a)   where     fixup :: forall a. (k a -> Event t (Identity a)) -> k a -> Event t a     fixup = case eventCoercion Coercion :: Coercion (Event t (Identity a)) (Event t a) of-              Coercion -> coerce+      Coercion -> coerce ---TODO: Specialize this so that we can take advantage of knowing that there's no changing going on+-- TODO: Specialize this so that we can take advantage of knowing that there's no changing going on+ -- | Constructs a single 'Event' out of a map of events. The output event may fire with multiple -- keys simultaneously. mergeInt :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)@@ -402,28 +458,33 @@   hold :: a -> Event t a -> m (Behavior t a)   default hold :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Behavior t a)   hold v0 = lift . hold v0+   -- | Create a 'Dynamic' value using the given initial value that changes every   -- time the 'Event' occurs.   holdDyn :: a -> Event t a -> m (Dynamic t a)   default holdDyn :: (m ~ f m', MonadTrans f, MonadHold t m') => a -> Event t a -> m (Dynamic t a)   holdDyn v0 = lift . holdDyn v0+   -- | Create an 'Incremental' value using the given initial value that changes   -- every time the 'Event' occurs.   holdIncremental :: Patch p => PatchTarget p -> Event t p -> m (Incremental t p)   default holdIncremental :: (Patch p, m ~ f m', MonadTrans f, MonadHold t m') => PatchTarget p -> Event t p -> m (Incremental t p)   holdIncremental v0 = lift . holdIncremental v0+   buildDynamic :: PushM t a -> Event t a -> m (Dynamic t a)+   {-   default buildDynamic :: (m ~ f m', MonadTrans f, MonadHold t m') => PullM t a -> Event t a -> m (Dynamic t a)   buildDynamic getV0 = lift . buildDynamic getV0   -}+   -- | Create a new 'Event' that only occurs only once, on the first occurrence of   -- the supplied 'Event'.   headE :: Event t a -> m (Event t a)+   -- | An event which only occurs at the current moment in time, such that:   --   -- > coincidence (pushAlways (\a -> (a <$) <$> now) e) = e-  --   now :: m (Event t ())   default now :: (m ~ f m', MonadTrans f, MonadHold t m') => m (Event t ())   now = lift now@@ -534,30 +595,30 @@ -- key.  This is much more efficient than filtering for each key with -- 'mapMaybe'. newtype EventSelector t k = EventSelector-  { -- | Retrieve the 'Event' for the given key.  The type of the 'Event' is-    -- determined by the type of the key, so this can be used to fan-out-    -- 'Event's whose sub-'Event's have different types.-    ---    -- Using 'EventSelector's and the 'fan' primitive is far more efficient than-    -- (but equivalent to) using 'mapMaybe' to select only the relevant-    -- occurrences of an 'Event'.-    select :: forall a. k a -> Event t a+  { select :: forall a. k a -> Event t a+  -- ^ Retrieve the 'Event' for the given key.  The type of the 'Event' is+  -- determined by the type of the key, so this can be used to fan-out+  -- 'Event's whose sub-'Event's have different types.+  --+  -- Using 'EventSelector's and the 'fan' primitive is far more efficient than+  -- (but equivalent to) using 'mapMaybe' to select only the relevant+  -- occurrences of an 'Event'.   }  newtype EventSelectorG t k v = EventSelectorG-  { -- | Retrieve the 'Event' for the given key.  The type of the 'Event' is-    -- determined by the type of the key, so this can be used to fan-out-    -- 'Event's whose sub-'Event's have different types.-    ---    -- Using 'EventSelector's and the 'fan' primitive is far more efficient than-    -- (but equivalent to) using 'mapMaybe' to select only the relevant-    -- occurrences of an 'Event'.-    selectG :: forall a. k a -> Event t (v a)+  { selectG :: forall a. k a -> Event t (v a)+  -- ^ Retrieve the 'Event' for the given key.  The type of the 'Event' is+  -- determined by the type of the key, so this can be used to fan-out+  -- 'Event's whose sub-'Event's have different types.+  --+  -- Using 'EventSelector's and the 'fan' primitive is far more efficient than+  -- (but equivalent to) using 'mapMaybe' to select only the relevant+  -- occurrences of an 'Event'.   }  -- | Efficiently select an 'Event' keyed on 'Int'. This is more efficient than manually -- filtering by key.-newtype EventSelectorInt t a = EventSelectorInt { selectInt :: Int -> Event t a }+newtype EventSelectorInt t a = EventSelectorInt {selectInt :: Int -> Event t a}  -------------------------------------------------------------------------------- -- Instances@@ -674,8 +735,8 @@   fromString = pure . fromString  instance Reflex t => Monad (Behavior t) where+  -- Note: it is tempting to write (_ >> b = b); however, this would result in (fail x >> return y) succeeding (returning y), which violates the law that (a >> b = a >>= \_ -> b), since the implementation of (>>=) below actually will fail. Since we can't examine 'Behavior's other than by using sample, I don't think it's possible to write (>>) to be more efficient than the (>>=) below.   a >>= f = pull $ sample a >>= sample . f-  -- Note: it is tempting to write (_ >> b = b); however, this would result in (fail x >> return y) succeeding (returning y), which violates the law that (a >> b = a >>= \_ -> b), since the implementation of (>>=) above actually will fail.  Since we can't examine 'Behavior's other than by using sample, I don't think it's possible to write (>>) to be more efficient than the (>>=) above. #if !MIN_VERSION_base(4,13,0)   fail = error "Monad (Behavior t) does not support fail" #endif@@ -734,10 +795,10 @@  -- | 'Event' intersection. Only occurs when both events are co-incident. instance Reflex t => Apply (Event t) where-  evf <.> evx = mapMaybe f (align evf evx) where-    f (These g a) = Just (g a)-    f _           = Nothing-+  evf <.> evx = mapMaybe f (align evf evx)+    where+      f (These g a) = Just (g a)+      f _ = Nothing  -- | 'Event' intersection (convenient interface to 'coincidence'). instance Reflex t => Bind (Event t) where@@ -813,7 +874,7 @@ -- been encountered later. takeWhileE   :: forall t m a-  .  (Reflex t, MonadFix m, MonadHold t m)+   . (Reflex t, MonadFix m, MonadHold t m)   => (a -> Bool)   -> Event t a   -> m (Event t a)@@ -828,14 +889,14 @@ -- been encountered later. takeWhileJustE   :: forall t m a b-  .  (Reflex t, MonadFix m, MonadHold t m)+   . (Reflex t, MonadFix m, MonadHold t m)   => (a -> Maybe b)   -> Event t a   -> m (Event t b) takeWhileJustE f e = do   rec let (eBad, eTrue) = fanEither $ ffor e' $ \a -> case f a of             Nothing -> Left never-            Just b  -> Right b+            Just b -> Right b       eFirstBad <- headE eBad       e' <- switchHold e eFirstBad   return eTrue@@ -849,7 +910,7 @@ -- would have been encountered later. dropWhileE   :: forall t m a-  .  (Reflex t, MonadFix m, MonadHold t m)+   . (Reflex t, MonadFix m, MonadHold t m)   => (a -> Bool)   -> Event t a   -> m (Event t a)@@ -869,14 +930,14 @@ -- on firing. takeDropWhileJustE   :: forall t m a b-  . (Reflex t, MonadFix m, MonadHold t m)+   . (Reflex t, MonadFix m, MonadHold t m)   => (a -> Maybe b)   -> Event t a   -> m (Event t b, Event t a) takeDropWhileJustE f e = do   rec let (eBad, eGood) = fanEither $ ffor e' $ \a -> case f a of             Nothing -> Left ()-            Just b  -> Right b+            Just b -> Right b       eFirstBad <- headE eBad       e' <- switchHold e (never <$ eFirstBad)   eRest <- switchHoldPromptOnly never (e <$ eFirstBad)@@ -920,12 +981,14 @@ mergeWith :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a mergeWith = mergeWith' id +{- HLINT ignore mergeWith' "Avoid restricted function" -} {-# INLINE mergeWith' #-} mergeWith' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b-mergeWith' f g es = fmap (Prelude.foldl1 g . fmap f)-                  . mergeInt-                  . IntMap.fromDistinctAscList-                  $ zip [0 :: Int ..] es+mergeWith' f g es =+  fmap (Prelude.foldl1 g . fmap f)+    . mergeInt+    . IntMap.fromDistinctAscList+    $ zip [0 :: Int ..] es  -- | Create a new 'Event' that occurs if at least one of the 'Event's in the -- list occurs. If multiple occur at the same time the value is the value of the@@ -955,19 +1018,21 @@ mergeMap :: (Reflex t, Ord k) => Map k (Event t a) -> Event t (Map k a) mergeMap = fmap dmapToMap . merge . mapWithFunctorToDMap --- | Like 'mergeMap' but for 'IntMap'.+-- | Alias for 'mergeInt'.+{-# DEPRECATED mergeIntMap "Use 'mergeInt' instead" #-} mergeIntMap :: Reflex t => IntMap (Event t a) -> Event t (IntMap a)-mergeIntMap = fmap dmapToIntMap . merge . intMapWithFunctorToDMap+mergeIntMap = mergeInt --- | Create a merge whose parents can change over time+-- | Create a merge whose parents can change over time. mergeMapIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Event t a)) -> Event t (Map k a) mergeMapIncremental = fmap dmapToMap . mergeIncremental . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWith id) --- | Create a merge whose parents can change over time+-- | Alias for 'mergeIntIncremental'.+{-# DEPRECATED mergeIntMapIncremental "Use 'mergeIntIncremental' instead" #-} mergeIntMapIncremental :: Reflex t => Incremental t (PatchIntMap (Event t a)) -> Event t (IntMap a)-mergeIntMapIncremental = fmap dmapToIntMap . mergeIncremental . unsafeMapIncremental intMapWithFunctorToDMap (const2IntPatchDMapWith id)+mergeIntMapIncremental = mergeIntIncremental --- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental+-- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental. mergeMapIncrementalWithMove :: (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Event t a)) -> Event t (Map k a) mergeMapIncrementalWithMove = fmap dmapToMap . mergeIncrementalWithMove . unsafeMapIncremental mapWithFunctorToDMap (const2PatchDMapWithMoveWith id) @@ -1052,23 +1117,29 @@ -- | See 'coincidencePatchMap' coincidencePatchMapWithMove :: (Reflex t, Ord k) => Event t (PatchMapWithMove k (Event t v)) -> Event t (PatchMapWithMove k v) coincidencePatchMapWithMove e = fmapCheap unsafePatchMapWithMove $ coincidence $ ffor e $ \p -> mergeMap $ ffor (unPatchMapWithMove p) $ \ni -> case PatchMapWithMove._nodeInfo_from ni of-  PatchMapWithMove.From_Delete -> fforCheap e $ \_ ->-    ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }-  PatchMapWithMove.From_Move k -> fforCheap e $ \_ ->-    ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k }-  PatchMapWithMove.From_Insert ev -> leftmost-    [ fforCheap ev $ \v ->-        ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v }-    , fforCheap e $ \_ ->-        ni { PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete }-    ]+  PatchMapWithMove.From_Delete ->+    fforCheap e+      $ const+      $ ni {PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete}+  PatchMapWithMove.From_Move k ->+    fforCheap e+      $ const+      $ ni {PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Move k}+  PatchMapWithMove.From_Insert ev ->+    leftmost+      [ fforCheap ev $ \v ->+          ni {PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Insert v}+      , fforCheap e+          $ const+          $ ni {PatchMapWithMove._nodeInfo_from = PatchMapWithMove.From_Delete}+      ]  -- | Given a 'PatchTarget' of events (e.g., a 'Map' with 'Event' values) and an event of 'Patch'es -- (e.g., a 'PatchMap' with 'Event' values), produce an 'Event' of the 'PatchTarget' type that -- fires with the patched value. switchHoldPromptOnlyIncremental   :: forall t m p pt w-  .  ( Reflex t+   . ( Reflex t      , MonadHold t m      , Patch (p (Event t w))      , PatchTarget (p (Event t w)) ~ pt (Event t w)@@ -1090,20 +1161,25 @@  instance Reflex t => Align (Event t) where   nil = never+#if !MIN_VERSION_these(0, 8, 0)+  align = alignEventWithMaybe Just+#endif+ #if MIN_VERSION_these(0, 8, 0) instance Reflex t => Semialign (Event t) where-#endif   align = alignEventWithMaybe Just- #ifdef MIN_VERSION_semialign-#if MIN_VERSION_semialign(1,1,0)-instance Reflex t => Zip (Event t) where-#endif+#if !MIN_VERSION_semialign(1,1,0)   zip x y = mapMaybe justThese $ align x y #endif+#endif+#endif  #ifdef MIN_VERSION_semialign #if MIN_VERSION_semialign(1,1,0)+instance Reflex t => Zip (Event t) where+  zip x y = mapMaybe justThese $ align x y+ instance Reflex t => Unzip (Event t) where   unzip = splitE #endif@@ -1116,8 +1192,9 @@  -- | Create a new behavior given a starting behavior and switch to the behavior -- carried by the event when it fires.-switcher :: (Reflex t, MonadHold t m)-        => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a)+switcher+  :: (Reflex t, MonadHold t m)+  => Behavior t a -> Event t (Behavior t a) -> m (Behavior t a) switcher b eb = pull . (sample <=< sample) <$> hold b eb  instance (Reflex t, IsString a) => IsString (Dynamic t a) where@@ -1164,9 +1241,11 @@ -- 'Dynamic' 'DMap'.  Its implementation is more efficient than doing the same -- through the use of multiple uses of 'zipDynWith' or 'Applicative' operators. distributeDMapOverDynPureG-  :: forall t k q v. (Reflex t, GCompare k)+  :: forall t k q v+   . (Reflex t, GCompare k)   => (forall a. q a -> Dynamic t (v a))-  -> DMap k q -> Dynamic t (DMap k v)+  -> DMap k q+  -> Dynamic t (DMap k v) distributeDMapOverDynPureG nt dm = case DMap.toList dm of   [] -> constDyn DMap.empty   [k :=> v] -> DMap.singleton k <$> nt v@@ -1185,10 +1264,10 @@ -- | Create a new 'Dynamic' by applying a combining function to a list of 'Dynamic's distributeListOverDynWith :: Reflex t => ([a] -> b) -> [Dynamic t a] -> Dynamic t b distributeListOverDynWith f =-  fmap (f . map fromDSum . DMap.toAscList) .-  distributeDMapOverDynPure .-  DMap.fromDistinctAscList .-  zipWith toDSum [0..]+  fmap (f . map fromDSum . DMap.toAscList)+    . distributeDMapOverDynPure+    . DMap.fromDistinctAscList+    . zipWith toDSum [0 ..]   where     toDSum :: Int -> Dynamic t a -> DSum (Const2 Int a) (Dynamic t)     toDSum k v = Const2 k :=> v@@ -1205,14 +1284,16 @@ -- | Zips two values by taking the union of their shapes and combining with the provided function. -- 'Nothing' values are dropped. alignEventWithMaybe :: Reflex t => (These a b -> Maybe c) -> Event t a -> Event t b -> Event t c-alignEventWithMaybe f ea eb = mapMaybe (f <=< dmapToThese) $-  merge $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]+alignEventWithMaybe f ea eb =+  mapMaybe (f <=< dmapToThese)+    $ merge+    $ DMap.fromList [LeftTag :=> ea, RightTag :=> eb]  -- | Produces an 'Event' that fires only when the input event fires with a 'DSum' key that -- matches the provided key. filterEventKey-  :: forall t m k v a.-     ( Reflex t+  :: forall t m k v a+   . ( Reflex t      , MonadFix m      , MonadHold t m      , GEq k@@ -1232,8 +1313,8 @@ -- 'DSum' at switchover and an 'Event' of values produced by subsequent -- firings of the input 'Event' that do not change the 'DSum' key. factorEvent-  :: forall t m k v a.-     ( Reflex t+  :: forall t m k v a+   . ( Reflex t      , MonadFix m      , MonadHold t m      , GEq k@@ -1243,12 +1324,13 @@   -> m (Event t (v a), Event t (DSum k (Product v (Compose (Event t) v)))) factorEvent k0 kv' = do   key :: Behavior t (Some k) <- hold (Some k0) $ fmapCheap (\(k :=> _) -> Some k) kv'-  let update = flip push kv' $ \(newKey :=> newVal) -> sample key >>= \case-        Some oldKey -> case newKey `geq` oldKey of-          Just Refl -> return Nothing-          Nothing -> do-            newInner <- filterEventKey newKey kv'-            return $ Just $ newKey :=> Pair newVal (Compose newInner)+  let update = flip push kv' $ \(newKey :=> newVal) ->+        sample key >>= \case+          Some oldKey -> case newKey `geq` oldKey of+            Just Refl -> return Nothing+            Nothing -> do+              newInner <- filterEventKey newKey kv'+              return $ Just $ newKey :=> Pair newVal (Compose newInner)   eInitial <- filterEventKey k0 kv'   return (eInitial, update) @@ -1518,8 +1600,8 @@ zipListWithEvent :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> c) -> [a] -> Event t b -> m (Event t c) zipListWithEvent f l e = do   let f' a b = case a of-        h:t -> (Just t, Just $ f h b)-        _ -> (Nothing, Nothing) --TODO: Unsubscribe the event?+        h : t -> (Just t, Just $ f h b)+        _ -> (Nothing, Nothing) -- TODO: Unsubscribe the event?   mapAccumMaybe_ f' l e  -- | Assign a number to each occurrence of the given 'Event', starting from 0@@ -1568,11 +1650,11 @@ -- A more suggestive example might be: -- -- > handleMouse <$> bPlayerState <*> bMousePosition <@> eMouseClick :: Event t (GameState -> GameState)--- (<@>) :: Reflex t => Behavior t (a -> b) -> Event t a -> Event t b (<@>) b = push $ \x -> do   f <- sample b   return . Just . f $ x+ infixl 4 <@>  -- | An version of '<@>' that does not use the value of the 'Event'.@@ -1601,8 +1683,9 @@ -- -- This is the same as '<@>' except that the 'Event' is being used only -- to act as a trigger.-(<@) :: (Reflex t) => Behavior t b -> Event t a -> Event t b+(<@) :: Reflex t => Behavior t b -> Event t a -> Event t b (<@) = tag+ infixl 4 <@  ------------------@@ -1624,7 +1707,6 @@ fmapMaybeCheap :: Reflex t => (a -> Maybe b) -> Event t a -> Event t b fmapMaybeCheap = mapMaybeCheap - -- | A "cheap" version of 'fforMaybe'. See the performance note on 'pushCheap'. {-# INLINE fforMaybeCheap #-} fforMaybeCheap :: Reflex t => Event t a -> (a -> Maybe b) -> Event t b@@ -1653,12 +1735,14 @@ {-# INLINE merge #-}  -- | Create a merge whose parents can change over time-mergeIncremental :: (Reflex t, GCompare k)+mergeIncremental+  :: (Reflex t, GCompare k)   => Incremental t (PatchDMap k (Event t)) -> Event t (DMap k Identity) mergeIncremental = mergeIncrementalG coerceEvent  -- | Experimental: Create a merge whose parents can change over time; changing the key of an Event is more efficient than with mergeIncremental-mergeIncrementalWithMove :: (Reflex t, GCompare k)+mergeIncrementalWithMove+  :: (Reflex t, GCompare k)   => Incremental t (PatchDMapWithMove k (Event t)) -> Event t (DMap k Identity) mergeIncrementalWithMove = mergeIncrementalWithMoveG coerceEvent @@ -1667,6 +1751,8 @@ mergeWithCheap :: Reflex t => (a -> a -> a) -> [Event t a] -> Event t a mergeWithCheap = mergeWithCheap' id +{- HLINT ignore mergeWithCheap' "Avoid restricted function" -}+ -- | A "cheap" version of 'mergeWithCheap''. See the performance note on 'pushCheap'. {-# INLINE mergeWithCheap' #-} mergeWithCheap' :: Reflex t => (a -> b) -> (b -> b -> b) -> [Event t a] -> Event t b@@ -1676,20 +1762,26 @@ {-# INLINE mergeWithFoldCheap' #-} mergeWithFoldCheap' :: Reflex t => (NonEmpty a -> b) -> [Event t a] -> Event t b mergeWithFoldCheap' f es =-  fmapCheap (f . (\(h : t) -> h :| t) . IntMap.elems)-  . mergeInt-  . IntMap.fromDistinctAscList-  $ zip [0 :: Int ..] es+  fmapCheap (f . nonEmptyElems . IntMap.elems)+    . mergeInt+    . IntMap.fromDistinctAscList+    $ zip [0 :: Int ..] es+  where+    nonEmptyElems (h : t) = h :| t+    nonEmptyElems [] = error "mergeWithFoldCheap': mergeInt fired with an empty IntMap"  -------------------------------------------------------------------------------- -- Deprecated functions --------------------------------------------------------------------------------  {-# DEPRECATED switchPromptly "Use 'switchHoldPromptly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}+ -- | See 'switchHoldPromptly' switchPromptly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a) switchPromptly = switchHoldPromptly+ {-# DEPRECATED switchPromptOnly "Use 'switchHoldPromptOnly' instead. The 'switchHold*' naming convention was chosen because those functions are more closely related to each other than they are to 'switch'. " #-}+ -- | See 'switchHoldPromptOnly' switchPromptOnly :: (Reflex t, MonadHold t m) => Event t a -> Event t (Event t a) -> m (Event t a) switchPromptOnly = switchHoldPromptOnly
src/Reflex/Collection.hs view
@@ -5,6 +5,7 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} @@ -12,15 +13,15 @@ -- Module: --   Reflex.Collection module Reflex.Collection-  (-  -- * Widgets on Collections+  ( -- * Widgets on Collections     listHoldWithKey   , listWithKey   , listWithKeyShallowDiff   , listViewWithKey   , selectViewListWithKey   , selectViewListWithKey_-  -- * List Utils++    -- * List Utils   , list   , simpleList   ) where@@ -38,15 +39,16 @@ import Data.Functor.Misc import Data.Map (Map) import qualified Data.Map as Map-import Data.Map.Misc import Data.These +import Data.Map.Misc+ #if !MIN_VERSION_base(4,18,0) import Control.Monad.Identity #endif -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.Dynamic import Reflex.PostBuild.Class @@ -62,19 +64,22 @@   -> m (Dynamic t (Map k a)) listHoldWithKey m0 m' f = do   let dm0 = mapWithFunctorToDMap $ Map.mapWithKey f m0-      dm' = fmap-        (PatchDMap . mapWithFunctorToDMap . Map.mapWithKey-          (\k v -> ComposeMaybe $ fmap (f k) v)-        )-        m'+      dm' =+        fmap+          ( PatchDMap+              . mapWithFunctorToDMap+              . Map.mapWithKey+                (\k v -> ComposeMaybe $ fmap (f k) v)+          )+          m'   (a0, a') <- sequenceDMapWithAdjust dm0 dm' -  --TODO: Move the dmapToMap to the righthand side so it doesn't get-  --fully redone every time+  -- TODO: Move the dmapToMap to the righthand side so it doesn't get+  -- fully redone every time   fmap dmapToMap . incrementalToDynamic <$> holdIncremental a0 a' ---TODO: Something better than Dynamic t (Map k v) - we want something---where the Events carry diffs, not the whole value+-- TODO: Something better than Dynamic t (Map k v) - we want something+-- where the Events carry diffs, not the whole value listWithKey   :: forall t k v m a    . (Ord k, Adjustable t m, PostBuild t m, MonadFix m, MonadHold t m, Eq v)@@ -93,21 +98,21 @@       -- accounted for.       diffOnlyKeyChanges olds news =         flip Map.mapMaybe (align olds news) $ \case-          This _    -> Just Nothing+          This _ -> Just Nothing           These _ _ -> Nothing-          That new  -> Just $ Just new+          That new -> Just $ Just new   rec sentVals :: Dynamic t (Map k v) <- foldDyn applyMap Map.empty changeVals       let changeVals :: Event t (Map k (Maybe v))           changeVals =-            attachWith diffOnlyKeyChanges (current sentVals) $ leftmost-              [ updated vals--              -- TODO: This should probably be added to the-              -- attachWith, not to the updated; if we were using-              -- diffMap instead of diffMapNoEq, I think it might not-              -- work-              , tag (current vals) postBuild-              ]+            attachWith diffOnlyKeyChanges (current sentVals) $+              leftmost+                [ updated vals+                , -- TODO: This should probably be added to the+                  -- attachWith, not to the updated; if we were using+                  -- diffMap instead of diffMapNoEq, I think it might not+                  -- work+                  tag (current vals) postBuild+                ]   listHoldWithKey Map.empty changeVals $ \k v ->     mkChild k =<< holdUniqDyn =<< holdDyn v (select childValChangedSelector $ Const2 k) @@ -126,24 +131,24 @@   let childValChangedSelector = fanMap $ fmap (Map.mapMaybe id) valsChanged   sentVals <- foldDyn applyMap (void initialVals) $ fmap (fmap void) valsChanged   let relevantPatch patch _ = case patch of-         -- Even if we let a Nothing through when the element doesn't         -- already exist, this doesn't cause a problem because it is         -- ignored         Nothing -> Just Nothing-         -- We don't want to let spurious re-creations of items through-        Just _  -> Nothing+        Just _ -> Nothing   listHoldWithKey-      initialVals-      (attachWith (flip (Map.differenceWith relevantPatch))-                  (current sentVals)-                  valsChanged-      )+    initialVals+    ( attachWith+        (flip (Map.differenceWith relevantPatch))+        (current sentVals)+        valsChanged+    )     $ \k v -> mkChild k v $ select childValChangedSelector $ Const2 k ---TODO: Something better than Dynamic t (Map k v) - we want something---where the Events carry diffs, not the whole value+-- TODO: Something better than Dynamic t (Map k v) - we want something+-- where the Events carry diffs, not the whole value+ -- | Create a dynamically-changing set of Event-valued widgets.  This --   is like 'listWithKey', specialized for widgets returning @/Event t a/@. --   'listWithKey' would return @/Dynamic t (Map k (Event t a))/@ in@@ -185,7 +190,7 @@   selectChild <- listWithKey vals $ \k v -> do     let selected = demuxed selectionDemux k     selectSelf <- mkChild k v selected-    return $ fmap ((,) k) selectSelf+    return $ fmap (k,) selectSelf   return $ switchPromptlyDyn $ leftmost . Map.elems <$> selectChild  -- | Like 'selectViewListWithKey' but discards the value of the list@@ -223,6 +228,8 @@   -> (Dynamic t v -> m a)   -> m (Dynamic t [a]) simpleList xs mkChild =-  fmap (fmap (map snd . Map.toList)) $ flip list mkChild $ fmap-    (Map.fromList . zip [(1 :: Int) ..])-    xs+  fmap (fmap (map snd . Map.toList))+    $ flip list mkChild+    $ fmap+      (Map.fromList . zip [(1 :: Int) ..])+      xs
src/Reflex/Dynamic.hs view
@@ -5,7 +5,6 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-}@@ -14,6 +13,7 @@ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE NoMonomorphismRestriction #-}  -- | -- Module:@@ -62,8 +62,10 @@   , Demux   , demux   , demuxed+     -- * Miscellaneous-    -- Things that probably aren't very useful:++  -- Things that probably aren't very useful:   , HList (..)   , FHList (..)   , collectDynPure@@ -72,6 +74,7 @@   , AllAreFunctors (..)   , HListPtr (..)   , distributeFHListOverDynPure+     -- * Unsafe   , unsafeDynamic   ) where@@ -91,7 +94,6 @@ import Data.Maybe import Data.These import Data.Type.Equality ((:~:) (..))- import Debug.Trace (trace)  #if !MIN_VERSION_base(4,18,0)@@ -166,7 +168,7 @@  -- | Create a new 'Dynamic' that counts the occurrences of the 'Event'. count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b)-count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e+count e = holdDyn 0 =<< zipListWithEvent const (iterate (+ 1) 1) e  -- | Create a new 'Dynamic' using the initial value that flips its -- value every time the 'Event' occurs.@@ -209,7 +211,7 @@  -- | Convert an 'IntMap' with 'Dynamic' elements into a 'Dynamic' of an 'IntMap' with -- non-'Dynamic' elements.-distributeIntMapOverDynPure :: (Reflex t) => IntMap (Dynamic t v) -> Dynamic t (IntMap v)+distributeIntMapOverDynPure :: Reflex t => IntMap (Dynamic t v) -> Dynamic t (IntMap v) distributeIntMapOverDynPure = fmap dmapToIntMap . distributeDMapOverDynPure . intMapWithFunctorToDMap  -- | Convert a list with 'Dynamic' elements into a 'Dynamic' of a list with@@ -218,7 +220,8 @@ distributeListOverDynPure :: Reflex t => [Dynamic t v] -> Dynamic t [v] distributeListOverDynPure = distributeListOverDyn ---TODO: Generalize this to functors other than Maps+-- TODO: Generalize this to functors other than Maps+ -- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic' -- with the current values of the 'Dynamic's in a map. joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a)@@ -226,7 +229,7 @@  -- | Combine a 'Dynamic' of an 'IntMap' of 'Dynamic's into a 'Dynamic' -- with the current values of the 'Dynamic's in a map.-joinDynThroughIntMap :: forall t a. (Reflex t) => Dynamic t (IntMap (Dynamic t a)) -> Dynamic t (IntMap a)+joinDynThroughIntMap :: forall t a. Reflex t => Dynamic t (IntMap (Dynamic t a)) -> Dynamic t (IntMap a) joinDynThroughIntMap = (distributeIntMapOverDynPure =<<)  -- | Print the value of the 'Dynamic' when it is first read and on each@@ -302,39 +305,44 @@ -- outer constructor changes back to 'Nothing'. maybeDyn :: forall t a m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Maybe a) -> m (Dynamic t (Maybe (Dynamic t a))) maybeDyn = fmap (fmap unpack) . eitherDyn . fmap pack-  where pack = \case-          Nothing -> Left ()-          Just a -> Right a-        unpack = \case-          Left _ -> Nothing-          Right a -> Just a+  where+    pack = \case+      Nothing -> Left ()+      Just a -> Right a+    unpack = \case+      Left _ -> Nothing+      Right a -> Just a  -- | Turns a 'Dynamic t (Either a b)' into a 'Dynamic t (Either (Dynamic t a) (Dynamic t b))' such that -- the outer 'Dynamic' is updated only when the 'Either' constructor changes (e.g., from 'Left' to 'Right'). eitherDyn :: forall t a b m. (Reflex t, MonadFix m, MonadHold t m) => Dynamic t (Either a b) -> m (Dynamic t (Either (Dynamic t a) (Dynamic t b))) eitherDyn = fmap (fmap unpack) . factorDyn . fmap eitherToDSum-  where unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)-        unpack = \case-          LeftTag :=> Compose a -> Left $ coerceDynamic a-          RightTag :=> Compose b -> Right $ coerceDynamic b+  where+    unpack :: DSum (EitherTag a b) (Compose (Dynamic t) Identity) -> Either (Dynamic t a) (Dynamic t b)+    unpack = \case+      LeftTag :=> Compose a -> Left $ coerceDynamic a+      RightTag :=> Compose b -> Right $ coerceDynamic b  -- | Factor a 'Dynamic t DSum' into a 'Dynamic' 'DSum' containing nested 'Dynamic' values. -- The outer 'Dynamic' updates only when the key of the 'DSum' changes, while the update of the inner -- 'Dynamic' represents updates within the current key.-factorDyn :: forall t m k v. (Reflex t, MonadHold t m, GEq k)-          => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))-factorDyn d = buildDynamic (sample (current d) >>= holdKey) update  where-  update :: Event t (DSum k (Compose (Dynamic t) v))-  update = flip push (updated d) $ \(newKey :=> newVal) -> do-     (oldKey :=> _) <- sample (current d)-     case newKey `geq` oldKey of-      Just Refl -> return Nothing-      Nothing -> Just <$> holdKey (newKey :=> newVal)+factorDyn+  :: forall t m k v+   . (Reflex t, MonadHold t m, GEq k)+  => Dynamic t (DSum k v) -> m (Dynamic t (DSum k (Compose (Dynamic t) v)))+factorDyn d = buildDynamic (sample (current d) >>= holdKey) update+  where+    update :: Event t (DSum k (Compose (Dynamic t) v))+    update = flip push (updated d) $ \(newKey :=> newVal) -> do+      (oldKey :=> _) <- sample (current d)+      case newKey `geq` oldKey of+        Just Refl -> return Nothing+        Nothing -> Just <$> holdKey (newKey :=> newVal) -  holdKey (k :=> v) = do-    inner' <- filterEventKey k (updated d)-    inner <- holdDyn v inner'-    return $ k :=> Compose inner+    holdKey (k :=> v) = do+      inner' <- filterEventKey k (updated d)+      inner <- holdDyn v inner'+      return $ k :=> Compose inner  -------------------------------------------------------------------------------- -- Demux@@ -351,19 +359,31 @@ -- -- However, when 'demuxed' is used multiple times, the complexity is only -- /O(log(n))/, rather than /O(n)/ for fmap.-data Demux t k = Demux { demuxValue :: Behavior t k-                       , demuxSelector :: EventSelector t (Const2 k Bool)-                       }+data Demux t k = Demux+  { demuxValue :: Behavior t k+  , demuxSelector :: EventSelector t (Const2 k Bool)+  }  -- | Demultiplex an input value to a 'Demux' with many outputs.  At any given -- time, whichever output is indicated by the given 'Dynamic' will be 'True'. demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k-demux k = Demux (current k)-                (fan $ attachWith (\k0 k1 -> if k0 == k1-                                                then DMap.empty-                                                else DMap.fromList [Const2 k0 :=> Identity False,-                                                                    Const2 k1 :=> Identity True])-                                  (current k) (updated k))+demux k =+  Demux+    (current k)+    ( fan $+        attachWith+          ( \k0 k1 ->+              if k0 == k1+                then DMap.empty+                else+                  DMap.fromList+                    [ Const2 k0 :=> Identity False+                    , Const2 k1 :=> Identity True+                    ]+          )+          (current k)+          (updated k)+    )  -- | Select a particular output of the 'Demux'; this is equivalent to (but much -- faster than) mapping over the original 'Dynamic' and checking whether it is@@ -371,19 +391,19 @@ demuxed :: (Reflex t, Eq k) => Demux t k -> k -> Dynamic t Bool demuxed d k =   let e = select (demuxSelector d) (Const2 k)-  in unsafeBuildDynamic (fmap (==k) $ sample $ demuxValue d) e+  in unsafeBuildDynamic (fmap (== k) $ sample $ demuxValue d) e  -------------------------------------------------------------------------------- -- collectDyn -------------------------------------------------------------------------------- ---TODO: This whole section is badly in need of cleanup+-- TODO: This whole section is badly in need of cleanup  -- | A heterogeneous list whose type and length are fixed statically.  This is -- reproduced from the 'HList' package due to integration issues, and because -- very little other functionality from that library is needed.-data HList (l::[Type]) where-  HNil  :: HList '[]+data HList (l :: [Type]) where+  HNil :: HList '[]   HCons :: e -> HList l -> HList (e ': l)  infixr 2 `HCons`@@ -399,18 +419,22 @@ hReverse :: HList l -> HList (HRevApp l '[]) hReverse l = hRevApp l HNil -hBuild :: (HBuild' '[] r) => r-hBuild =  hBuild' HNil+hBuild :: HBuild' '[] r => r+hBuild = hBuild' HNil  class HBuild' l r where-    hBuild' :: HList l -> r+  hBuild' :: HList l -> r -instance (l' ~ HRevApp l '[])-      => HBuild' l (HList l') where+instance+  l' ~ HRevApp l '[]+  => HBuild' l (HList l')+  where   hBuild' = hReverse -instance HBuild' (a ': l) r-      => HBuild' l (a->r) where+instance+  HBuild' (a ': l) r+  => HBuild' l (a -> r)+  where   hBuild' l x = hBuild' (HCons x l)  -- | Like 'HList', but with a functor wrapping each element.@@ -440,10 +464,11 @@  fhlistToDMap :: forall (f :: Type -> Type) l. FHList f l -> DMap (HListPtr l) f fhlistToDMap = DMap.fromList . go-  where go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]-        go = \case-          FHNil -> []-          FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)+  where+    go :: forall l'. FHList f l' -> [DSum (HListPtr l') f]+    go = \case+      FHNil -> []+      FHCons h t -> (HHeadPtr :=> h) : map (\(p :=> v) -> HTailPtr p :=> v) (go t)  -- | This class allows 'HList's and 'FHlist's to be built from regular lists; -- they must be contiguous and sorted.@@ -461,12 +486,17 @@  instance RebuildSortedHList t => RebuildSortedHList (h ': t) where   rebuildSortedFHList l = case l of-    ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t+    ((HHeadPtr :=> h) : t) -> FHCons h . rebuildSortedFHList . map fromTailPtr $ t     _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected"   rebuildSortedHList l = case l of-    ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map (\(HTailPtr p :=> v) -> p :=> v) $ t+    ((HHeadPtr :=> Identity h) : t) -> HCons h . rebuildSortedHList . map fromTailPtr $ t     _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected" +-- | Change the key of an element of the list for @h ': t@ into a key for @t@.+fromTailPtr :: DSum (HListPtr (h ': t)) f -> DSum (HListPtr t) f+fromTailPtr (HTailPtr p :=> v) = p :=> v+fromTailPtr (HHeadPtr :=> _) = error "rebuildSortedHList{h':t}: HHeadPtr after the first element"+ dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) Identity -> HList l dmapToHList = rebuildSortedHList . DMap.toList @@ -487,29 +517,26 @@   type FunctorList f '[] = '[]   toFHList l = case l of     HNil -> FHNil-#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800-    _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139-#endif   fromFHList FHNil = HNil  instance AllAreFunctors f t => AllAreFunctors f (h ': t) where   type FunctorList f (h ': t) = f h ': FunctorList f t   toFHList l = case l of     a `HCons` b -> a `FHCons` toFHList b-#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800-    _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139-#endif   fromFHList (a `FHCons` b) = a `HCons` fromFHList b  -- | Convert a datastructure whose constituent parts are all 'Dynamic's into a -- single 'Dynamic' whose value represents all the current values of the input's -- constituent 'Dynamic's.-collectDynPure :: ( RebuildSortedHList (HListElems b)-                  , IsHList a, IsHList b-                  , AllAreFunctors (Dynamic t) (HListElems b)-                  , Reflex t-                  , HListElems a ~ FunctorList (Dynamic t) (HListElems b)-                  ) => a -> Dynamic t b+collectDynPure+  :: ( RebuildSortedHList (HListElems b)+     , IsHList a+     , IsHList b+     , AllAreFunctors (Dynamic t) (HListElems b)+     , Reflex t+     , HListElems a ~ FunctorList (Dynamic t) (HListElems b)+     )+  => a -> Dynamic t b collectDynPure ds = fmap fromHList $ distributeFHListOverDynPure $ toFHList $ toHList ds  -- | Poor man's 'Generic's for product types only.@@ -523,24 +550,15 @@   toHList (a, b) = hBuild a b   fromHList l = case l of     a `HCons` b `HCons` HNil -> (a, b)-#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800-    _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139-#endif  instance IsHList (a, b, c, d) where   type HListElems (a, b, c, d) = [a, b, c, d]   toHList (a, b, c, d) = hBuild a b c d   fromHList l = case l of     a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d)-#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800-    _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139-#endif  instance IsHList (a, b, c, d, e, f) where   type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f]   toHList (a, b, c, d, e, f) = hBuild a b c d e f   fromHList l = case l of     a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f)-#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ < 800-    _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139-#endif
src/Reflex/Dynamic/TH.hs view
@@ -38,27 +38,30 @@       f d = case eqT of         Just (Refl :: d :~: Exp)           | AppE (VarE m) eInner <- d-          , m == 'unqMarker-          -> do n <- lift $ newName "dynamicQuotedExpressionVariable"-                modify ((n, eInner):)+          , m == 'unqMarker ->+              do+                n <- lift $ newName "dynamicQuotedExpressionVariable"+                modify ((n, eInner) :)                 return $ VarE n         _ -> gmapM f d   (e', exprsReversed) <- runStateT (gmapM f e) []   let exprs = reverse exprsReversed-      arg = foldr-        (\(_, expr) rest -> [e| FHCons $(pure expr) $rest |])-        [e| FHNil |]-        exprs-      param = foldr-        (\(name, _) rest -> [p| HCons $(pure $ VarP name) $rest |])-        [p| HNil |]-        exprs-  [| (\ $param -> $(pure e')) <$> distributeFHListOverDynPure $arg |]+      arg =+        foldr+          (\(_, expr) rest -> [e|FHCons $(pure expr) $rest|])+          [e|FHNil|]+          exprs+      param =+        foldr+          (\(name, _) rest -> [p|HCons $(pure $ VarP name) $rest|])+          [p|HNil|]+          exprs+  [|(\ $param -> $(pure e')) <$> distributeFHListOverDynPure $arg|]  -- | Antiquote a 'Dynamic' expression.  This can /only/ be used inside of a -- 'qDyn' quotation. unqDyn :: Q Exp -> Q Exp-unqDyn e = [| unqMarker $e |]+unqDyn e = [|unqMarker $e|]  -- | This type represents an occurrence of unqDyn before it has been processed -- by qDyn.  If you see it in a type error, it probably means that unqDyn has@@ -68,7 +71,7 @@ -- unqMarker must not be exported; it is used only as a way of smuggling data -- from unqDyn to qDyn ---TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery+-- TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery unqMarker :: a -> UnqDyn unqMarker = error "An unqDyn expression was used outside of a qDyn expression" @@ -80,25 +83,30 @@ -- -- would have a very cumbersome 'Applicative' encoding. mkDynPure :: QuasiQuoter-mkDynPure = QuasiQuoter-  { quoteExp = mkDynExp-  , quotePat = error "mkDyn: pattern splices are not supported"-  , quoteType = error "mkDyn: type splices are not supported"-  , quoteDec = error "mkDyn: declaration splices are not supported"-  }+mkDynPure =+  QuasiQuoter+    { quoteExp = mkDynExp+    , quotePat = error "mkDyn: pattern splices are not supported"+    , quoteType = error "mkDyn: type splices are not supported"+    , quoteDec = error "mkDyn: declaration splices are not supported"+    }  mkDynExp :: String -> Q Exp-mkDynExp s = case Hs.parseExpWithMode Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] } s of+mkDynExp s = case Hs.parseExpWithMode Hs.defaultParseMode {Hs.extensions = [Hs.EnableExtension Hs.TemplateHaskell]} s of   Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err   Hs.ParseOk e -> qDynPure $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e-    where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker-          antiE :: Hs.Exp Hs.SrcSpanInfo -> Hs.Exp Hs.SrcSpanInfo-          antiE x = case x of-            Hs.SpliceExp l se ->-              Hs.App l (Hs.Var l $ Hs.Qual l (Hs.ModuleName l modName) (Hs.Ident l occName)) $ case se of-                Hs.IdSplice l2 v -> Hs.Var l2 $ Hs.UnQual l2 $ Hs.Ident l2 v-                Hs.ParenSplice _ ps -> ps-            _ -> x-          reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))-            | modName == modName' && occName == occName' = 'unqMarker-          reinstateUnqDyn x = x+    where+      (occName, modName) = case 'unqMarker of+        TH.Name (TH.OccName o) (TH.NameG _ _ (TH.ModName m)) -> (o, m)+        _ -> error "mkDyn: 'unqMarker is not a global name"+      antiE :: Hs.Exp Hs.SrcSpanInfo -> Hs.Exp Hs.SrcSpanInfo+      antiE x = case x of+        Hs.SpliceExp l se ->+          Hs.App l (Hs.Var l $ Hs.Qual l (Hs.ModuleName l modName) (Hs.Ident l occName)) $ case se of+            Hs.IdSplice l2 v -> Hs.Var l2 $ Hs.UnQual l2 $ Hs.Ident l2 v+            Hs.ParenSplice _ ps -> ps+            _ -> error "mkDyn: typed splices are not supported"+        _ -> x+      reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName')))+        | modName == modName' && occName == occName' = 'unqMarker+      reinstateUnqDyn x = x
src/Reflex/Dynamic/Uniq.hs view
@@ -29,12 +29,12 @@ -- unnecessary update propagation; this is much more efficient than performing -- full comparisons.  However, when the 'UniqDynamic' is converted back into a -- regular 'Dynamic', a full comparison is performed.-newtype UniqDynamic t a = UniqDynamic { unUniqDynamic :: Dynamic t a }+newtype UniqDynamic t a = UniqDynamic {unUniqDynamic :: Dynamic t a}  -- | Construct a 'UniqDynamic' by eliminating redundant updates from a 'Dynamic'. uniqDynamic :: Reflex t => Dynamic t a -> UniqDynamic t a uniqDynamic d = UniqDynamic $ unsafeBuildDynamic (sample $ current d) $ flip pushCheap (updated d) $ \new -> do-  old <- sample $ current d --TODO: Is it better to sample ourselves here?+  old <- sample $ current d -- TODO: Is it better to sample ourselves here?   return $ unsafeJustChanged old new  -- | Retrieve a normal 'Dynamic' from a 'UniqDynamic'.  This will perform a@@ -75,8 +75,8 @@ unsafeJustChanged :: a -> a -> Maybe a unsafeJustChanged old new =   if old `unsafePtrEq` new-  then Nothing-  else Just new+    then Nothing+    else Just new  instance Reflex t => Accumulator t (UniqDynamic t) where   accumMaybeM f z e = do
src/Reflex/DynamicWriter/Base.hs view
@@ -6,11 +6,11 @@ {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE StandaloneDeriving #-}  module Reflex.DynamicWriter.Base   ( DynamicWriterT (..)@@ -19,7 +19,7 @@   ) where  import Control.Monad-import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.IO.Class@@ -31,7 +31,6 @@ import Data.Align import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap-import Data.FastMutableIntMap import Data.Functor.Misc import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap@@ -40,17 +39,20 @@ import Data.Some (Some) import Data.These +import Data.FastMutableIntMap+ #if !MIN_VERSION_base(4,18,0) import Control.Monad.Identity import Data.Semigroup (Semigroup(..)) #endif +import qualified Data.Patch.MapWithMove as MapWithMove+ import Reflex.Adjustable.Class import Reflex.Class import Reflex.DynamicWriter.Class import Reflex.EventWriter.Class (EventWriter, tellEvent) import Reflex.Host.Class-import qualified Data.Patch.MapWithMove as MapWithMove import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.Query.Class@@ -62,57 +64,60 @@  mergeDynIncremental :: (Reflex t, Ord k) => Incremental t (PatchMap k (Dynamic t v)) -> Incremental t (PatchMap k v) mergeDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues-  where changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a-        addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m+  where+    changedValues = fmap (PatchMap . fmap Just) $ mergeMapIncremental $ mapIncrementalMapValues updated a+    addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchMap m) -> PatchMap <$> mapM (mapM (sample . current)) m -mergeIntMapDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)-mergeIntMapDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues-  where changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntMapIncremental $ mapIncrementalMapValues updated a-        addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m+mergeIntDynIncremental :: Reflex t => Incremental t (PatchIntMap (Dynamic t v)) -> Incremental t (PatchIntMap v)+mergeIntDynIncremental a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ addedAndRemovedValues <> changedValues+  where+    changedValues = fmap (PatchIntMap . fmap Just) $ mergeIntIncremental $ mapIncrementalMapValues updated a+    addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ \(PatchIntMap m) -> PatchIntMap <$> mapM (mapM (sample . current)) m  mergeDynIncrementalWithMove :: forall t k v. (Reflex t, Ord k) => Incremental t (PatchMapWithMove k (Dynamic t v)) -> Incremental t (PatchMapWithMove k v) mergeDynIncrementalWithMove a = unsafeBuildIncremental (mapM (sample . current) =<< sample (currentIncremental a)) $ alignWith f addedAndRemovedValues changedValues-  where changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a-        addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove-        f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v-        f x = unsafePatchMapWithMove $-          let (p, changed) = case x of-                This p_ -> (unPatchMapWithMove p_, mempty)-                That c -> (mempty, c)-                These p_ c -> (unPatchMapWithMove p_, c)-              (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case-                MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v-                MapWithMove.From_Delete -> return MapWithMove.From_Delete-                MapWithMove.From_Move k -> case Map.lookup k changed of-                  Nothing -> return $ MapWithMove.From_Move k-                  Just v -> do-                    modify (k:)-                    return $ MapWithMove.From_Insert v-              noLongerMovedMap = Map.fromList $ fmap (, ()) noLongerMoved-          in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap --TODO: Check if any in the second map are not covered?+  where+    changedValues = mergeMapIncrementalWithMove $ mapIncrementalMapValues updated a+    addedAndRemovedValues = flip pushAlways (updatedIncremental a) $ fmap unsafePatchMapWithMove . mapM (mapM (sample . current)) . unPatchMapWithMove+    f :: These (PatchMapWithMove k v) (Map k v) -> PatchMapWithMove k v+    f x =+      unsafePatchMapWithMove $+        let (p, changed) = case x of+              This p_ -> (unPatchMapWithMove p_, mempty)+              That c -> (mempty, c)+              These p_ c -> (unPatchMapWithMove p_, c)+            (pWithNewVals, noLongerMoved) = flip runState [] $ forM p $ MapWithMove.nodeInfoMapMFrom $ \case+              MapWithMove.From_Insert v -> return $ MapWithMove.From_Insert v+              MapWithMove.From_Delete -> return MapWithMove.From_Delete+              MapWithMove.From_Move k -> case Map.lookup k changed of+                Nothing -> return $ MapWithMove.From_Move k+                Just v -> do+                  modify (k :)+                  return $ MapWithMove.From_Insert v+            noLongerMovedMap = Map.fromList $ fmap (,()) noLongerMoved+        in Map.differenceWith (\e _ -> Just $ MapWithMove.nodeInfoSetTo Nothing e) pWithNewVals noLongerMovedMap -- TODO: Check if any in the second map are not covered?  -- | A basic implementation of 'DynamicWriter'.-newtype DynamicWriterT t w m a = DynamicWriterT { unDynamicWriterT :: StateT [Dynamic t w] m a }+newtype DynamicWriterT t w m a = DynamicWriterT {unDynamicWriterT :: StateT [Dynamic t w] m a}   -- The list is kept in reverse order   deriving-    ( Functor-    , Applicative-    , Monad-    , MonadTrans+    ( Applicative+    , Functor     , MFunctor-    , MonadIO-    , MonadFix+    , Monad     , MonadAsyncException-    , MonadException     , MonadCatch-    , MonadThrow+    , MonadException+    , MonadFix+    , MonadIO     , MonadMask+    , MonadThrow+    , MonadTrans     )  deriving instance MonadHold t m => MonadHold t (DynamicWriterT t w m) deriving instance MonadSample t m => MonadSample t (DynamicWriterT t w m) - instance MonadRef m => MonadRef (DynamicWriterT t w m) where   type Ref (DynamicWriterT t w m) = Ref m   newRef = lift . newRef@@ -172,15 +177,17 @@     (result0, result') <- lift $ runWithReplace (runDynamicWriterT a0) $ runDynamicWriterT <$> a'     tellDyn . join =<< holdDyn (snd result0) (snd <$> result')     return (fst result0, fst <$> result')-  traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntMapDynIncremental+  traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustImpl traverseIntMapWithKeyWithAdjust mergeIntDynIncremental   traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap weakenPatchDMapWith mergeDynIncremental   traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove weakenPatchDMapWithMoveWith mergeDynIncrementalWithMove -traverseDMapWithKeyWithAdjustImpl :: forall t w k v' p p' v m. (PatchTarget (p' (Some k) (Dynamic t w)) ~ Map (Some k) (Dynamic t w), PatchTarget (p' (Some k) w) ~ Map (Some k) w, Patch (p' (Some k) w), Patch (p' (Some k) (Dynamic t w)), Monoid w, Reflex t, MonadHold t m)-  => (   (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))-      -> DMap k v-      -> Event t (p k v)-      -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))+traverseDMapWithKeyWithAdjustImpl+  :: forall t w k v' p p' v m+   . (PatchTarget (p' (Some k) (Dynamic t w)) ~ Map (Some k) (Dynamic t w), PatchTarget (p' (Some k) w) ~ Map (Some k) w, Patch (p' (Some k) w), Patch (p' (Some k) (Dynamic t w)), Monoid w, Reflex t, MonadHold t m)+  => ( (forall a. k a -> v a -> m (DynamicWriterTLoweredResult t w v' a))+       -> DMap k v+       -> Event t (p k v)+       -> m (DMap k (DynamicWriterTLoweredResult t w v'), Event t (p k (DynamicWriterTLoweredResult t w v')))      )   -> ((forall a. DynamicWriterTLoweredResult t w v' a -> v' a) -> p k (DynamicWriterTLoweredResult t w v') -> p k v')   -> ((forall a. DynamicWriterTLoweredResult t w v' a -> Dynamic t w) -> p k (DynamicWriterTLoweredResult t w v') -> p' (Some k) (Dynamic t w))@@ -198,16 +205,18 @@       liftedWritten0 :: Map (Some k) (Dynamic t w)       liftedWritten0 = weakenDMapWith getWritten result0       liftedWritten' = ffor result' $ weakenPatchWith getWritten-  --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics+  -- TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics   i <- holdIncremental liftedWritten0 liftedWritten'   tellDyn $ fmap (mconcat . Map.elems) $ incrementalToDynamic $ mergeMyDynIncremental i   return (liftedResult0, liftedResult') -traverseIntMapWithKeyWithAdjustImpl :: forall t w v' p p' v m. (PatchTarget (p' (Dynamic t w)) ~ IntMap (Dynamic t w), PatchTarget (p' w) ~ IntMap w, Patch (p' w), Patch (p' (Dynamic t w)), Monoid w, Reflex t, MonadHold t m, Functor p, p ~ p')-  => (   (IntMap.Key -> v -> m (v', Dynamic t w))-      -> IntMap v-      -> Event t (p v)-      -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))+traverseIntMapWithKeyWithAdjustImpl+  :: forall t w v' p p' v m+   . (PatchTarget (p' (Dynamic t w)) ~ IntMap (Dynamic t w), PatchTarget (p' w) ~ IntMap w, Patch (p' w), Patch (p' (Dynamic t w)), Monoid w, Reflex t, MonadHold t m, Functor p, p ~ p')+  => ( (IntMap.Key -> v -> m (v', Dynamic t w))+       -> IntMap v+       -> Event t (p v)+       -> m (IntMap (v', Dynamic t w), Event t (p (v', Dynamic t w)))      )   -> (Incremental t (p' (Dynamic t w)) -> Incremental t (p' w))   -> (IntMap.Key -> v -> DynamicWriterT t w m v')@@ -221,16 +230,17 @@       liftedWritten0 :: IntMap (Dynamic t w)       liftedWritten0 = fmap snd result0       liftedWritten' = fmap (fmap snd) result'-  --TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics+  -- TODO: We should be able to improve the performance here by incrementally updating the mconcat of the merged Dynamics   i <- holdIncremental liftedWritten0 liftedWritten'   tellDyn $ fmap (mconcat . IntMap.elems) $ incrementalToDynamic $ mergeMyDynIncremental i   return (liftedResult0, liftedResult')  -- | Map a function over the output of a 'DynamicWriterT'.-withDynamicWriterT :: (Monoid w, Monoid w', Reflex t, MonadHold t m)-                   => (w -> w')-                   -> DynamicWriterT t w m a-                   -> DynamicWriterT t w' m a+withDynamicWriterT+  :: (Monoid w, Monoid w', Reflex t, MonadHold t m)+  => (w -> w')+  -> DynamicWriterT t w m a+  -> DynamicWriterT t w' m a withDynamicWriterT f dw = do   (r, d) <- lift $ do     (r, d) <- runDynamicWriterT dw
src/Reflex/DynamicWriter/Class.hs view
@@ -1,19 +1,21 @@--- | This module defines the 'DynamicWriter' class.-{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-}+{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines the 'DynamicWriter' class. module Reflex.DynamicWriter.Class   ( MonadDynamicWriter-  , DynamicWriter(..)+  , DynamicWriter (..)   ) where  import Control.Monad.Reader (ReaderT, lift)+ import Reflex.Class (Dynamic)  {-# DEPRECATED MonadDynamicWriter "Use 'DynamicWriter' instead" #-}+ -- | Type synonym for 'DynamicWriter' type MonadDynamicWriter = DynamicWriter 
src/Reflex/EventWriter/Base.hs view
@@ -1,5 +1,3 @@--- | This module provides 'EventWriterT', the standard implementation of--- 'EventWriter'. {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleInstances #-}@@ -11,6 +9,8 @@ {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module provides 'EventWriterT', the standard implementation of+-- 'EventWriter'. module Reflex.EventWriter.Base   ( EventWriterT (..)   , runEventWriterT@@ -20,21 +20,9 @@   , withEventWriterT   ) where -import Reflex.Adjustable.Class-import Reflex.Class-import Reflex.EventWriter.Class (EventWriter, tellEvent)-import Reflex.DynamicWriter.Class (DynamicWriter, tellDyn)-import Reflex.Host.Class-import Reflex.PerformEvent.Class-import Reflex.PostBuild.Class-import Reflex.Query.Class-import Reflex.Requester.Class-import Reflex.TriggerEvent.Class--import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix-import Control.Monad.Identity import Control.Monad.Morph import Control.Monad.Primitive import Control.Monad.Reader@@ -42,10 +30,9 @@ import Control.Monad.State.Strict import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap-import Data.Dependent.Sum (DSum (..)) import Data.Functor.Compose import Data.Functor.Misc-import Data.GADT.Compare (GCompare (..), GEq (..), GOrdering (..))+import Data.GADT.Compare (GCompare) import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.List.NonEmpty (NonEmpty (..))@@ -54,98 +41,75 @@ import Data.Semigroup import Data.Some (Some) import Data.Tuple-import Data.Type.Equality -import Unsafe.Coerce--{-# DEPRECATED TellId "Do not construct this directly; use tellId instead" #-}-newtype TellId w x-  = TellId Int -- ^ WARNING: Do not construct this directly; use 'tellId' instead-  deriving (Show, Eq, Ord, Enum)--tellId :: Int -> TellId w w-tellId = TellId-{-# INLINE tellId #-}--tellIdRefl :: TellId w x -> w :~: x-tellIdRefl _ = unsafeCoerce Refl--withTellIdRefl :: TellId w x -> (w ~ x => r) -> r-withTellIdRefl tid r = case tellIdRefl tid of-  Refl -> r--instance GEq (TellId w) where-  a `geq` b =-    withTellIdRefl a $-    withTellIdRefl b $-    if a == b-    then Just Refl-    else Nothing--instance GCompare (TellId w) where-  a `gcompare` b =-    withTellIdRefl a $-    withTellIdRefl b $-    case a `compare` b of-      LT -> GLT-      EQ -> GEQ-      GT -> GGT--data EventWriterState t w = EventWriterState-  { _eventWriterState_nextId :: {-# UNPACK #-} !Int -- Always negative (and decreasing over time)-  , _eventWriterState_told :: ![DSum (TellId w) (Event t)] -- In increasing order-  }+import Reflex.Adjustable.Class+import Reflex.Class+import Reflex.DynamicWriter.Class (DynamicWriter, tellDyn)+import Reflex.EventWriter.Class (EventWriter, tellEvent)+import Reflex.Host.Class+import Reflex.PerformEvent.Class+import Reflex.PostBuild.Class+import Reflex.Query.Class+import Reflex.Requester.Class+import Reflex.TriggerEvent.Class  -- | A basic implementation of 'EventWriter'.-newtype EventWriterT t w m a = EventWriterT { unEventWriterT :: StateT (EventWriterState t w) m a }+newtype EventWriterT t w m a = EventWriterT {unEventWriterT :: StateT [Event t w] m a}   deriving-    ( Functor-    , Applicative-    , Monad-    , MonadTrans+    ( Applicative+    , Functor     , MFunctor+    , Monad+    , MonadAsyncException+    , MonadCatch+    , MonadException     , MonadFix     , MonadIO-    , MonadException-    , MonadAsyncException     , MonadMask-    , MonadCatch     , MonadThrow+    , MonadTrans     ) +-- TODO: When 'Data.IntMap.fromDistinctDescList' becomes available+-- (https://github.com/haskell/containers/pull/1194), key the reversed list with+-- descending keys instead, so that 'combineResults' can use 'IntMap.elems'+-- directly.++-- TODO: If the 'Semigroup' were known to be commutative, the intermediate+-- 'IntMap's could be avoided. (See+-- https://github.com/reflex-frp/reflex/issues/538)+ -- | Run a 'EventWriterT' action. runEventWriterT :: forall t m w a. (Reflex t, Monad m, Semigroup w) => EventWriterT t w m a -> m (a, Event t w) runEventWriterT (EventWriterT a) = do-  (result, requests) <- runStateT a $ EventWriterState (-1) []-  let combineResults :: DMap (TellId w) Identity -> w-      combineResults = sconcat-        . (\(h : t) -> h :| t) -- Unconditional; 'merge' guarantees that it will only fire with non-empty DMaps-        . DMap.foldlWithKey (\vs tid (Identity v) -> withTellIdRefl tid $ v : vs) [] -- This is where we finally reverse the DMap to get things in the correct order-  return (result, fmap combineResults $ merge $ DMap.fromDistinctAscList $ _eventWriterState_told requests) --TODO: We can probably make this fromDistinctAscList more efficient by knowing the length in advance, but this will require exposing internals of DMap; also converting it to use a strict list might help+  (result, told) <- runStateT a []+  let combineResults :: IntMap w -> w+      combineResults =+        sconcat+          . nonEmptyElems+          . IntMap.foldl (flip (:)) [] -- Ascending key order is reverse tell order, so prepend while traversing to restore tell order+      nonEmptyElems (h : t) = h :| t+      nonEmptyElems [] = error "runEventWriterT: mergeInt fired with an empty IntMap"+  return (result, fmap combineResults $ mergeInt $ IntMap.fromDistinctAscList $ zip [0 ..] told)  instance (Reflex t, Monad m, Semigroup w) => EventWriter t w (EventWriterT t w m) where-  tellEvent w = EventWriterT $ modify $ \old ->-    let myId = _eventWriterState_nextId old-    in EventWriterState-       { _eventWriterState_nextId = pred myId-       , _eventWriterState_told = (tellId myId :=> w) : _eventWriterState_told old-       }+  tellEvent w = EventWriterT $ modify (w :)  instance MonadSample t m => MonadSample t (EventWriterT t w m) where   sample = lift . sample  instance MonadHold t m => MonadHold t (EventWriterT t w m) where-  {-# INLINABLE hold #-}+  {-# INLINEABLE hold #-}   hold v0 = lift . hold v0-  {-# INLINABLE holdDyn #-}+  {-# INLINEABLE holdDyn #-}   holdDyn v0 = lift . holdDyn v0-  {-# INLINABLE holdIncremental #-}+  {-# INLINEABLE holdIncremental #-}   holdIncremental v0 = lift . holdIncremental v0-  {-# INLINABLE buildDynamic #-}+  {-# INLINEABLE buildDynamic #-}   buildDynamic a0 = lift . buildDynamic a0-  {-# INLINABLE headE #-}+  {-# INLINEABLE headE #-}   headE = lift . headE-  {-# INLINABLE now #-}+  {-# INLINEABLE now #-}   now = lift now  instance (Reflex t, Adjustable t m, MonadHold t m, Semigroup w) => Adjustable t (EventWriterT t w m) where@@ -164,11 +128,13 @@ -- 'runWithReplace' for 'EventWriterT'.  This is necessary when the underlying -- monad doesn't have a 'Adjustable' instance or to override the default -- 'Adjustable' behavior.-runWithReplaceEventWriterTWith :: forall m t w a b. (Reflex t, MonadHold t m, Semigroup w)-                               => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))-                               -> EventWriterT t w m a-                               -> Event t (EventWriterT t w m b)-                               -> EventWriterT t w m (a, Event t b)+runWithReplaceEventWriterTWith+  :: forall m t w a b+   . (Reflex t, MonadHold t m, Semigroup w)+  => (forall a' b'. m a' -> Event t (m b') -> EventWriterT t w m (a', Event t b'))+  -> EventWriterT t w m a+  -> Event t (EventWriterT t w m b)+  -> EventWriterT t w m (a, Event t b) runWithReplaceEventWriterTWith f a0 a' = do   (result0, result') <- f (runEventWriterT a0) $ fmapCheap runEventWriterT a'   tellEvent =<< switchHoldPromptOnly (snd result0) (fmapCheap snd result')@@ -177,7 +143,7 @@ -- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceIntMapWithAdjust'. sequenceIntMapWithAdjustEventWriterTWith   :: forall t m p w v v'-  .  ( Reflex t+   . ( Reflex t      , MonadHold t m      , Semigroup w      , Functor p@@ -186,10 +152,10 @@      , Patch (p w)      , PatchTarget (p w) ~ IntMap w      )-  => (   (IntMap.Key -> v -> m (Event t w, v'))-      -> IntMap v-      -> Event t (p v)-      -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))+  => ( (IntMap.Key -> v -> m (Event t w, v'))+       -> IntMap v+       -> Event t (p v)+       -> EventWriterT t w m (IntMap (Event t w, v'), Event t (p (Event t w, v')))      )   -> (Incremental t (p (Event t w)) -> Event t (PatchTarget (p w)))   -> (Event t (p (Event t w)) -> Event t (p w))@@ -217,7 +183,7 @@ -- | Like 'runWithReplaceEventWriterTWith', but for 'sequenceDMapWithAdjust'. sequenceDMapWithAdjustEventWriterTWith   :: forall t m p p' w k v v'-  .  ( Reflex t+   . ( Reflex t      , MonadHold t m      , Semigroup w      , Patch (p' (Some k) (Event t w))@@ -226,10 +192,10 @@      , Patch (p' (Some k) w)      , PatchTarget (p' (Some k) w) ~ Map (Some k) w      )-  => (   (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))-      -> DMap k v-      -> Event t (p k v)-      -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))+  => ( (forall a. k a -> v a -> m (Compose ((,) (Event t w)) v' a))+       -> DMap k v+       -> Event t (p k v)+       -> EventWriterT t w m (DMap k (Compose ((,) (Event t w)) v'), Event t (p k (Compose ((,) (Event t w)) v')))      )   -> ((forall a. Compose ((,) (Event t w)) v' a -> v' a) -> p k (Compose ((,) (Event t w)) v') -> p k v')   -> ((forall a. Compose ((,) (Event t w)) v' a -> Event t w) -> p k (Compose ((,) (Event t w)) v') -> p' (Some k) (Event t w))@@ -300,10 +266,11 @@   primitive = lift . primitive  -- | Map a function over the output of a 'EventWriterT'.-withEventWriterT :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)-                 => (w -> w')-                 -> EventWriterT t w m a-                 -> EventWriterT t w' m a+withEventWriterT+  :: (Semigroup w, Semigroup w', Reflex t, MonadHold t m)+  => (w -> w')+  -> EventWriterT t w m a+  -> EventWriterT t w' m a withEventWriterT f ew = do   (r, e) <- lift $ do     (r, e) <- runEventWriterT ew
src/Reflex/EventWriter/Class.hs view
@@ -1,9 +1,9 @@--- | This module defines the 'EventWriter' class. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines the 'EventWriter' class. module Reflex.EventWriter.Class   ( EventWriter (..)   ) where@@ -16,12 +16,10 @@  import Reflex.Class (Event) - -- | 'EventWriter' efficiently collects 'Event' values using 'tellEvent' -- and combines them via 'Semigroup' to provide an 'Event' result. class (Monad m, Semigroup w) => EventWriter t w m | m -> t w where   tellEvent :: Event t w -> m ()-  instance EventWriter t w m => EventWriter t w (ReaderT r m) where   tellEvent = lift . tellEvent
− src/Reflex/FastWeak.hs
@@ -1,210 +0,0 @@-{-# LANGUAGE CPP #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE ScopedTypeVariables #-}-#if GHCJS_FAST_WEAK-{-# LANGUAGE ForeignFunctionInterface #-}-{-# LANGUAGE JavaScriptFFI #-}-#endif---- |--- Module:---   Reflex.FastWeak--- Description:---   'FastWeak' is a weak pointer to some value, and 'FastWeakTicket' ensures the value---   referred to by a 'FastWeak' stays live while the ticket is held (live).------   On GHC or GHCJS when not built with the @fast-weak@ cabal flag, 'FastWeak' is a wrapper---   around the simple version of 'System.Mem.Weak.Weak' where the key and value are the same.------   On GHCJS when built with the @fast-weak@ cabal flag, 'FastWeak' is implemented directly---   in JS using @h$FastWeak@ and @h$FastWeakTicket@ which are a nonstandard part of the GHCJS RTS.-module Reflex.FastWeak-  ( FastWeakTicket-  , FastWeak-  , mkFastWeakTicket-  , getFastWeakTicketValue-  , getFastWeakTicketWeak-  , getFastWeakValue-  , getFastWeakTicket-  , emptyFastWeak-#ifdef GHCJS_FAST_WEAK-  --TODO: Move these elsewhere-  , unsafeFromRawJSVal-  , unsafeToRawJSVal-  , js_isNull-#endif-  ) where--import GHC.Exts (Any)-import Unsafe.Coerce--#ifdef GHCJS_FAST_WEAK-import GHCJS.Types-#else-import Control.Exception (evaluate)-import System.IO.Unsafe-import System.Mem.Weak-#endif---#ifdef GHCJS_FAST_WEAK--- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'--- can be used to get the referred to value without fear of @Nothing,--- and 'getFastWeakTicketWeak' can be used to get the weak version.------ Implemented by way of special support in the GHCJS RTS, @h$FastWeakTicket@.-newtype FastWeakTicket a = FastWeakTicket JSVal---- | A reference to some value which can be garbage collected if there are only--- weak references to the value left.------ 'getFastWeakValue' can be used to try and obtain a strong reference to the value.------ The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using--- 'getFastWeakTicket' if the value hasn't been collected yet.------ Implemented by way of special support in the GHCJS RTS, @h$FastWeak@.-newtype FastWeak a = FastWeak JSVal---- Just designed to mirror JSVal, so that we can unsafeCoerce between the two-data Val a = Val { unVal :: a }---- | Coerce a JSVal that represents the heap object of a value of type @a@ into a value of type @a@-unsafeFromRawJSVal :: JSVal -> a-unsafeFromRawJSVal v = unVal (unsafeCoerce v)---- | Coerce a heap object of type @a@ into a 'JSVal' which represents that object.-unsafeToRawJSVal :: a -> JSVal-unsafeToRawJSVal v = unsafeCoerce (Val v)-#else--- | A 'FastWeak' which has been promoted to a strong reference. 'getFastWeakTicketValue'--- can be used to get the referred to value without fear of @Nothing@,--- and 'getFastWeakTicketWeak' can be used to get the weak version.-data FastWeakTicket a = FastWeakTicket-  { _fastWeakTicket_val :: !a-  , _fastWeakTicket_weak :: {-# UNPACK #-} !(Weak a)-  }---- | A reference to some value which can be garbage collected if there are only weak references to the value left.------ 'getFastWeakValue' can be used to try and obtain a strong reference to the value.------ The value in a @FastWeak@ can also be kept alive by obtaining a 'FastWeakTicket' using 'getFastWeakTicket'--- if the value hasn't been collected yet.------ Synonymous with 'Weak'.-type FastWeak a = Weak a-#endif---- | Return the @a@ kept alive by the given 'FastWeakTicket'.------ This needs to be in IO so we know that we've relinquished the ticket.-getFastWeakTicketValue :: FastWeakTicket a -> IO a-#ifdef GHCJS_FAST_WEAK-getFastWeakTicketValue t = do-  v <- js_ticketVal t-  return $ unsafeFromRawJSVal v--foreign import javascript unsafe "$r = $1.val;" js_ticketVal :: FastWeakTicket a -> IO JSVal-#else-getFastWeakTicketValue = return . _fastWeakTicket_val-#endif---- | Get the value referred to by a 'FastWeak' if it hasn't yet been collected,--- or @Nothing@ if it has been collected.-getFastWeakValue :: FastWeak a -> IO (Maybe a)-#ifdef GHCJS_FAST_WEAK-getFastWeakValue w = do-  r <- js_weakVal w-  case js_isNull r of-    True -> return Nothing-    False -> return $ Just $ unsafeFromRawJSVal r--foreign import javascript unsafe "$1 === null" js_isNull :: JSVal -> Bool--foreign import javascript unsafe "$r = ($1.ticket === null) ? null : $1.ticket.val;" js_weakVal :: FastWeak a -> IO JSVal-#else-getFastWeakValue = deRefWeak-#endif---- | Try to create a 'FastWeakTicket' for the given 'FastWeak' which will ensure the value referred--- remains alive. Returns @Just@ if the value hasn't been collected--- and a ticket can therefore be obtained, @Nothing@ if it's been collected.-getFastWeakTicket :: forall a. FastWeak a -> IO (Maybe (FastWeakTicket a))-#ifdef GHCJS_FAST_WEAK-getFastWeakTicket w = do-  r <- js_weakTicket w-  case js_isNull r of-    True -> return Nothing-    False -> return $ Just $ FastWeakTicket r--foreign import javascript unsafe "$r = $1.ticket;" js_weakTicket :: FastWeak a -> IO JSVal-#else-getFastWeakTicket w = do-  deRefWeak w >>= \case-    Nothing -> return Nothing-    Just v -> return $ Just $ FastWeakTicket-      { _fastWeakTicket_val = v-      , _fastWeakTicket_weak = w-      }-#endif---- | Create a 'FastWeakTicket' directly from a value, creating a 'FastWeak' in the process--- which can be obtained with 'getFastWeakTicketValue'.------ This function is marked NOINLINE so it is opaque to GHC.--- If we do not do this, then GHC will sometimes fuse the constructor away--- so any weak references that are attached to the ticket will have their--- finalizer run. Using the opaque constructor, GHC does not see the--- constructor application, so it behaves like an IORef and cannot be fused away.------ The result is also evaluated to WHNF, since forcing a thunk invalidates--- the weak pointer to it in some cases.-{-# NOINLINE mkFastWeakTicket #-}-mkFastWeakTicket :: a -> IO (FastWeakTicket a)--- I think it's fine if this is lazy - it'll retain the 'a', but so would the output; we just need to make sure it's forced before we start relying on the--- associated FastWeak to actually be weak-#ifdef GHCJS_FAST_WEAK-mkFastWeakTicket v = js_fastWeakTicket (unsafeToRawJSVal v)--foreign import javascript unsafe "$r = new h$FastWeakTicket($1);" js_fastWeakTicket :: JSVal -> IO (FastWeakTicket a)-#else-mkFastWeakTicket v = do-  v' <- evaluate v-  w <- mkWeakPtr v' Nothing-  return $ FastWeakTicket-    { _fastWeakTicket_val = v'-    , _fastWeakTicket_weak = w-    }-#endif---- | Demote a 'FastWeakTicket'; which ensures the value is alive, to a 'FastWeak' which doesn't.--- Note that unless the ticket for the same 'FastWeak' is held in some other way--- the value might be collected immediately.-getFastWeakTicketWeak :: FastWeakTicket a -> IO (FastWeak a)--- Needs IO so that it can force the value - otherwise, could end up with a reference to the Ticket, which would retain the value-#ifdef GHCJS_FAST_WEAK-foreign import javascript unsafe "$r = $1.weak;" getFastWeakTicketWeak' :: FastWeakTicket a -> IO (FastWeak a)-{-# INLINE getFastWeakTicketWeak #-}-getFastWeakTicketWeak = getFastWeakTicketWeak'-#else-getFastWeakTicketWeak = return . _fastWeakTicket_weak-#endif---- | A weak reference that is always empty-emptyFastWeak :: FastWeak a-emptyFastWeak = unsafeCoerce w-  where w :: FastWeak Any-#ifdef GHCJS_FAST_WEAK-        w = js_emptyWeak-#else-        w = unsafePerformIO $ do-          w' <- mkWeakPtr undefined Nothing-          finalize w'-          return w'-#endif-{-# NOINLINE emptyFastWeak #-}--#ifdef GHCJS_FAST_WEAK-foreign import javascript unsafe "$r = new h$FastWeak(null);" js_emptyWeak :: FastWeak Any-#endif
src/Reflex/FunctorMaybe.hs view
@@ -19,11 +19,12 @@ #endif import Witherable ---TODO: See if there's a better class in the standard libraries already+-- TODO: See if there's a better class in the standard libraries already  -- | A class for values that combines filtering and mapping using 'Maybe'. -- Morally, @'FunctorMaybe' ~ KleisliFunctor 'Maybe'@. {-# DEPRECATED FunctorMaybe "Use 'Filterable' from Data.Witherable instead" #-}+ class FunctorMaybe f where   -- | Combined mapping and filtering function.   fmapMaybe :: (a -> Maybe b) -> f a -> f b
src/Reflex/Host/Class.hs view
@@ -26,16 +26,14 @@   , fireEventRefAndRead   ) where -import Reflex.Class- import Control.Monad.Fix import Control.Monad.Identity import Control.Monad.Ref import Control.Monad.Trans import Control.Monad.Trans.Cont (ContT) import Control.Monad.Trans.Except (ExceptT)-import Control.Monad.Trans.Reader (ReaderT) import Control.Monad.Trans.RWS (RWST)+import Control.Monad.Trans.Reader (ReaderT) import Control.Monad.Trans.State (StateT) import qualified Control.Monad.Trans.State.Strict as Strict import Control.Monad.Trans.Writer (WriterT)@@ -43,15 +41,20 @@ import Data.GADT.Compare import Data.Kind (Type) +import Reflex.Class+ -- | Framework implementation support class for the reflex implementation -- represented by @t@.-class ( Reflex t-      , MonadReflexCreateTrigger t (HostFrame t)-      , MonadSample t (HostFrame t)-      , MonadHold t (HostFrame t)-      , MonadFix (HostFrame t)-      , MonadSubscribeEvent t (HostFrame t)-      ) => ReflexHost t where+class+  ( Reflex t+  , MonadReflexCreateTrigger t (HostFrame t)+  , MonadSample t (HostFrame t)+  , MonadHold t (HostFrame t)+  , MonadFix (HostFrame t)+  , MonadSubscribeEvent t (HostFrame t)+  ) =>+  ReflexHost t+  where   type EventTrigger t :: Type -> Type   type EventHandle t :: Type -> Type   type HostFrame t :: Type -> Type@@ -102,19 +105,26 @@   -- event, by passing it to 'fireEventsAndRead'.   --   -- Note: An event may be set up multiple times. So after the teardown action-  -- is executed, the event may still be set up again in the future.+  -- is executed, the event may still be set up again in the future. Also, the+  -- setup and teardown actions must not run a frame.   newEventWithTrigger :: (EventTrigger t a -> IO (IO ())) -> m (Event t a)+   newFanEventWithTrigger :: GCompare k => (forall a. k a -> EventTrigger t a -> IO (IO ())) -> m (EventSelector t k)  -- | 'MonadReflexHost' designates monads that can run reflex frames.-class ( ReflexHost t-      , MonadReflexCreateTrigger t m-      , MonadSubscribeEvent t m-      , MonadReadEvent t (ReadPhase m)-      , MonadSample t (ReadPhase m)-      , MonadHold t (ReadPhase m)-      ) => MonadReflexHost t m | m -> t where+class+  ( ReflexHost t+  , MonadReflexCreateTrigger t m+  , MonadSubscribeEvent t m+  , MonadReadEvent t (ReadPhase m)+  , MonadSample t (ReadPhase m)+  , MonadHold t (ReadPhase m)+  ) =>+  MonadReflexHost t m+    | m -> t+  where   type ReadPhase m :: Type -> Type+   -- | Propagate some events firings and read the values of events afterwards.   --   -- This function will create a new frame to fire the given events. It will@@ -122,7 +132,10 @@   -- given callback is executed which allows to read the final values of events   -- and check whether they have fired in this frame or not.   ---  -- All events that are given are fired at the same time.+  -- All events that are given are fired at the same time. If a trigger is listed+  -- twice, the behavior is undefined for efficiency reasons. For safety or+  -- debugging purposes, the @debug-frame@ Cabal flag can be used: it causes an+  -- exception to be thrown when the any-trigger-once-per-frame rule is violated.   --   -- This function is typically used in the main loop of a reflex framework   -- implementation.  The main loop waits for external events to happen (such as@@ -186,7 +199,6 @@         Nothing -> return Nothing         Just getValue -> fmap Just getValue - -------------------------------------------------------------------------------- -- Instances --------------------------------------------------------------------------------@@ -227,7 +239,6 @@   fireEventsAndRead dm a = lift $ fireEventsAndRead dm a   runHostFrame = lift . runHostFrame - instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (Strict.StateT s m) where   newEventWithTrigger = lift . newEventWithTrigger   newFanEventWithTrigger initializer = lift $ newFanEventWithTrigger initializer@@ -239,8 +250,6 @@   type ReadPhase (Strict.StateT s m) = ReadPhase m   fireEventsAndRead dm a = lift $ fireEventsAndRead dm a   runHostFrame = lift . runHostFrame--  instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (ContT r m) where   newEventWithTrigger = lift . newEventWithTrigger
src/Reflex/Host/Headless.hs view
@@ -14,8 +14,8 @@ import Control.Monad.Primitive (PrimMonad) import Control.Monad.Ref (MonadRef, Ref, readRef) import Data.Dependent.Sum (DSum (..), (==>))-import Data.Foldable (for_, asum)-import Data.Functor.Identity (Identity(..))+import Data.Foldable (asum, for_)+import Data.Functor.Identity (Identity (..)) import Data.IORef (IORef, readIORef) import Data.Maybe (catMaybes) import Data.Traversable (for)@@ -56,7 +56,7 @@ -- testing. Each headless network runs on its own spider timeline. runHeadlessApp   :: forall a-  .  (forall t m. MonadHeadlessApp t m => m (Event t a))+   . (forall t m. MonadHeadlessApp t m => m (Event t a))   -- ^ The action to be run in the headless FRP network. The FRP network is   -- closed at the first occurrence of the resulting 'Event'.   -> IO a@@ -73,21 +73,17 @@     -- Run the "guest" application, providing the appropriate context. We'll     -- pure the result of the action, and a 'FireCommand' that will be used to     -- trigger events.-    (result, fc@(FireCommand fire)) <- do-      hostPerformEventT $                 -- Allows the guest app to run-                                          -- 'performEvent', so that actions-                                          -- (e.g., IO actions) can be run when-                                          -- 'Event's fire.--        flip runPostBuildT postBuild $    -- Allows the guest app to access to-                                          -- a "post-build" 'Event'--          flip runTriggerEventT events $  -- Allows the guest app to create new-                                          -- events and triggers and write-                                          -- those triggers to a channel from-                                          -- which they will be read and-                                          -- processed.-            guest+    (result, fc@(FireCommand fire)) <-+      -- Allows the guest app to run 'performEvent', so that actions (e.g., IO+      -- actions) can be run when 'Event's fire.+      hostPerformEventT+        -- Allows the guest app to access to a "post-build" 'Event'+        . flip runPostBuildT postBuild+        -- Allows the guest app to create new events and triggers and write+        -- those triggers to a channel from which they will be read and+        -- processed.+        . flip runTriggerEventT events+        $ guest      -- Read the trigger reference for the post-build event. This will be     -- 'Nothing' if the guest application hasn't subscribed to this event.@@ -126,15 +122,13 @@             -- Ideally, we should cut off the event loop as soon as this fires,             -- but Performable doesn't currently give us an easy way to do that.             shutdownNow = asum shutdownEventFirings-        case shutdownNow of-          Just exitResult -> pure exitResult-          Nothing -> loop+        maybe loop pure shutdownNow   where     -- Use the given 'FireCommand' to fire events that have subscribers     -- and call the callback for the 'TriggerInvocation' of each.     fireEventTriggerRefs       :: forall b m t-      .  MonadIO m+       . MonadIO m       => FireCommand t m       -> [DSum (EventTriggerRef t) TriggerInvocation]       -> ReadPhase m b
src/Reflex/Network.hs view
@@ -12,8 +12,8 @@   , untilReady   ) where -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.NotReady.Class import Reflex.PostBuild.Class 
src/Reflex/NotReady/Class.hs view
@@ -8,7 +8,7 @@ {-# LANGUAGE UndecidableInstances #-}  module Reflex.NotReady.Class-  ( NotReady(..)+  ( NotReady (..)   ) where  import Control.Monad.Reader (ReaderT)
src/Reflex/PerformEvent/Base.hs view
@@ -1,5 +1,3 @@--- | This module provides 'PerformEventT', the standard implementation of--- 'PerformEvent'. {-# LANGUAGE CPP #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-}@@ -16,19 +14,14 @@ {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module provides 'PerformEventT', the standard implementation of+-- 'PerformEvent'. module Reflex.PerformEvent.Base   ( PerformEventT (..)   , FireCommand (..)   , hostPerformEventT   ) where -import Reflex.Adjustable.Class-import Reflex.Class-import Reflex.Host.Class-import Reflex.PerformEvent.Class-import Reflex.Requester.Base-import Reflex.Requester.Class- import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix@@ -44,6 +37,13 @@ import qualified Data.IntMap.Strict as IntMap import qualified Data.Semigroup as S +import Reflex.Adjustable.Class+import Reflex.Class+import Reflex.Host.Class+import Reflex.PerformEvent.Class+import Reflex.Requester.Base+import Reflex.Requester.Class+ #if !MIN_VERSION_base(4,18,0) import Control.Monad.Identity #endif@@ -52,11 +52,13 @@ -- any followup actions provided via 'PerformEvent'.  The given 'ReadPhase' -- action will be run once for the initial trigger execution as well as once for -- each followup.-newtype FireCommand t m = FireCommand { runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a] } --TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?+-- As for 'Reflex.Host.Class.fireEventsAndRead', the list must not contain one+-- trigger twice.+newtype FireCommand t m = FireCommand {runFireCommand :: forall a. [DSum (EventTrigger t) Identity] -> ReadPhase m a -> m [a]} -- TODO: The handling of this ReadPhase seems wrong, or at least inelegant; how do we actually make the decision about what order frames run in?  -- | Provides a basic implementation of 'PerformEvent'.  Note that, despite the -- name, 'PerformEventT' is not an instance of 'MonadTrans'.-newtype PerformEventT t m a = PerformEventT { unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a }+newtype PerformEventT t m a = PerformEventT {unPerformEventT :: RequesterT t (HostFrame t) Identity (HostFrame t) a}  deriving instance ReflexHost t => Functor (PerformEventT t m) deriving instance ReflexHost t => Applicative (PerformEventT t m)@@ -76,23 +78,26 @@  instance (Monad (HostFrame t), ReflexHost t, Ref m ~ Ref IO) => PerformEvent t (PerformEventT t m) where   type Performable (PerformEventT t m) = HostFrame t-  {-# INLINABLE performEvent_ #-}+  {-# INLINEABLE performEvent_ #-}   performEvent_ = PerformEventT . requesting_-  {-# INLINABLE performEvent #-}+  {-# INLINEABLE performEvent #-}   performEvent = PerformEventT . requestingIdentity  instance ReflexHost t => Adjustable t (PerformEventT t m) where   runWithReplace outerA0 outerA' = PerformEventT $ runWithReplaceRequesterTWith f (coerce outerA0) (coerceEvent outerA')-    where f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)-          f a0 a' = do-            result0 <- lift a0-            result' <- requestingIdentity a'-            return (result0, result')+    where+      f :: HostFrame t a -> Event t (HostFrame t b) -> RequesterT t (HostFrame t) Identity (HostFrame t) (a, Event t b)+      f a0 a' = do+        result0 <- lift a0+        result' <- requestingIdentity a'+        return (result0, result')   traverseIntMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseIntMapWithKeyWithAdjustRequesterTWith (defaultAdjustIntBase traverseIntMapPatchWithKey) patchIntMapNewElementsMap mergeIntIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')   traverseDMapWithKeyWithAdjust f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithKey) mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm')   traverseDMapWithKeyWithAdjustWithMove f outerDm0 outerDm' = PerformEventT $ traverseDMapWithKeyWithAdjustRequesterTWith (defaultAdjustBase traversePatchDMapWithMoveWithKey) mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove (\k v -> unPerformEventT $ f k v) (coerce outerDm0) (coerceEvent outerDm') -defaultAdjustBase :: forall t v v2 k' p. (Monad (HostFrame t), Reflex t)+defaultAdjustBase+  :: forall t v v2 k' p+   . (Monad (HostFrame t), Reflex t)   => ((forall a. k' a -> v a -> HostFrame t (v2 a)) -> p k' v -> HostFrame t (p k' v2))   -> (forall a. k' a -> v a -> HostFrame t (v2 a))   -> DMap k' v@@ -103,7 +108,9 @@   result' <- requestingIdentity $ ffor dm' $ traversePatchWithKey f'   return (result0, result') -defaultAdjustIntBase :: forall t v v2 p. (Monad (HostFrame t), Reflex t)+defaultAdjustIntBase+  :: forall t v v2 p+   . (Monad (HostFrame t), Reflex t)   => ((IntMap.Key -> v -> HostFrame t v2) -> p v -> HostFrame t (p v2))   -> (IntMap.Key -> v -> HostFrame t v2)   -> IntMap v@@ -115,22 +122,23 @@   return (result0, result')  instance ReflexHost t => MonadReflexCreateTrigger t (PerformEventT t m) where-  {-# INLINABLE newEventWithTrigger #-}+  {-# INLINEABLE newEventWithTrigger #-}   newEventWithTrigger = PerformEventT . lift . newEventWithTrigger-  {-# INLINABLE newFanEventWithTrigger #-}+  {-# INLINEABLE newFanEventWithTrigger #-}   newFanEventWithTrigger f = PerformEventT $ lift $ newFanEventWithTrigger f  -- | Run a 'PerformEventT' action, returning a 'FireCommand' that allows the -- caller to trigger 'Event's while ensuring that 'performEvent' actions are run -- at the appropriate time.-{-# INLINABLE hostPerformEventT #-}-hostPerformEventT :: forall t m a.-                     ( MonadReflexHost t m-                     , MonadRef m-                     , Ref m ~ Ref IO-                     )-                  => PerformEventT t m a-                  -> m (a, FireCommand t m)+{-# INLINEABLE hostPerformEventT #-}+hostPerformEventT+  :: forall t m a+   . ( MonadReflexHost t m+     , MonadRef m+     , Ref m ~ Ref IO+     )+  => PerformEventT t m a+  -> m (a, FireCommand t m) hostPerformEventT a = do   (response, responseTrigger) <- newEventWithTriggerRef   (result, eventToPerform) <- runHostFrame $ runRequesterT (unPerformEventT a) response@@ -150,36 +158,36 @@               let followupEventTriggers = case mrt of                     Just rt -> [rt :=> Identity responses]                     Nothing -> []-              (result':) <$> go followupEventTriggers+              (result' :) <$> go followupEventTriggers     go triggers  instance ReflexHost t => MonadSample t (PerformEventT t m) where-  {-# INLINABLE sample #-}+  {-# INLINEABLE sample #-}   sample = PerformEventT . lift . sample  instance (ReflexHost t, MonadHold t m) => MonadHold t (PerformEventT t m) where-  {-# INLINABLE hold #-}+  {-# INLINEABLE hold #-}   hold v0 v' = PerformEventT $ lift $ hold v0 v'-  {-# INLINABLE holdDyn #-}+  {-# INLINEABLE holdDyn #-}   holdDyn v0 v' = PerformEventT $ lift $ holdDyn v0 v'-  {-# INLINABLE holdIncremental #-}+  {-# INLINEABLE holdIncremental #-}   holdIncremental v0 v' = PerformEventT $ lift $ holdIncremental v0 v'-  {-# INLINABLE buildDynamic #-}+  {-# INLINEABLE buildDynamic #-}   buildDynamic getV0 v' = PerformEventT $ lift $ buildDynamic getV0 v'-  {-# INLINABLE headE #-}+  {-# INLINEABLE headE #-}   headE = PerformEventT . lift . headE-  {-# INLINABLE now #-}+  {-# INLINEABLE now #-}   now = PerformEventT . lift $ now  instance (MonadRef (HostFrame t), ReflexHost t) => MonadRef (PerformEventT t m) where   type Ref (PerformEventT t m) = Ref (HostFrame t)-  {-# INLINABLE newRef #-}+  {-# INLINEABLE newRef #-}   newRef = PerformEventT . lift . newRef-  {-# INLINABLE readRef #-}+  {-# INLINEABLE readRef #-}   readRef = PerformEventT . lift . readRef-  {-# INLINABLE writeRef #-}+  {-# INLINEABLE writeRef #-}   writeRef r = PerformEventT . lift . writeRef r  instance (MonadAtomicRef (HostFrame t), ReflexHost t) => MonadAtomicRef (PerformEventT t m) where-  {-# INLINABLE atomicModifyRef #-}+  {-# INLINEABLE atomicModifyRef #-}   atomicModifyRef r = PerformEventT . lift . atomicModifyRef r
src/Reflex/PerformEvent/Class.hs view
@@ -1,6 +1,3 @@--- | This module defines 'PerformEvent', which mediates the--- interaction between a "Reflex"-based program and the external side-effecting--- actions such as 'IO'. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-}@@ -10,6 +7,9 @@ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines 'PerformEvent', which mediates the+-- interaction between a "Reflex"-based program and the external side-effecting+-- actions such as 'IO'. module Reflex.PerformEvent.Class   ( PerformEvent (..)   , performEventAsync@@ -33,11 +33,13 @@   -- | The type of action to be triggered; this is often not the same type as   -- the triggering action.   type Performable m :: Type -> Type+   -- | Perform the action contained in the given 'Event' whenever the 'Event'   -- fires.  Return the result in another 'Event'.  Note that the output 'Event'   -- will generally occur later than the input 'Event', since most 'Performable'   -- actions cannot be performed during 'Event' propagation.   performEvent :: Event t (Performable m a) -> m (Event t a)+   -- | Like 'performEvent', but do not return the result.  May have slightly   -- better performance.   performEvent_ :: Event t (Performable m ()) -> m ()@@ -50,7 +52,7 @@ -- the callback whenever it is ready.  This will work properly, even in GHCJS -- (which fully implements concurrency even though JavaScript does not have -- built in concurrency).-{-# INLINABLE performEventAsync #-}+{-# INLINEABLE performEventAsync #-} performEventAsync :: (TriggerEvent t m, PerformEvent t m) => Event t ((a -> IO ()) -> Performable m ()) -> m (Event t a) performEventAsync e = do   (eOut, triggerEOut) <- newTriggerEvent
src/Reflex/PostBuild/Base.hs view
@@ -1,5 +1,3 @@--- | This module defines 'PostBuildT', the standard implementation of--- 'PostBuild'. {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-}@@ -8,18 +6,22 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines 'PostBuildT', the standard implementation of+-- 'PostBuild'. module Reflex.PostBuild.Base   ( PostBuildT (..)   , runPostBuildT-  -- * Internal++    -- * Internal   , mapIntMapWithAdjustImpl   , mapDMapWithAdjustImpl   ) where -import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.Primitive@@ -38,33 +40,33 @@ import Control.Monad.Identity #endif -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.Host.Class import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.TriggerEvent.Class  -- | Provides a basic implementation of 'PostBuild'.-newtype PostBuildT t m a = PostBuildT { unPostBuildT :: ReaderT (Event t ()) m a }+newtype PostBuildT t m a = PostBuildT {unPostBuildT :: ReaderT (Event t ()) m a}   deriving-    ( Functor-    , Applicative+    ( Applicative+    , Functor     , Monad+    , MonadAsyncException+    , MonadCatch+    , MonadException     , MonadFix     , MonadIO-    , MonadTrans-    , MonadException-    , MonadAsyncException     , MonadMask     , MonadThrow-    , MonadCatch+    , MonadTrans     )  -- | Run a 'PostBuildT' action.  An 'Event' should be provided that fires -- immediately after the action is finished running; no other 'Event's should -- fire first.-{-# INLINABLE runPostBuildT #-}+{-# INLINEABLE runPostBuildT #-} runPostBuildT :: PostBuildT t m a -> Event t () -> m a runPostBuildT (PostBuildT a) = runReaderT a @@ -80,58 +82,58 @@   primitive = lift . primitive  instance (Reflex t, Monad m) => PostBuild t (PostBuildT t m) where-  {-# INLINABLE getPostBuild #-}+  {-# INLINEABLE getPostBuild #-}   getPostBuild = PostBuildT ask  instance MonadSample t m => MonadSample t (PostBuildT t m) where-  {-# INLINABLE sample #-}+  {-# INLINEABLE sample #-}   sample = lift . sample  instance MonadHold t m => MonadHold t (PostBuildT t m) where-  {-# INLINABLE hold #-}+  {-# INLINEABLE hold #-}   hold v0 = lift . hold v0-  {-# INLINABLE holdDyn #-}+  {-# INLINEABLE holdDyn #-}   holdDyn v0 = lift . holdDyn v0-  {-# INLINABLE holdIncremental #-}+  {-# INLINEABLE holdIncremental #-}   holdIncremental v0 = lift . holdIncremental v0-  {-# INLINABLE buildDynamic #-}+  {-# INLINEABLE buildDynamic #-}   buildDynamic a0 = lift . buildDynamic a0-  {-# INLINABLE headE #-}+  {-# INLINEABLE headE #-}   headE = lift . headE-  {-# INLINABLE now #-}+  {-# INLINEABLE now #-}   now = lift now  instance PerformEvent t m => PerformEvent t (PostBuildT t m) where   type Performable (PostBuildT t m) = Performable m-  {-# INLINABLE performEvent_ #-}+  {-# INLINEABLE performEvent_ #-}   performEvent_ = lift . performEvent_-  {-# INLINABLE performEvent #-}+  {-# INLINEABLE performEvent #-}   performEvent = lift . performEvent  instance (ReflexHost t, MonadReflexCreateTrigger t m) => MonadReflexCreateTrigger t (PostBuildT t m) where-  {-# INLINABLE newEventWithTrigger #-}+  {-# INLINEABLE newEventWithTrigger #-}   newEventWithTrigger = PostBuildT . lift . newEventWithTrigger-  {-# INLINABLE newFanEventWithTrigger #-}+  {-# INLINEABLE newFanEventWithTrigger #-}   newFanEventWithTrigger f = PostBuildT $ lift $ newFanEventWithTrigger f  instance TriggerEvent t m => TriggerEvent t (PostBuildT t m) where-  {-# INLINABLE newTriggerEvent #-}+  {-# INLINEABLE newTriggerEvent #-}   newTriggerEvent = lift newTriggerEvent-  {-# INLINABLE newTriggerEventWithOnComplete #-}+  {-# INLINEABLE newTriggerEventWithOnComplete #-}   newTriggerEventWithOnComplete = lift newTriggerEventWithOnComplete   newEventWithLazyTriggerWithOnComplete = lift . newEventWithLazyTriggerWithOnComplete  instance MonadRef m => MonadRef (PostBuildT t m) where   type Ref (PostBuildT t m) = Ref m-  {-# INLINABLE newRef #-}+  {-# INLINEABLE newRef #-}   newRef = lift . newRef-  {-# INLINABLE readRef #-}+  {-# INLINEABLE readRef #-}   readRef = lift . readRef-  {-# INLINABLE writeRef #-}+  {-# INLINEABLE writeRef #-}   writeRef r = lift . writeRef r  instance MonadAtomicRef m => MonadAtomicRef (PostBuildT t m) where-  {-# INLINABLE atomicModifyRef #-}+  {-# INLINEABLE atomicModifyRef #-}   atomicModifyRef r = lift . atomicModifyRef r  instance (Reflex t, MonadHold t m, MonadFix m, Adjustable t m, PerformEvent t m) => Adjustable t (PostBuildT t m) where@@ -139,20 +141,22 @@     postBuild <- getPostBuild     lift $ do       rec result@(_, result') <- runWithReplace (runPostBuildT a0 postBuild) $ fmap (\v -> runPostBuildT v =<< headE voidResult') a'-          let voidResult' = fmapCheap (\_ -> ()) result'+          let voidResult' = fmapCheap (const ()) result'       return result-  {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}+  {-# INLINEABLE traverseIntMapWithKeyWithAdjust #-}   traverseIntMapWithKeyWithAdjust = mapIntMapWithAdjustImpl traverseIntMapWithKeyWithAdjust-  {-# INLINABLE traverseDMapWithKeyWithAdjust #-}+  {-# INLINEABLE traverseDMapWithKeyWithAdjust #-}   traverseDMapWithKeyWithAdjust = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjust mapPatchDMap   traverseDMapWithKeyWithAdjustWithMove = mapDMapWithAdjustImpl traverseDMapWithKeyWithAdjustWithMove mapPatchDMapWithMove -{-# INLINABLE mapIntMapWithAdjustImpl #-}-mapIntMapWithAdjustImpl :: forall t m v v' p. (Reflex t, MonadFix m, MonadHold t m, Functor p)-  => (   (IntMap.Key -> (Event t (), v) -> m v')-      -> IntMap (Event t (), v)-      -> Event t (p (Event t (), v))-      -> m (IntMap v', Event t (p v'))+{-# INLINEABLE mapIntMapWithAdjustImpl #-}+mapIntMapWithAdjustImpl+  :: forall t m v v' p+   . (Reflex t, MonadFix m, MonadHold t m, Functor p)+  => ( (IntMap.Key -> (Event t (), v) -> m v')+       -> IntMap (Event t (), v)+       -> Event t (p (Event t (), v))+       -> m (IntMap v', Event t (p v'))      )   -> (IntMap.Key -> v -> PostBuildT t m v')   -> IntMap v@@ -160,7 +164,7 @@   -> PostBuildT t m (IntMap v', Event t (p v')) mapIntMapWithAdjustImpl base f dm0 dm' = do   postBuild <- getPostBuild-  let loweredDm0 = fmap ((,) postBuild) dm0+  let loweredDm0 = fmap (postBuild,) dm0       f' :: IntMap.Key -> (Event t (), v) -> m v'       f' k (e, v) = do         runPostBuildT (f k v) e@@ -170,15 +174,17 @@         numberedDm' <- numberOccurrencesFrom 1 dm'         let postBuild' = fanInt $ fmapCheap (`IntMap.singleton` ()) cohortDone             loweredDm' = flip pushAlways numberedDm' $ \(n, p) -> do-              return $ fmap ((,) (selectInt postBuild' n)) p+              return $ fmap (selectInt postBuild' n,) p     return (result0, result') -{-# INLINABLE mapDMapWithAdjustImpl #-}-mapDMapWithAdjustImpl :: forall t m k v v' p. (Reflex t, MonadFix m, MonadHold t m)-  => (   (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))-      -> DMap k (Compose ((,) (Bool, Event t ())) v)-      -> Event t (p k (Compose ((,) (Bool, Event t ())) v))-      -> m (DMap k v', Event t (p k v'))+{-# INLINEABLE mapDMapWithAdjustImpl #-}+mapDMapWithAdjustImpl+  :: forall t m k v v' p+   . (Reflex t, MonadFix m, MonadHold t m)+  => ( (forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a))+       -> DMap k (Compose ((,) (Bool, Event t ())) v)+       -> Event t (p k (Compose ((,) (Bool, Event t ())) v))+       -> m (DMap k v', Event t (p k v'))      )   -> ((forall a. v a -> Compose ((,) (Bool, Event t ())) v a) -> p k v -> p k (Compose ((,) (Bool, Event t ())) v))   -> (forall a. k a -> v a -> PostBuildT t m (v' a))@@ -190,13 +196,14 @@   let loweredDm0 = DMap.map (Compose . (,) (False, postBuild)) dm0       f' :: forall a. k a -> Compose ((,) (Bool, Event t ())) v a -> m (v' a)       f' k (Compose ((shouldHeadE, e), v)) = do-        eOnce <- if shouldHeadE-          then headE e --TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence-          else return e+        eOnce <-+          if shouldHeadE+            then headE e -- TODO: Avoid doing this headE so many times; once per loweredDm' firing ought to be OK, but it's not totally trivial to do because result' might be firing at the same time, and we don't want *that* to be the postBuild occurrence+            else return e         runPostBuildT (f k v) eOnce   lift $ do     rec (result0, result') <- base f' loweredDm0 loweredDm'-        let voidResult' = fmapCheap (\_ -> ()) result'+        let voidResult' = fmapCheap (const ()) result'         let loweredDm' = ffor dm' $ mapPatch (Compose . (,) (True, voidResult'))     return (result0, result') @@ -207,7 +214,7 @@ -- | Deprecated instance TransControl.MonadTransControl (PostBuildT t) where   type StT (PostBuildT t) a = TransControl.StT (ReaderT (Event t ())) a-  {-# INLINABLE liftWith #-}+  {-# INLINEABLE liftWith #-}   liftWith = TransControl.defaultLiftWith PostBuildT unPostBuildT-  {-# INLINABLE restoreT #-}+  {-# INLINEABLE restoreT #-}   restoreT = TransControl.defaultRestoreT PostBuildT
src/Reflex/PostBuild/Class.hs view
@@ -1,5 +1,3 @@--- | This module defines 'PostBuild', which indicates that an action will be--- notified when it, and any action it's a part of, has finished executing. {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-}@@ -8,15 +6,17 @@ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines 'PostBuild', which indicates that an action will be+-- notified when it, and any action it's a part of, has finished executing. module Reflex.PostBuild.Class   ( PostBuild (..)   ) where -import Reflex.Class- import Control.Monad.Reader import Control.Monad.State import qualified Control.Monad.State.Strict as Strict++import Reflex.Class  -- | 'PostBuild' represents an action that is notified via an 'Event' when it -- has finished executing.  Note that the specific definition of "finished" is
src/Reflex/Profiled.hs view
@@ -5,13 +5,13 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE PolyKinds #-}-{-# LANGUAGE TypeApplications #-}-{-# LANGUAGE RankNTypes #-}  -- | -- Module:@@ -32,10 +32,9 @@ import Data.Coerce import Data.Dependent.Map (DMap) import Data.GADT.Compare (GCompare)-import Data.FastMutableIntMap import Data.IORef-import Data.List import Data.Kind (Type)+import Data.List import Data.Map (Map) import qualified Data.Map.Strict as Map import Data.Ord@@ -48,6 +47,8 @@ import GHC.Stack import System.IO.Unsafe +import Data.FastMutableIntMap+ #if !MIN_VERSION_base(4,18,0) import Data.Monoid ((<>)) #endif@@ -76,11 +77,11 @@   , _costCentreTree_cumulativeEntries :: !Int   , _costCentreTree_children :: !(Map (Ptr CostCentre) CostCentreTree)   }-  deriving (Show, Eq, Ord)+  deriving (Eq, Ord, Show)  instance S.Semigroup CostCentreTree where   (CostCentreTree oa ea ca) <> (CostCentreTree ob eb cb) =-      CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb+    CostCentreTree (oa + ob) (ea + eb) $ Map.unionWith (S.<>) ca cb  instance Monoid CostCentreTree where   mempty = CostCentreTree 0 0 mempty@@ -88,9 +89,11 @@  getCostCentreStack :: Ptr CostCentreStack -> IO [Ptr CostCentre] getCostCentreStack = go []-  where go l ccs = if ccs == nullPtr-          then return l-          else do+  where+    go l ccs =+      if ccs == nullPtr+        then return l+        else do           cc <- ccsCC ccs           parent <- ccsParent ccs           go (cc : l) parent@@ -107,17 +110,18 @@  formatCostCentreTree :: CostCentreTree -> IO String formatCostCentreTree cct0 = unlines . reverse <$> execStateT (go 0 cct0) []-  where go :: Int -> CostCentreTree -> StateT [String] IO ()-        go depth cct = do-          let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct-              indent = mconcat $ replicate depth "  "-          forM_ children $ \(cc, childCct) -> do-            lbl <- liftIO $ peekCString utf8 =<< ccLabel cc-            mdl <- liftIO $ peekCString utf8 =<< ccModule cc-            loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc-            let description = mdl <> "." <> lbl <> " (" <> loc <> ")"-            modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)-            go (succ depth) childCct+  where+    go :: Int -> CostCentreTree -> StateT [String] IO ()+    go depth cct = do+      let children = sortOn (Down . _costCentreTree_cumulativeEntries . snd) $ Map.toList $ _costCentreTree_children cct+          indent = mconcat $ replicate depth "  "+      forM_ children $ \(cc, childCct) -> do+        lbl <- liftIO $ peekCString utf8 =<< ccLabel cc+        mdl <- liftIO $ peekCString utf8 =<< ccModule cc+        loc <- liftIO $ peekCString utf8 =<< ccSrcSpan cc+        let description = mdl <> "." <> lbl <> " (" <> loc <> ")"+        modify $ (:) $ indent <> description <> "\t" <> show (_costCentreTree_cumulativeEntries childCct) <> "\t" <> show (_costCentreTree_ownEntries childCct)+        go (succ depth) childCct  showProfilingData :: IO () showProfilingData = do@@ -127,8 +131,8 @@ writeProfilingData p = do   writeFile p =<< formatCostCentreTree =<< getCostCentreTree -newtype ProfiledM m a = ProfiledM { runProfiledM :: m a }-  deriving (Functor, Applicative, Monad, MonadFix, MonadException, MonadAsyncException)+newtype ProfiledM m a = ProfiledM {runProfiledM :: m a}+  deriving (Applicative, Functor, Monad, MonadAsyncException, MonadException, MonadFix)  profileEvent :: Reflex t => Event t a -> Event t a profileEvent e = unsafePerformIO $ do@@ -138,13 +142,13 @@         return $ return $ Just x   return $ pushCheap f e ---TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs+-- TODO: Instead of profiling just the input or output of each one, profile all the inputs and all the outputs  instance Reflex t => Reflex (ProfiledTimeline t) where-  newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled { unBehavior_Profiled :: Behavior t a }-  newtype Event (ProfiledTimeline t) a = Event_Profiled { unEvent_Profiled :: Event t a }-  newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled { unDynamic_Profiled :: Dynamic t a }-  newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled { unIncremental_Profiled :: Incremental t p }+  newtype Behavior (ProfiledTimeline t) a = Behavior_Profiled {unBehavior_Profiled :: Behavior t a}+  newtype Event (ProfiledTimeline t) a = Event_Profiled {unEvent_Profiled :: Event t a}+  newtype Dynamic (ProfiledTimeline t) a = Dynamic_Profiled {unDynamic_Profiled :: Dynamic t a}+  newtype Incremental (ProfiledTimeline t) p = Incremental_Profiled {unIncremental_Profiled :: Incremental t p}   type PushM (ProfiledTimeline t) = ProfiledM (PushM t)   type PullM (ProfiledTimeline t) = ProfiledM (PullM t)   never = Event_Profiled never@@ -153,9 +157,12 @@   pushCheap f (Event_Profiled e) = coerce $ pushCheap (coerce f) $ profileEvent e   pull = Behavior_Profiled . pull . coerce   fanG (Event_Profiled e) = EventSelectorG $ coerce $ selectG (fanG $ profileEvent e)-  mergeG :: forall z (k :: z -> Type) q v. GCompare k+  mergeG+    :: forall z (k :: z -> Type) q v+     . GCompare k     => (forall a. q a -> Event (ProfiledTimeline t) (v a))-    -> DMap k q -> Event (ProfiledTimeline t) (DMap k v)+    -> DMap k q+    -> Event (ProfiledTimeline t) (DMap k v)   mergeG nt = Event_Profiled #. mergeG (coerce nt)   switch (Behavior_Profiled b) = coerce $ profileEvent $ switch (coerceBehavior b)   coincidence (Event_Profiled e) = coerce $ profileEvent $ coincidence (coerceEvent e)@@ -176,8 +183,10 @@     Coercion `trans` dynamicCoercion @t c `trans` Coercion   incrementalCoercion c d =     Coercion `trans` incrementalCoercion @t c d `trans` Coercion-  mergeIntIncremental = Event_Profiled . mergeIntIncremental .-    coerceWith (Coercion `trans` incrementalCoercion Coercion Coercion `trans` Coercion)+  mergeIntIncremental =+    Event_Profiled+      . mergeIntIncremental+      . coerceWith (Coercion `trans` incrementalCoercion Coercion Coercion `trans` Coercion)   fanInt (Event_Profiled e) = coerce $ fanInt $ profileEvent e  deriving instance Functor (Dynamic t) => Functor (Dynamic (ProfiledTimeline t))@@ -196,14 +205,18 @@   sample (Behavior_Profiled b) = ProfiledM $ sample b  instance Adjustable t m => Adjustable (ProfiledTimeline t) (ProfiledM m) where-  runWithReplace a0 a' = (fmap . fmap) coerce . lift $-    runWithReplace (coerce a0) (coerce $ coerce <$> a')-  traverseIntMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $-    traverseIntMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')-  traverseDMapWithKeyWithAdjust f dm0 dm' = (fmap . fmap) coerce . lift $-    traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')-  traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = (fmap . fmap) coerce . lift $-    traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) dm0 (coerce dm')+  runWithReplace a0 a' =+    (fmap . fmap) coerce . lift $+      runWithReplace (coerce a0) (coerce $ coerce <$> a')+  traverseIntMapWithKeyWithAdjust f dm0 dm' =+    (fmap . fmap) coerce . lift $+      traverseIntMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')+  traverseDMapWithKeyWithAdjust f dm0 dm' =+    (fmap . fmap) coerce . lift $+      traverseDMapWithKeyWithAdjust (\k v -> coerce $ f k v) dm0 (coerce dm')+  traverseDMapWithKeyWithAdjustWithMove f dm0 dm' =+    (fmap . fmap) coerce . lift $+      traverseDMapWithKeyWithAdjustWithMove (\k v -> coerce $ f k v) dm0 (coerce dm')  instance MonadTrans ProfiledM where   lift = ProfiledM
src/Reflex/Pure.hs view
@@ -3,11 +3,11 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE PolyKinds #-} -- There are two expected orphan instances in this module: --   * MonadSample (Pure t) ((->) t) --   * MonadHold (Pure t) ((->) t)@@ -30,16 +30,17 @@  import Control.Monad import Data.Dependent.Map (DMap)-import Data.GADT.Compare (GCompare) import qualified Data.Dependent.Map as DMap+import Data.GADT.Compare (GCompare) import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap+import Data.Kind (Type) import Data.Maybe import Data.MemoTrie import Data.Monoid import Data.Type.Coercion+ import Reflex.Class-import Data.Kind (Type)  -- | A completely pure-functional 'Reflex' timeline, identifying moments in time -- with the type @/t/@.@@ -49,20 +50,19 @@ -- any @/y :: t/@ such that @/'pred' x < y < x/@. The 'HasTrie' instance will be used -- exclusively to memoize functions of @/t/@, not for any of its other capabilities. instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where--  newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }-  newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }-  newtype Dynamic (Pure t) a = Dynamic { unDynamic :: t -> (a, Maybe a) }-  newtype Incremental (Pure t) p = Incremental { unIncremental :: t -> (PatchTarget p, Maybe p) }+  newtype Behavior (Pure t) a = Behavior {unBehavior :: t -> a}+  newtype Event (Pure t) a = Event {unEvent :: t -> Maybe a}+  newtype Dynamic (Pure t) a = Dynamic {unDynamic :: t -> (a, Maybe a)}+  newtype Incremental (Pure t) p = Incremental {unIncremental :: t -> (PatchTarget p, Maybe p)}    type PushM (Pure t) = (->) t   type PullM (Pure t) = (->) t    never :: Event (Pure t) a-  never = Event $ \_ -> Nothing+  never = Event $ const Nothing    constant :: a -> Behavior (Pure t) a-  constant x = Behavior $ \_ -> x+  constant x = Behavior $ const x    push :: (a -> PushM (Pure t) (Maybe b)) -> Event (Pure t) a -> Event (Pure t) b   push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t@@ -78,17 +78,17 @@   -- GCompare instance produces a different warning, due to that constraint   -- being present in the original class definition. -  --mergeG :: GCompare k => (forall a. q a -> Event (Pure t) (v a))+  -- mergeG :: GCompare k => (forall a. q a -> Event (Pure t) (v a))   --   -> DMap k q -> Event (Pure t) (DMap k v)   mergeG nt events = Event $ memo $ \t ->     let currentOccurrences = DMap.mapMaybeWithKey (\_ q -> case nt q of Event a -> a t) events     in if DMap.null currentOccurrences-       then Nothing-       else Just currentOccurrences+         then Nothing+         else Just currentOccurrences ---  The instance signature doeesn't compile, leave commented for documentation---  fanG :: GCompare k => Event (Pure t) (DMap k v) -> EventSelectorG (Pure t) k v-  fanG e = EventSelectorG $ \k -> Event $ \t -> unEvent e t >>= DMap.lookup k+  --  The instance signature doeesn't compile, leave commented for documentation+  --  fanG :: GCompare k => Event (Pure t) (DMap k v) -> EventSelectorG (Pure t) k v+  fanG e = EventSelectorG $ \k -> Event $ unEvent e >=> DMap.lookup k    switch :: Behavior (Pure t) (Event (Pure t) a) -> Event (Pure t) a   switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t@@ -107,8 +107,8 @@    -- See UNUSED_CONSTRAINT, above. -  --unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p-  --a) -> Incremental (Pure t) p a+  -- unsafeBuildIncremental :: Patch p => PullM (Pure t) a -> Event (Pure t) (p+  -- a) -> Incremental (Pure t) p a   unsafeBuildIncremental readV0 p = Incremental $ \t -> (readV0 t, unEvent p t)    mergeIncrementalG = mergeIncrementalImpl@@ -129,32 +129,35 @@   dynamicCoercion Coercion = Coercion   incrementalCoercion Coercion Coercion = Coercion -  fanInt e = EventSelectorInt $ \k -> Event $ \t -> unEvent e t >>= IntMap.lookup k+  fanInt e = EventSelectorInt $ \k -> Event $ unEvent e >=> IntMap.lookup k    mergeIntIncremental = mergeIntIncrementalImpl -mergeIncrementalImpl :: (PatchTarget p ~ DMap k q, GCompare k)+mergeIncrementalImpl+  :: (PatchTarget p ~ DMap k q, GCompare k)   => (forall a. q a -> Event (Pure t) (v a))-  -> Incremental (Pure t) p -> Event (Pure t) (DMap k v)+  -> Incremental (Pure t) p+  -> Event (Pure t) (DMap k v) mergeIncrementalImpl nt i = Event $ \t ->   let results = DMap.mapMaybeWithKey (\_ q -> case nt q of Event e -> e t) $ fst $ unIncremental i t   in if DMap.null results-     then Nothing-     else Just results+       then Nothing+       else Just results -mergeIntIncrementalImpl :: (PatchTarget p ~ IntMap (Event (Pure t) a)) => Incremental (Pure t) p -> Event (Pure t) (IntMap a)+mergeIntIncrementalImpl :: PatchTarget p ~ IntMap (Event (Pure t) a) => Incremental (Pure t) p -> Event (Pure t) (IntMap a) mergeIntIncrementalImpl i = Event $ \t ->   let results = IntMap.mapMaybeWithKey (\_ (Event e) -> e t) $ fst $ unIncremental i t   in if IntMap.null results-     then Nothing-     else Just results+       then Nothing+       else Just results  instance Functor (Dynamic (Pure t)) where-  fmap f d = Dynamic $ \t -> let (cur, upd) = unDynamic d t-                             in (f cur, fmap f upd)+  fmap f d = Dynamic $ \t ->+    let (cur, upd) = unDynamic d t+    in (f cur, fmap f upd)  instance Applicative (Dynamic (Pure t)) where-  pure a = Dynamic $ \_ -> (a, Nothing)+  pure a = Dynamic $ const (a, Nothing)   (<*>) = ap  instance Monad (Dynamic (Pure t)) where@@ -164,27 +167,28 @@         (cur :: b, updOuter :: Maybe b) = unDynamic (f curX) t         (updInner :: Maybe b, updBoth :: Maybe b) = case updX of           Nothing -> (Nothing, Nothing)-          Just nextX -> let (c, u) = unDynamic (f nextX) t-                        in (Just c, u)-    in (cur, getFirst $ mconcat $ map First [updBoth, updOuter, updInner])+          Just nextX ->+            let (c, u) = unDynamic (f nextX) t+            in (Just c, u)+    in (cur, getFirst $ mconcat $ map First [updBoth, updInner, updOuter])  instance MonadSample (Pure t) ((->) t) where-   sample :: Behavior (Pure t) a -> (t -> a)   sample = unBehavior  instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where-   hold :: a -> Event (Pure t) a -> t -> Behavior (Pure t) a   hold initialValue e initialTime = Behavior f-    where f = memo $ \sampleTime ->-            -- Really, the sampleTime should never be prior to the initialTime,-            -- because that would mean the Behavior is being sampled before-            -- being created.-            if sampleTime <= initialTime-            then initialValue-            else let lastTime = pred sampleTime-                 in fromMaybe (f lastTime) $ unEvent e lastTime+    where+      f = memo $ \sampleTime ->+        -- Really, the sampleTime should never be prior to the initialTime,+        -- because that would mean the Behavior is being sampled before+        -- being created.+        if sampleTime <= initialTime+          then initialValue+          else+            let lastTime = pred sampleTime+            in fromMaybe (f lastTime) $ unEvent e lastTime    holdDyn v0 = buildDynamic (return v0) @@ -195,17 +199,19 @@    holdIncremental :: Patch p => PatchTarget p -> Event (Pure t) p -> t -> Incremental (Pure t) p   holdIncremental initialValue e initialTime = Incremental $ \t -> (f t, unEvent e t)-    where f = memo $ \sampleTime ->-            -- Really, the sampleTime should never be prior to the initialTime,-            -- because that would mean the Behavior is being sampled before-            -- being created.-            if sampleTime <= initialTime-            then initialValue-            else let lastTime = pred sampleTime-                     lastValue = f lastTime-                 in case unEvent e lastTime of-                   Nothing -> lastValue-                   Just x -> fromMaybe lastValue $ apply x lastValue+    where+      f = memo $ \sampleTime ->+        -- Really, the sampleTime should never be prior to the initialTime,+        -- because that would mean the Behavior is being sampled before+        -- being created.+        if sampleTime <= initialTime+          then initialValue+          else+            let lastTime = pred sampleTime+                lastValue = f lastTime+            in case unEvent e lastTime of+                 Nothing -> lastValue+                 Just x -> fromMaybe lastValue $ apply x lastValue    headE = slowHeadE   now t = Event $ guard . (t ==)
src/Reflex/Query/Base.hs view
@@ -6,9 +6,9 @@ {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE StandaloneDeriving #-}  module Reflex.Query.Base   ( QueryT (..)@@ -20,7 +20,7 @@   , mapQueryT   ) where -import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.Morph@@ -31,7 +31,7 @@ import Data.Align import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap-import Data.Dependent.Sum (DSum(..))+import Data.Dependent.Sum (DSum (..)) import Data.Foldable import Data.Functor.Compose import Data.Functor.Misc@@ -43,7 +43,7 @@ import qualified Data.Map as Map import qualified Data.Semigroup as S import Data.Semigroup.Commutative-import Data.Some (Some(Some))+import Data.Some (Some (Some)) import Data.These  #if !MIN_VERSION_base(4,18,0)@@ -51,21 +51,22 @@ import Data.Monoid ((<>)) #endif -import Reflex.Class+import qualified Data.Patch.MapWithMove as MapWithMove+ import Reflex.Adjustable.Class+import Reflex.Class import Reflex.DynamicWriter.Class import Reflex.EventWriter.Base import Reflex.EventWriter.Class import Reflex.Host.Class-import qualified Data.Patch.MapWithMove as MapWithMove import Reflex.PerformEvent.Class import Reflex.PostBuild.Class import Reflex.Query.Class import Reflex.Requester.Class import Reflex.TriggerEvent.Class -newtype QueryT t q m a = QueryT { unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a }-  deriving (Functor, Applicative, Monad, MonadException, MonadFix, MonadIO, MonadAtomicRef, MonadCatch, MonadThrow, MonadMask)+newtype QueryT t q m a = QueryT {unQueryT :: StateT [Behavior t q] (EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m)) a}+  deriving (Applicative, Functor, Monad, MonadAtomicRef, MonadCatch, MonadException, MonadFix, MonadIO, MonadMask, MonadThrow)  deriving instance MonadHold t m => MonadHold t (QueryT t q m) deriving instance MonadSample t m => MonadSample t (QueryT t q m)@@ -91,7 +92,7 @@     ((r0, bs0), r') <- QueryT $ lift $ runWithReplace (runStateT a0 []) $ fmapCheap (flip runStateT [] . unQueryT) a'     let sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q         sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty-        bs' = fmapCheap snd $ r'+        bs' = fmapCheap snd r'     bbs <- hold bs0 bs'     let patches = flip pushCheap bs' $ \newBs -> do           oldBs <- sample bbs@@ -106,20 +107,26 @@         f' k v = fmap QueryTLoweredResult $ flip runStateT [] $ unQueryT $ f k v     (result0, result') <- QueryT $ lift $ traverseIntMapWithKeyWithAdjust f' im0 im'     let liftedResult0 = IntMap.map getQueryTLoweredResultValue result0-        liftedResult' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $-          IntMap.map (fmap getQueryTLoweredResultValue) p+        liftedResult' = fforCheap result' $ \(PatchIntMap p) ->+          PatchIntMap $+            IntMap.map (fmap getQueryTLoweredResultValue) p         liftedBs0 :: IntMap [Behavior t q]         liftedBs0 = IntMap.map getQueryTLoweredResultWritten result0         liftedBs' :: Event t (PatchIntMap [Behavior t q])-        liftedBs' = fforCheap result' $ \(PatchIntMap p) -> PatchIntMap $-          IntMap.map (fmap getQueryTLoweredResultWritten) p+        liftedBs' = fforCheap result' $ \(PatchIntMap p) ->+          PatchIntMap $+            IntMap.map (fmap getQueryTLoweredResultWritten) p         sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q         sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty-        accumBehaviors :: forall m'. MonadHold t m'-                       => IntMap [Behavior t q]-                       -> PatchIntMap [Behavior t q]-                       -> m' ( Maybe (IntMap [Behavior t q])-                             , Maybe (AdditivePatch q))+        accumBehaviors+          :: forall m'+           . MonadHold t m'+          => IntMap [Behavior t q]+          -> PatchIntMap [Behavior t q]+          -> m'+               ( Maybe (IntMap [Behavior t q])+               , Maybe (AdditivePatch q)+               )         -- f accumulates the child behavior state we receive from running traverseIntMapWithKeyWithAdjust for the underlying monad.         -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.         -- bs0 is a Map denoting the behaviors of the current children.@@ -145,26 +152,33 @@     tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch     return (liftedResult0, liftedResult') -  traverseDMapWithKeyWithAdjust :: forall (k :: Type -> Type) v v'. (GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> QueryT t q m (DMap k v', Event t (PatchDMap k v'))+  traverseDMapWithKeyWithAdjust :: forall (k :: Type -> Type) v v'. GCompare k => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> QueryT t q m (DMap k v', Event t (PatchDMap k v'))   traverseDMapWithKeyWithAdjust f dm0 dm' = do     let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)         f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v     (result0, result') <- QueryT $ lift $ traverseDMapWithKeyWithAdjust f' dm0 dm'     let liftedResult0 = mapKeyValuePairsMonotonic (\(k :=> Compose r) -> k :=> getQueryTLoweredResultValue r) result0-        liftedResult' = fforCheap result' $ \(PatchDMap p) -> PatchDMap $-          mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p+        liftedResult' = fforCheap result' $ \(PatchDMap p) ->+          PatchDMap $+            mapKeyValuePairsMonotonic (\(k :=> ComposeMaybe mr) -> k :=> ComposeMaybe (fmap (getQueryTLoweredResultValue . getCompose) mr)) p         liftedBs0 :: Map (Some k) [Behavior t q]         liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0         liftedBs' :: Event t (PatchMap (Some k) [Behavior t q])-        liftedBs' = fforCheap result' $ \(PatchDMap p) -> PatchMap $-          Map.fromDistinctAscList $ (\(k :=> ComposeMaybe mr) -> (Some k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p+        liftedBs' = fforCheap result' $ \(PatchDMap p) ->+          PatchMap+            $ Map.fromDistinctAscList+            $ (\(k :=> ComposeMaybe mr) -> (Some k, fmap (getQueryTLoweredResultWritten . getCompose) mr)) <$> DMap.toList p         sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q         sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty-        accumBehaviors :: forall m'. MonadHold t m'-                       => Map (Some k) [Behavior t q]-                       -> PatchMap (Some k) [Behavior t q]-                       -> m' ( Maybe (Map (Some k) [Behavior t q])-                             , Maybe (AdditivePatch q))+        accumBehaviors+          :: forall m'+           . MonadHold t m'+          => Map (Some k) [Behavior t q]+          -> PatchMap (Some k) [Behavior t q]+          -> m'+               ( Maybe (Map (Some k) [Behavior t q])+               , Maybe (AdditivePatch q)+               )         -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjust for the underlying monad.         -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.         -- bs0 is a Map denoting the behaviors of the current children.@@ -190,7 +204,7 @@     tellQueryIncremental $ unsafeBuildIncremental (fold <$> mapM sampleBs liftedBs0) qpatch     return (liftedResult0, liftedResult') -  traverseDMapWithKeyWithAdjustWithMove :: forall (k :: Type -> Type) v v'. (GCompare k) => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMapWithMove k v) -> QueryT t q m (DMap k v', Event t (PatchDMapWithMove k v'))+  traverseDMapWithKeyWithAdjustWithMove :: forall (k :: Type -> Type) v v'. GCompare k => (forall a. k a -> v a -> QueryT t q m (v' a)) -> DMap k v -> Event t (PatchDMapWithMove k v) -> QueryT t q m (DMap k v', Event t (PatchDMapWithMove k v'))   traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do     let f' :: forall a. k a -> v a -> EventWriterT t q (ReaderT (Dynamic t (QueryResult q)) m) (Compose (QueryTLoweredResult t q) v' a)         f' k v = fmap (Compose . QueryTLoweredResult) $ flip runStateT [] $ unQueryT $ f k v@@ -200,15 +214,24 @@         liftedBs0 :: Map (Some k) [Behavior t q]         liftedBs0 = Map.fromDistinctAscList $ (\(k :=> Compose r) -> (Some k, getQueryTLoweredResultWritten r)) <$> DMap.toList result0         liftedBs' :: Event t (PatchMapWithMove (Some k) [Behavior t q])-        liftedBs' = fforCheap result' $ weakenPatchDMapWithMoveWith (getQueryTLoweredResultWritten . getCompose) {- \(PatchDMap p) -> PatchMapWithMove $-          Map.fromDistinctAscList $ (\(k :=> mr) -> (Some k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}+        liftedBs' =+          fforCheap result' $+            weakenPatchDMapWithMoveWith+              ( getQueryTLoweredResultWritten . getCompose {- \(PatchDMap p) -> PatchMapWithMove $+                                                           Map.fromDistinctAscList $ (\(k :=> mr) -> (Some k, fmap (fmap (getQueryTLoweredResultWritten . getCompose)) mr)) <$> DMap.toList p -}+              )+         sampleBs :: forall m'. MonadSample t m' => [Behavior t q] -> m' q         sampleBs = foldlM (\b a -> (b <>) <$> sample a) mempty-        accumBehaviors' :: forall m'. MonadHold t m'-                        => Map (Some k) [Behavior t q]-                        -> PatchMapWithMove (Some k) [Behavior t q]-                        -> m' ( Maybe (Map (Some k) [Behavior t q])-                              , Maybe (AdditivePatch q))+        accumBehaviors'+          :: forall m'+           . MonadHold t m'+          => Map (Some k) [Behavior t q]+          -> PatchMapWithMove (Some k) [Behavior t q]+          -> m'+               ( Maybe (Map (Some k) [Behavior t q])+               , Maybe (AdditivePatch q)+               )         -- f accumulates the child behavior state we receive from running traverseDMapWithKeyWithAdjustWithMove for the underlying monad.         -- When an update occurs, it also computes a patch to communicate to the parent QueryT state.         -- bs0 is a Map denoting the behaviors of the current children.@@ -233,7 +256,7 @@                   MapWithMove.From_Move k'                     | k' == k -> return Nothing                     | otherwise -> case Map.lookup k' bs0 of-                  -- If we are moving from a non-existent key, that is a delete+                        -- If we are moving from a non-existent key, that is a delete                         Nothing -> maskMempty . negateG <$> sampleBs oldBs                         Just newBs -> maskMempty <$> ((~~) <$> sampleBs newBs <*> sampleBs oldBs)           -- we compute the patch by iterating over the update PatchMap and proceeding by cases. Then we fold over the@@ -257,7 +280,7 @@ instance PostBuild t m => PostBuild t (QueryT t q m) where   getPostBuild = lift getPostBuild -instance (MonadAsyncException m) => MonadAsyncException (QueryT t q m) where+instance MonadAsyncException m => MonadAsyncException (QueryT t q m) where   mask f = QueryT $ mask $ \unMask -> unQueryT $ f $ QueryT . unMask . unQueryT  instance TriggerEvent t m => TriggerEvent t (QueryT t q m) where@@ -289,16 +312,18 @@   (<>) = liftA2 (S.<>)  -- | withQueryT's QueryMorphism argument needs to be a group homomorphism in order to behave correctly-withQueryT :: (MonadFix m, PostBuild t m, Group q, Group q', Commutative q, Commutative q', Query q')-           => QueryMorphism q q'-           -> QueryT t q m a-           -> QueryT t q' m a+withQueryT+  :: (MonadFix m, PostBuild t m, Group q, Group q', Commutative q, Commutative q', Query q')+  => QueryMorphism q q'+  -> QueryT t q m a+  -> QueryT t q' m a withQueryT f a = do   r' <- askQueryResult   (result, q) <- lift $ runQueryT a $ mapQueryResult f <$> r'-  tellQueryIncremental $ unsafeBuildIncremental-    (fmap (mapQuery f) (sample (currentIncremental q)))-    (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)+  tellQueryIncremental $+    unsafeBuildIncremental+      (fmap (mapQuery f) (sample (currentIncremental q)))+      (fmapCheap (AdditivePatch . mapQuery f . unAdditivePatch) $ updatedIncremental q)   return result  -- | Maps a function over a 'QueryT' that can change the underlying monad@@ -306,34 +331,36 @@ mapQueryT f (QueryT a) = QueryT $ mapStateT (mapEventWriterT (mapReaderT f)) a  -- | dynWithQueryT's (Dynamic t QueryMorphism) argument needs to be a group homomorphism at all times in order to behave correctly-dynWithQueryT :: (MonadFix m, PostBuild t m, Group q, Commutative q, Group q', Commutative q', Query q')-           => Dynamic t (QueryMorphism q q')-           -> QueryT t q m a-           -> QueryT t q' m a+dynWithQueryT+  :: (MonadFix m, PostBuild t m, Group q, Commutative q, Group q', Commutative q', Query q')+  => Dynamic t (QueryMorphism q q')+  -> QueryT t q m a+  -> QueryT t q' m a dynWithQueryT f q = do   r' <- askQueryResult   (result, q') <- lift $ runQueryT q $ zipDynWith mapQueryResult f r'   tellQueryIncremental $ zipDynIncrementalWith mapQuery f q'   return result- where zipDynIncrementalWith g da ib =-         let eab = align (updated da) (updatedIncremental ib)-             ec = flip push eab $ \case-                 This a -> do-                   aOld <- sample $ current da-                   b <- sample $ currentIncremental ib-                   return $ Just $ AdditivePatch (g a b ~~ g aOld b)-                 That (AdditivePatch b) -> do-                   a <- sample $ current da-                   return $ Just $ AdditivePatch $ g a b-                 These a (AdditivePatch b) -> do-                   aOld <- sample $ current da-                   bOld <- sample $ currentIncremental ib-                   return $ Just $ AdditivePatch $ mconcat [ g a bOld, negateG (g aOld bOld), g a b]-         in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec+  where+    zipDynIncrementalWith g da ib =+      let eab = align (updated da) (updatedIncremental ib)+          ec = flip push eab $ \case+            This a -> do+              aOld <- sample $ current da+              b <- sample $ currentIncremental ib+              return $ Just $ AdditivePatch (g a b ~~ g aOld b)+            That (AdditivePatch b) -> do+              a <- sample $ current da+              return $ Just $ AdditivePatch $ g a b+            These a (AdditivePatch b) -> do+              aOld <- sample $ current da+              bOld <- sample $ currentIncremental ib+              return $ Just $ AdditivePatch $ mconcat [g a bOld, negateG (g aOld bOld), g a b]+      in unsafeBuildIncremental (g <$> sample (current da) <*> sample (currentIncremental ib)) ec  instance (Monad m, Group q, Commutative q, Query q, Reflex t) => MonadQuery t q (QueryT t q m) where   tellQueryIncremental q = do-    QueryT (modify (currentIncremental q:))+    QueryT (modify (currentIncremental q :))     QueryT (lift (tellEvent (fmapCheap unAdditivePatch (updatedIncremental q))))   askQueryResult = QueryT ask   queryIncremental q = do
src/Reflex/Query/Class.hs view
@@ -19,7 +19,6 @@   , QueryMorphism (..)   , SelectedCount (..)   , combineSelectedCounts-   , MonadQuery (..)   , tellQueryDyn   , queryDyn@@ -36,10 +35,10 @@ import Data.Ix import Data.Kind (Type) import Data.Map.Monoidal (MonoidalMap)-import qualified Data.Map.Monoidal as MonoidalMap+import qualified Data.Map.Monoidal as MMap+import Data.Monoid hiding ((<>)) import Data.Semigroup.Commutative import Data.Void-import Data.Monoid hiding ((<>)) import Foreign.Storable  #if !MIN_VERSION_base(4,18,0)@@ -59,7 +58,7 @@  instance (Ord k, Query v) => Query (MonoidalMap k v) where   type QueryResult (MonoidalMap k v) = MonoidalMap k (QueryResult v)-  crop q r = MonoidalMap.intersectionWith (flip crop) r q+  crop q r = MMap.intersectionWith (flip crop) r q  -- | the result of two queries is both results. instance (Query a, Query b) => Query (a, b) where@@ -101,10 +100,11 @@  instance Category QueryMorphism where   id = QueryMorphism id id-  qm . qm' = QueryMorphism-    { _queryMorphism_mapQuery = mapQuery qm . mapQuery qm'-    , _queryMorphism_mapQueryResult = mapQueryResult qm' . mapQueryResult qm-    }+  qm . qm' =+    QueryMorphism+      { _queryMorphism_mapQuery = mapQuery qm . mapQuery qm'+      , _queryMorphism_mapQueryResult = mapQueryResult qm' . mapQueryResult qm+      }  -- | Apply a 'QueryMorphism' to a 'Query' mapQuery :: QueryMorphism q q' -> q -> q'@@ -116,8 +116,8 @@  -- | This type can be used to track of the frequency of interest in a given 'Query'. See note on -- 'combineSelectedCounts'-newtype SelectedCount = SelectedCount { unSelectedCount :: Int }-  deriving (Eq, Ord, Show, Read, Integral, Num, Bounded, Enum, Real, Ix, Bits, FiniteBits, Storable, Data)+newtype SelectedCount = SelectedCount {unSelectedCount :: Int}+  deriving (Bits, Bounded, Data, Enum, Eq, FiniteBits, Integral, Ix, Num, Ord, Read, Real, Show, Storable)  instance Semigroup SelectedCount where   SelectedCount a <> SelectedCount b = SelectedCount (a + b)
src/Reflex/Requester/Base/Internal.hs view
@@ -1,5 +1,3 @@--- | This module provides 'RequesterT', the standard implementation of--- 'Requester'. {-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE ApplicativeDo #-} {-# LANGUAGE CPP #-}@@ -13,14 +11,17 @@ {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module provides 'RequesterT', the standard implementation of+-- 'Requester'. module Reflex.Requester.Base.Internal where  import Control.Monad-import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.Identity@@ -43,10 +44,9 @@ import Data.Map (Map) import qualified Data.Map as Map import Data.Proxy-import Data.Some (Some(Some))+import Data.Some (Some (Some)) import Data.Type.Equality import Data.Unique.Tag- import GHC.Exts (Any) import Unsafe.Coerce @@ -55,8 +55,8 @@ import Data.Monoid ((<>)) #endif -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.Dynamic import Reflex.EventWriter.Class import Reflex.Host.Class@@ -65,7 +65,7 @@ import Reflex.Requester.Class import Reflex.TriggerEvent.Class ---TODO: Make this module type-safe+-- TODO: Make this module type-safe  newtype TagMap (f :: Type -> Type) = TagMap (IntMap Any) @@ -76,7 +76,7 @@  data RequesterDataKey a where   RequesterDataKey_Single :: {-# UNPACK #-} !(MyTag (Single a)) -> RequesterDataKey a-  RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a --TODO: Don't put a second Int here (or in the other Multis); use a single Int instead+  RequesterDataKey_Multi :: {-# UNPACK #-} !(MyTag Multi) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a -- TODO: Don't put a second Int here (or in the other Multis); use a single Int instead   RequesterDataKey_Multi2 :: GCompare k => {-# UNPACK #-} !(MyTag (Multi2 k)) -> !(Some k) -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a   RequesterDataKey_Multi3 :: {-# UNPACK #-} !(MyTag Multi3) -> {-# UNPACK #-} !Int -> {-# UNPACK #-} !Int -> !(RequesterDataKey a) -> RequesterDataKey a @@ -84,10 +84,14 @@ singletonRequesterData rdk v = case rdk of   RequesterDataKey_Single k -> RequesterData $ singletonTagMap k $ Entry v   RequesterDataKey_Multi k k' k'' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ singletonRequesterData k'' v-  RequesterDataKey_Multi2 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ Multi2Contents-    { _multi2Contents_values = Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v-    , _multi2Contents_dict = Dict-    }+  RequesterDataKey_Multi2 k k' k'' k''' ->+    RequesterData+      $ singletonTagMap k+      $ Entry+      $ Multi2Contents+        { _multi2Contents_values = Map.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v+        , _multi2Contents_dict = Dict+        }   RequesterDataKey_Multi3 k k' k'' k''' -> RequesterData $ singletonTagMap k $ Entry $ IntMap.singleton k' $ IntMap.singleton k'' $ singletonRequesterData k''' v  mergeRequesterData :: RequesterData f -> RequesterData f -> RequesterData f@@ -102,10 +106,11 @@       MyTagType_Single -> a       MyTagType_Multi -> IntMap.unionWith mergeRequesterData a b       MyTagType_Multi2 -> case _multi2Contents_dict a of-        Dict -> Multi2Contents-          { _multi2Contents_values = Map.unionWith (IntMap.unionWith mergeRequesterData) (_multi2Contents_values a) (_multi2Contents_values b)-          , _multi2Contents_dict = Dict-          }+        Dict ->+          Multi2Contents+            { _multi2Contents_values = Map.unionWith (IntMap.unionWith mergeRequesterData) (_multi2Contents_values a) (_multi2Contents_values b)+            , _multi2Contents_dict = Dict+            }       MyTagType_Multi3 -> IntMap.unionWith (IntMap.unionWith mergeRequesterData) a b     g' :: (forall a. MyTag a -> Entry f a -> Entry f a -> Entry f a) -> Int -> Any -> Any -> Any     g' f rawKey a b =@@ -142,8 +147,9 @@  tagMapToList :: forall f. TagMap f -> [DSum MyTag f] tagMapToList (TagMap m) = f <$> IntMap.toList m-  where f :: (Int, Any) -> DSum MyTag f-        f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v+  where+    f :: (Int, Any) -> DSum MyTag f+    f (k, v) = MyTag k :=> (unsafeCoerce :: Any -> f a) v  traverseTagMapWithKey :: forall t f g. Applicative t => (forall a. MyTag a -> f a -> t (g a)) -> TagMap f -> t (TagMap g) traverseTagMapWithKey f (TagMap m) = TagMap <$> IntMap.traverseWithKey g m@@ -153,19 +159,22 @@  -- | Runs in reverse to accommodate for the fact that we accumulate it in reverse traverseRequesterData :: forall m request response. Applicative m => (forall a. request a -> m (response a)) -> RequesterData request -> m (RequesterData response)-traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m --TODO: reverse this, since our tags are in reverse order-  where go :: forall x. MyTag x -> Entry request x -> m (Entry response x)-        go k (Entry request) = Entry <$> case myKeyType k of-          MyTagType_Single -> f request-          MyTagType_Multi -> traverse (traverseRequesterData f) request-          MyTagType_Multi2 -> case request of-            Multi2Contents { _multi2Contents_values = request', _multi2Contents_dict = Dict } -> do-              v <- traverse (traverse (traverseRequesterData f)) request'-              pure $ Multi2Contents+traverseRequesterData f (RequesterData m) = RequesterData <$> traverseTagMapWithKey go m -- TODO: reverse this, since our tags are in reverse order+  where+    go :: forall x. MyTag x -> Entry request x -> m (Entry response x)+    go k (Entry request) =+      Entry <$> case myKeyType k of+        MyTagType_Single -> f request+        MyTagType_Multi -> traverse (traverseRequesterData f) request+        MyTagType_Multi2 -> case request of+          Multi2Contents {_multi2Contents_values = request', _multi2Contents_dict = Dict} -> do+            v <- traverse (traverse (traverseRequesterData f)) request'+            pure $+              Multi2Contents                 { _multi2Contents_values = v                 , _multi2Contents_dict = Dict                 }-          MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request+        MyTagType_Multi3 -> traverse (traverse (traverseRequesterData f)) request  -- | 'traverseRequesterData' with its arguments flipped forRequesterData :: forall request response m. Applicative m => RequesterData request -> (forall a. request a -> m (response a)) -> m (RequesterData response)@@ -216,7 +225,7 @@   , _multi2Contents_values :: {-# UNPACK #-} !(Map (Some k) (IntMap (RequesterData request)))   } -newtype Entry request x = Entry { unEntry :: EntryContents request x }+newtype Entry request x = Entry {unEntry :: EntryContents request x}  {-# INLINE singleEntry #-} singleEntry :: f a -> Entry f (Single a)@@ -232,9 +241,9 @@  -- | We use a hack here to pretend we have x ~ request a; we don't want to use a GADT, because GADTs (even with zero-size existential contexts) can't be newtypes -- WARNING: This type should never be exposed.  In particular, this is extremely unsound if a MyTag from one run of runRequesterT is ever compared against a MyTag from another-newtype MyTag x = MyTag Int deriving (Show, Eq, Ord, Enum)+newtype MyTag x = MyTag Int deriving (Enum, Eq, Ord, Show) -newtype MyTagWrap (f :: Type -> Type) x = MyTagWrap Int deriving (Show, Eq, Ord, Enum)+newtype MyTagWrap (f :: Type -> Type) x = MyTagWrap Int deriving (Enum, Eq, Ord, Show)  {-# INLINE castMyTagWrap #-} castMyTagWrap :: MyTagWrap f (Entry f x) -> MyTagWrap g (Entry g x)@@ -243,8 +252,8 @@ instance GEq MyTag where   (MyTag a) `geq` (MyTag b) =     if a == b-    then Just $ unsafeCoerce Refl-    else Nothing+      then Just $ unsafeCoerce Refl+      else Nothing  instance GCompare MyTag where   (MyTag a) `gcompare` (MyTag b) =@@ -256,8 +265,8 @@ instance GEq (MyTagWrap f) where   (MyTagWrap a) `geq` (MyTagWrap b) =     if a == b-    then Just $ unsafeCoerce Refl-    else Nothing+      then Just $ unsafeCoerce Refl+      else Nothing  instance GCompare (MyTagWrap f) where   (MyTagWrap a) `gcompare` (MyTagWrap b) =@@ -272,13 +281,19 @@   }  -- | A basic implementation of 'Requester'.-newtype RequesterT t request (response :: Type -> Type) m a = RequesterT { unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a }-  deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException-           , MonadAsyncException-           , MonadCatch-           , MonadThrow-           , MonadMask-           )+newtype RequesterT t request (response :: Type -> Type) m a = RequesterT {unRequesterT :: StateT (RequesterState t request) (ReaderT (EventSelectorInt t Any) m) a}+  deriving+    ( Applicative+    , Functor+    , Monad+    , MonadAsyncException+    , MonadCatch+    , MonadException+    , MonadFix+    , MonadIO+    , MonadMask+    , MonadThrow+    )  deriving instance MonadSample t m => MonadSample t (RequesterT t request response m) deriving instance MonadHold t m => MonadHold t (RequesterT t request response m)@@ -299,32 +314,41 @@ instance (Semigroup a, Monad m) => Semigroup (RequesterT t request response m a) where   (<>) = liftA2 (<>) - -- | Run a 'RequesterT' action.  The resulting 'Event' will fire whenever -- requests are made, and responses should be provided in the input 'Event'. -- The 'Tag' keys will be used to return the responses to the same place the -- requests were issued.-runRequesterT :: (Reflex t, Monad m)-              => RequesterT t request response m a-              -> Event t (RequesterData response) --TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse-              -> m (a, Event t (RequesterData request)) --TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild+runRequesterT+  :: (Reflex t, Monad m)+  => RequesterT t request response m a+  -> Event t (RequesterData response) -- TODO: This DMap will be in reverse order, so we need to make sure the caller traverses it in reverse+  -> m (a, Event t (RequesterData request)) -- TODO: we need to hide these 'MyTag's here, because they're unsafe to mix in the wild runRequesterT (RequesterT a) responses = do-  (result, s) <- runReaderT (runStateT a $ RequesterState (-4) []) $ fanInt $-    coerceEvent responses+  (result, s) <-+    runReaderT (runStateT a $ RequesterState (-4) [])+      $ fanInt+      $ coerceEvent responses   return (result, fmapCheap (RequesterData . TagMap) $ mergeInt $ IntMap.fromDistinctAscList $ _requesterState_requests s)  -- | Map a function over the request and response of a 'RequesterT' withRequesterT   :: (Reflex t, MonadFix m)-  => (forall x. req x -> req' x) -- ^ The function to map over the request-  -> (forall x. rsp' x -> rsp x) -- ^ The function to map over the response-  -> RequesterT t req rsp m a -- ^ The internal 'RequesterT' whose input and output will be transformed-  -> RequesterT t req' rsp' m a -- ^ The resulting 'RequesterT'+  => (forall x. req x -> req' x)+  -- ^ The function to map over the request+  -> (forall x. rsp' x -> rsp x)+  -- ^ The function to map over the response+  -> RequesterT t req rsp m a+  -- ^ The internal 'RequesterT' whose input and output will be transformed+  -> RequesterT t req' rsp' m a+  -- ^ The resulting 'RequesterT' withRequesterT freq frsp child = do   rec let rsp = fmap (runIdentity . traverseRequesterData (Identity . frsp)) rsp'       (a, req) <- lift $ runRequesterT child rsp-      rsp' <- fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry) $ requesting' $-        fmapCheap (multiEntry . IntMap.singleton 0) $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req+      rsp' <-+        fmap (flip selectInt 0 . fanInt . fmapCheap unMultiEntry)+          $ requesting'+          $ fmapCheap (multiEntry . IntMap.singleton 0)+          $ fmap (runIdentity . traverseRequesterData (Identity . freq)) req   return a  instance (Reflex t, Monad m) => Requester t (RequesterT t request response m) where@@ -339,10 +363,12 @@   old <- RequesterT get   let n = _requesterState_nextMyTag old .|. myTagTypeOffset (Proxy :: Proxy x)       t = MyTagWrap n-  RequesterT $ put $ RequesterState-    { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4-    , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old-    }+  RequesterT+    $ put+    $ RequesterState+      { _requesterState_nextMyTag = _requesterState_nextMyTag old - 0x4+      , _requesterState_requests = (n, (unsafeCoerce :: Event t (Entry request x) -> Event t Any) req) : _requesterState_requests old+      }   return t  {-# INLINE responseFromTag #-}@@ -380,51 +406,55 @@ instance (Reflex t, Adjustable t m, MonadHold t m, MonadFix m) => Adjustable t (RequesterT t request response m) where   runWithReplace = runWithReplaceRequesterTWith $ \dm0 dm' -> lift $ runWithReplace dm0 dm'   traverseIntMapWithKeyWithAdjust = traverseIntMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseIntMapWithKeyWithAdjust f dm0 dm') patchIntMapNewElementsMap mergeIntIncremental-  {-# INLINABLE traverseDMapWithKeyWithAdjust #-}+  {-# INLINEABLE traverseDMapWithKeyWithAdjust #-}   traverseDMapWithKeyWithAdjust = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjust f dm0 dm') mapPatchDMap weakenPatchDMapWith patchMapNewElementsMap mergeMapIncremental   traverseDMapWithKeyWithAdjustWithMove = traverseDMapWithKeyWithAdjustRequesterTWith (\f dm0 dm' -> lift $ traverseDMapWithKeyWithAdjustWithMove f dm0 dm') mapPatchDMapWithMove weakenPatchDMapWithMoveWith patchMapWithMoveNewElementsMap mergeMapIncrementalWithMove  requesting' :: (MyTagTypeOffset x, Monad m) => Event t (Entry request x) -> RequesterT t request response m (Event t (Entry response x)) requesting' = responseFromTag . castMyTagWrap <=< tagRequest -{-# INLINABLE runWithReplaceRequesterTWith #-}-runWithReplaceRequesterTWith :: forall m t request response a b. (Reflex t, MonadHold t m-                                                                 , MonadFix m-                                                                 )-                             => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))-                             -> RequesterT t request response m a-                             -> Event t (RequesterT t request response m b)-                             -> RequesterT t request response m (a, Event t b)+{-# INLINEABLE runWithReplaceRequesterTWith #-}+runWithReplaceRequesterTWith+  :: forall m t request response a b+   . ( Reflex t+     , MonadHold t m+     , MonadFix m+     )+  => (forall a' b'. m a' -> Event t (m b') -> RequesterT t request response m (a', Event t b'))+  -> RequesterT t request response m a+  -> Event t (RequesterT t request response m b)+  -> RequesterT t request response m (a, Event t b) runWithReplaceRequesterTWith f a0 a' = do   rec na' <- numberOccurrencesFrom 1 a'-      responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests --TODO: Investigate whether we can really get rid of the prompt stuff here+      responses <- fmap (fmapCheap unMultiEntry) $ requesting' $ fmapCheap multiEntry $ switchPromptlyDyn requests -- TODO: Investigate whether we can really get rid of the prompt stuff here       let responses' = fanInt responses-      ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap ((,) n) $ runRequesterT a $ selectInt responses' n) na'+      ((result0, requests0), v') <- f (runRequesterT a0 (selectInt responses' 0)) $ fmapCheap (\(n, a) -> fmap (n,) $ runRequesterT a $ selectInt responses' n) na'       requests <- holdDyn (fmapCheap (IntMap.singleton 0) requests0) $ fmapCheap (\(n, (_, reqs)) -> fmapCheap (IntMap.singleton n) reqs) v'   return (result0, fmapCheap (fst . snd) v')  {-# INLINE traverseIntMapWithKeyWithAdjustRequesterTWith #-}-traverseIntMapWithKeyWithAdjustRequesterTWith :: forall t request response m v v' p.-                                        ( Reflex t-                                        , MonadHold t m-                                        , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))-                                        , Patch (p (Event t (IntMap (RequesterData request))))-                                        , Functor p-                                        , MonadFix m-                                        )-                                     => (   (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))-                                         -> IntMap (IntMap.Key, v)-                                         -> Event t (p (IntMap.Key, v))-                                         -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))-                                        )-                                     -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))-                                     -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))-                                     -> (IntMap.Key -> v -> RequesterT t request response m v')-                                     -> IntMap v-                                     -> Event t (p v)-                                     -> RequesterT t request response m (IntMap v', Event t (p v'))+traverseIntMapWithKeyWithAdjustRequesterTWith+  :: forall t request response m v v' p+   . ( Reflex t+     , MonadHold t m+     , PatchTarget (p (Event t (IntMap (RequesterData request)))) ~ IntMap (Event t (IntMap (RequesterData request)))+     , Patch (p (Event t (IntMap (RequesterData request))))+     , Functor p+     , MonadFix m+     )+  => ( (IntMap.Key -> (IntMap.Key, v) -> m (Event t (IntMap (RequesterData request)), v'))+       -> IntMap (IntMap.Key, v)+       -> Event t (p (IntMap.Key, v))+       -> RequesterT t request response m (IntMap (Event t (IntMap (RequesterData request)), v'), Event t (p (Event t (IntMap (RequesterData request)), v')))+     )+  -> (p (Event t (IntMap (RequesterData request))) -> IntMap (Event t (IntMap (RequesterData request))))+  -> (Incremental t (p (Event t (IntMap (RequesterData request)))) -> Event t (IntMap (IntMap (RequesterData request))))+  -> (IntMap.Key -> v -> RequesterT t request response m v')+  -> IntMap v+  -> Event t (p v)+  -> RequesterT t request response m (IntMap v', Event t (p v')) traverseIntMapWithKeyWithAdjustRequesterTWith base patchNewElements mergePatchIncremental f dm0 dm' = do-  rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here+  rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests -- TODO: Investigate whether we can really get rid of the prompt stuff here       let responses :: EventSelectorInt t (IntMap (RequesterData response))           responses = fanInt $ fmapCheap unpack response           unpack :: Entry response Multi3 -> IntMap (IntMap (RequesterData response))@@ -433,10 +463,10 @@           pack = Entry           f' :: IntMap.Key -> (Int, v) -> m (Event t (IntMap (RequesterData request)), v')           f' k (n, v) = do-            (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k --TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time?+            (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ selectInt responses k -- TODO: Instead of doing mapMaybeCheap, can we share a fanInt across all instances of a given key, or at least the ones that are adjacent in time?             return (fmapCheap (IntMap.singleton n) myRequests, result)       ndm' <- numberOccurrencesFrom 1 dm'-      (children0, children') <- base f' (fmap ((,) 0) dm0) $ fmap (\(n, dm) -> fmap ((,) n) dm) ndm' --TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable+      (children0, children') <- base f' (fmap (0,) dm0) $ fmap (\(n, dm) -> fmap (n,) dm) ndm' -- TODO: Avoid this somehow, probably by adding some sort of per-cohort information passing to Adjustable       let result0 = fmap snd children0           result' = fforCheap children' $ fmap snd           requests0 :: IntMap (Event t (IntMap (RequesterData request)))@@ -444,41 +474,43 @@           requests' :: Event t (p (Event t (IntMap (RequesterData request))))           requests' = fforCheap children' $ fmap fst           promptRequests :: Event t (IntMap (IntMap (RequesterData request)))-          promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'+          promptRequests = coincidence $ fmapCheap (mergeInt . patchNewElements) requests' -- TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'       requests <- holdIncremental requests0 requests'   return (result0, result')  {-# INLINE traverseDMapWithKeyWithAdjustRequesterTWith #-}-traverseDMapWithKeyWithAdjustRequesterTWith :: forall k t request response m v v' p p'.-                                        ( GCompare k-                                        , Reflex t-                                        , MonadHold t m-                                        , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))-                                        , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))-                                        , MonadFix m-                                        )-                                     => (forall k' v1 v2. GCompare k'-                                         => (forall a. k' a -> v1 a -> m (v2 a))-                                         -> DMap k' v1-                                         -> Event t (p k' v1)-                                         -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))-                                        )-                                     -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)-                                     -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)-                                     -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)-                                     -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))-                                     -> (forall a. k a -> v a -> RequesterT t request response m (v' a))-                                     -> DMap k v-                                     -> Event t (p k v)-                                     -> RequesterT t request response m (DMap k v', Event t (p k v'))+traverseDMapWithKeyWithAdjustRequesterTWith+  :: forall k t request response m v v' p p'+   . ( GCompare k+     , Reflex t+     , MonadHold t m+     , PatchTarget (p' (Some k) (Event t (IntMap (RequesterData request)))) ~ Map (Some k) (Event t (IntMap (RequesterData request)))+     , Patch (p' (Some k) (Event t (IntMap (RequesterData request))))+     , MonadFix m+     )+  => ( forall k' v1 v2+        . GCompare k'+       => (forall a. k' a -> v1 a -> m (v2 a))+       -> DMap k' v1+       -> Event t (p k' v1)+       -> RequesterT t request response m (DMap k' v2, Event t (p k' v2))+     )+  -> (forall v1 v2. (forall a. v1 a -> v2 a) -> p k v1 -> p k v2)+  -> (forall v1 v2. (forall a. v1 a -> v2) -> p k v1 -> p' (Some k) v2)+  -> (forall v2. p' (Some k) v2 -> Map (Some k) v2)+  -> (forall a. Incremental t (p' (Some k) (Event t a)) -> Event t (Map (Some k) a))+  -> (forall a. k a -> v a -> RequesterT t request response m (v' a))+  -> DMap k v+  -> Event t (p k v)+  -> RequesterT t request response m (DMap k v', Event t (p k v')) traverseDMapWithKeyWithAdjustRequesterTWith base mapPatch weakenPatchWith patchNewElements mergePatchIncremental f dm0 dm' = do-  rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests --TODO: Investigate whether we can really get rid of the prompt stuff here+  rec response <- requesting' $ fmapCheap pack $ promptRequests `mappend` mergePatchIncremental requests -- TODO: Investigate whether we can really get rid of the prompt stuff here       let responses :: EventSelector t (Const2 (Some k) (IntMap (RequesterData response)))           responses = fanMap $ fmapCheap unpack response           unpack :: Entry response (Multi2 k) -> Map (Some k) (IntMap (RequesterData response))           unpack = _multi2Contents_values . unEntry           pack :: Map (Some k) (IntMap (RequesterData request)) -> Entry request (Multi2 k)-          pack m = Entry $ Multi2Contents { _multi2Contents_values = m, _multi2Contents_dict = Dict }+          pack m = Entry $ Multi2Contents {_multi2Contents_values = m, _multi2Contents_dict = Dict}           f' :: forall a. k a -> Compose ((,) Int) v a -> m (Compose ((,) (Event t (IntMap (RequesterData request)))) v' a)           f' k (Compose (n, v)) = do             (result, myRequests) <- runRequesterT (f k v) $ mapMaybeCheap (IntMap.lookup n) $ select responses (Const2 (Some k))@@ -492,16 +524,16 @@           requests' :: Event t (p' (Some k) (Event t (IntMap (RequesterData request))))           requests' = fforCheap children' $ weakenPatchWith $ fst . getCompose           promptRequests :: Event t (Map (Some k) (IntMap (RequesterData request)))-          promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' --TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'+          promptRequests = coincidence $ fmapCheap (mergeMap . patchNewElements) requests' -- TODO: Create a mergeIncrementalPromptly, and use that to eliminate this 'coincidence'       requests <- holdIncremental requests0 requests'   return (result0, result') -data Decoder rawResponse response =-  forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)+data Decoder rawResponse response+  = forall a. Decoder (RequesterDataKey a) (rawResponse -> response a)  matchResponsesWithRequests-  :: forall t rawRequest rawResponse request response m.-     ( MonadFix m+  :: forall t rawRequest rawResponse request response m+   . ( MonadFix m      , MonadHold t m      , Reflex t      )@@ -512,7 +544,8 @@   -- ^ The outgoing requests   -> Event t (Int, rawResponse)   -- ^ The incoming responses, tagged by an identifying key-  -> m ( Event t (Map Int rawRequest)+  -> m+       ( Event t (Map Int rawRequest)        , Event t (RequesterData response)        )   -- ^ A map of outgoing wire-format requests and an event of responses keyed@@ -523,8 +556,8 @@ -- and uses the provided request "decoder" function to process -- incoming responses. matchResponseMapWithRequests-  :: forall t rawRequest rawResponse request response m.-     ( MonadFix m+  :: forall t rawRequest rawResponse request response m+   . ( MonadFix m      , MonadHold t m      , Reflex t      )@@ -535,7 +568,8 @@   -- ^ The outgoing requests   -> Event t (Map Int rawResponse)   -- ^ A map of incoming responses, tagged by an identifying key-  -> m ( Event t (Map Int rawRequest)+  -> m+       ( Event t (Map Int rawRequest)        , Event t (RequesterData response)        )   -- ^ A map of outgoing wire-format requests and an event of responses keyed@@ -543,10 +577,11 @@ matchResponseMapWithRequests f send recv = do   rec nextId <- hold 1 $ fmap (\(next, _, _) -> next) outgoing       waitingFor :: Incremental t (PatchMap Int (Decoder rawResponse response)) <--        holdIncremental mempty $ leftmost-          [ fmap (\(_, outstanding, _) -> outstanding) outgoing-          , snd <$> incoming-          ]+        holdIncremental mempty $+          leftmost+            [ fmap (\(_, outstanding, _) -> outstanding) outgoing+            , snd <$> incoming+            ]       let outgoing = processOutgoing nextId send           incoming = processIncoming waitingFor recv   return (fmap (\(_, _, rawReqs) -> rawReqs) outgoing, fst <$> incoming)@@ -560,10 +595,13 @@       -- The next available key       -> Event t (RequesterData request)       -- The outgoing request-      -> Event t ( Int-                 , PatchMap Int (Decoder rawResponse response)-                 , Map Int rawRequest )-      -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests+      -> Event+           t+           ( Int+           , PatchMap Int (Decoder rawResponse response)+           , Map Int rawRequest+           )+    -- The new next-available-key, a map of requests expecting responses, and the tagged raw requests     processOutgoing nextId out = flip pushAlways out $ \dm -> do       oldNextId <- sample nextId       let (result, newNextId) = flip runState oldNextId $ forM (requesterDataToList dm) $ \(k :=> v) -> do@@ -571,8 +609,10 @@             put $ succ n             let (rawReq, rspF) = f v             return (n, rawReq, Decoder k rspF)-          patchWaitingFor = PatchMap $ Map.fromList $-            (\(n, _, dec) -> (n, Just dec)) <$> result+          patchWaitingFor =+            PatchMap+              $ Map.fromList+              $ (\(n, _, dec) -> (n, Just dec)) <$> result           toSend = Map.fromList $ (\(n, rawReq, _) -> (n, rawReq)) <$> result       return (newNextId, patchWaitingFor, toSend)     -- Looks up the each incoming raw response in a map of response@@ -585,12 +625,16 @@       -> Event t (Map Int rawResponse)       -- A incoming response paired with its identifying key       -> Event t (RequesterData response, PatchMap Int v)-      -- The decoded response and a patch that clears the outstanding responses queue+    -- The decoded response and a patch that clears the outstanding responses queue     processIncoming waitingFor inc = flip push inc $ \rspMap -> do       wf <- sample $ currentIncremental waitingFor       let match rawRsp (Decoder k rspF) =             let rsp = rspF rawRsp             in singletonRequesterData k rsp           matches = Map.intersectionWith match rspMap wf-      pure $ if Map.null matches then Nothing else Just-        (Map.foldl' mergeRequesterData emptyRequesterData matches, PatchMap $ Nothing <$ matches)+      pure $+        if Map.null matches+          then Nothing+          else+            Just+              (Map.foldl' mergeRequesterData emptyRequesterData matches, PatchMap $ Nothing <$ matches)
src/Reflex/Requester/Class.hs view
@@ -1,8 +1,3 @@--- | This module defines 'Requester', which indicates that an action can make--- requests and receive responses to them.  Typically, this is used for things--- like a WebSocket, where it's desirable to collect many potential sources of--- events and send them over a single channel, then distribute the results back--- out efficiently to their original request sites. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-}@@ -11,11 +6,16 @@ {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines 'Requester', which indicates that an action can make+-- requests and receive responses to them.  Typically, this is used for things+-- like a WebSocket, where it's desirable to collect many potential sources of+-- events and send them over a single channel, then distribute the results back+-- out efficiently to their original request sites. module Reflex.Requester.Class- ( Requester (..)- , withRequesting- , requestingIdentity- ) where+  ( Requester (..)+  , withRequesting+  , requestingIdentity+  ) where  import Control.Monad.Fix import Control.Monad.Identity@@ -23,6 +23,7 @@ import qualified Control.Monad.State.Lazy as Lazy import Control.Monad.State.Strict import Data.Kind (Type)+ import Reflex.Class  -- | A 'Requester' action can trigger requests of type @Request m a@ based on@@ -34,16 +35,18 @@ class (Reflex t, Monad m) => Requester t m | m -> t where   -- | The type of requests that this 'Requester' can emit   type Request m :: Type -> Type+   -- | The type of responses that this 'Requester' can receive   type Response m :: Type -> Type+   -- | Emit a request whenever the given 'Event' fires, and return responses in   -- the resulting 'Event'.   --   -- Semantically, the response event occurs at a later time than the request event.   requesting :: Event t (Request m a) -> m (Event t (Response m a))+   -- | Emit a request whenever the given 'Event' fires, and ignore all responses.   requesting_ :: Event t (Request m a) -> m ()-  instance Requester t m => Requester t (ReaderT r m) where   type Request (ReaderT r m) = Request m
src/Reflex/Spider.hs view
@@ -14,8 +14,6 @@   , runSpiderHostForTimeline   , newSpiderTimeline   , withSpiderTimeline-    -- * Deprecated-  , SpiderEnv   ) where  import Reflex.Spider.Internal
+ src/Reflex/Spider/Height.hs view
@@ -0,0 +1,241 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE PatternSynonyms #-}+{-# LANGUAGE ViewPatterns #-}++module Reflex.Spider.Height+  ( Height+  , pattern ZeroHeight+  , pattern InvalidHeight+  , invalidHeightBeingTraversed+  , isUnmarkedInvalidHeight+  , pattern ValidHeight+  , zeroHeight+  , invalidHeight+  , maxHeight+  , raiseHeight+  , coincidenceHeight+  , compareHeight+  , heightSlotPassed+  , HeightBag+  , heightBagEmpty+  , heightBagHeight+  , heightBagParentCount+  , heightBagAddParent+  , heightBagRemoveParent+  , heightBagInvalidateParent+  , heightBagRecalculateParent+  , heightBagSuccHeight+  , HeightQueue+  , heightQueueEmpty+  , heightQueueInsert+  , heightQueueNext+  ) where++import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif++--------------------------------------------------------------------------------+-- Height data+--------------------------------------------------------------------------------++debugCycles :: Bool+#ifdef DEBUG_CYCLES+debugCycles = True+#else+debugCycles = False+#endif++newtype Height = Height Int+  deriving (Show)++{-# INLINE unsafeHeightAsInt #-}+unsafeHeightAsInt :: Height -> Int+unsafeHeightAsInt (Height h) = h++pattern ZeroHeight :: Height+pattern ZeroHeight = Height 0++pattern InvalidHeight :: Height+pattern InvalidHeight <- (isInvalidHeight -> True)+  where+    InvalidHeight = Height (-1000)++{-# INLINE isInvalidHeight #-}+isInvalidHeight :: Height -> Bool+isInvalidHeight (Height h) = h == (-1000) || debugCycles && h == (-1001)++isUnmarkedInvalidHeight :: Height -> Bool+isUnmarkedInvalidHeight (Height h) = h == (-1000)++pattern ValidHeight :: Height+pattern ValidHeight <- Height ((>= 0) -> True)++pattern UnsafeValidHeight :: Int -> Height+pattern UnsafeValidHeight n <- Height (\x -> if x >= 0 then Just x else Nothing -> Just n)++{-# INLINE zeroHeight #-}+zeroHeight :: Height+zeroHeight = Height 0++{-# INLINE invalidHeight #-}+invalidHeight :: Height+invalidHeight = Height (-1000)++{-# INLINE maxHeight #-}+maxHeight :: Height+maxHeight = Height maxBound++-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents+{-# INLINE invalidHeightBeingTraversed #-}+invalidHeightBeingTraversed :: Height+invalidHeightBeingTraversed = Height (-1001)++{-# COMPLETE InvalidHeight, ValidHeight #-}+{-# COMPLETE InvalidHeight, UnsafeValidHeight #-}++{-# INLINE coincidenceHeight #-}+coincidenceHeight :: Height -> Height -> Height+coincidenceHeight (UnsafeValidHeight outer) (UnsafeValidHeight inner) = Height (max outer inner)+coincidenceHeight InvalidHeight ValidHeight = invalidHeight+coincidenceHeight ValidHeight InvalidHeight = invalidHeight+coincidenceHeight InvalidHeight InvalidHeight = invalidHeight++{-# INLINE raiseHeight #-}+raiseHeight :: Height -> Height -> Maybe Height+raiseHeight (UnsafeValidHeight from) (UnsafeValidHeight to)+  | to > from = Just (Height to)+  | otherwise = Nothing+raiseHeight from to =+  error $ "raiseHeight was passed special height: " <> show from <> " " <> show to++-- | Safe compare, throw an error if either is special.+{-# INLINE compareHeight #-}+compareHeight :: Height -> Height -> Ordering+compareHeight (UnsafeValidHeight a) (UnsafeValidHeight b) = compare a b+compareHeight a b = error $ "compareHeight: special height(s): " <> show a <> " " <> show b++-- Used in merges+{-# INLINE heightSlotPassed #-}+heightSlotPassed :: Height -> Height -> Bool+heightSlotPassed (UnsafeValidHeight current) (UnsafeValidHeight mine) = current >= mine+heightSlotPassed ValidHeight InvalidHeight = True+heightSlotPassed InvalidHeight _ = error "heightSlotPassed: current height is special"++--------------------------------------------------------------------------------+-- Heightbag+--------------------------------------------------------------------------------++-- | Valid merge parents' heights and the number of parents with invalid+-- heights.+data HeightBag = HeightBag+  { _heightBag_invalidParents :: {-# UNPACK #-} !Int+  , _heightBag_contents :: !(IntMap Word) -- Number of parents in each height bucket+  }+  deriving (Eq, Ord, Read, Show)++{-# INLINE heightBagEmpty #-}+heightBagEmpty :: HeightBag+heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty++{-# INLINE heightBagHeight #-}+heightBagHeight :: HeightBag -> Height+heightBagHeight b@(HeightBag invalidParents _) = case compare invalidParents 0 of+  EQ -> heightBagSuccHeight b+  GT -> invalidHeight+  LT -> error $ "heightBagHeight: more heights than parents: " <> show b++{-# INLINE heightBagParentCount #-}+heightBagParentCount :: HeightBag -> Int+heightBagParentCount (HeightBag invalidParents c) = invalidParents + fromIntegral (sum (IntMap.elems c))++{-# INLINE heightBagAddParent #-}+heightBagAddParent :: Height -> HeightBag -> HeightBag+heightBagAddParent h (HeightBag invalidParents c) = heightBagVerify $ case h of+  ValidHeight -> HeightBag invalidParents (insertHeight h c)+  InvalidHeight -> HeightBag (succ invalidParents) c++{-# INLINE heightBagRemoveParent #-}+heightBagRemoveParent :: Height -> HeightBag -> HeightBag+heightBagRemoveParent h b@(HeightBag invalidParents c) = heightBagVerify $ case h of+  ValidHeight -> HeightBag invalidParents (deleteHeight h b)+  InvalidHeight -> HeightBag (pred invalidParents) c++{-# INLINE heightBagInvalidateParent #-}+heightBagInvalidateParent :: Height -> HeightBag -> HeightBag+heightBagInvalidateParent h b@(HeightBag invalidParents _) =+  heightBagVerify $+    HeightBag (succ invalidParents) (deleteHeight h b)++{-# INLINE heightBagRecalculateParent #-}+heightBagRecalculateParent :: Height -> HeightBag -> HeightBag+heightBagRecalculateParent h (HeightBag invalidParents c) =+  heightBagVerify $+    HeightBag (pred invalidParents) (insertHeight h c)++{-# INLINE insertHeight #-}+insertHeight :: Height -> IntMap Word -> IntMap Word+insertHeight (Height h) = IntMap.insertWith (+) h 1++{-# INLINE deleteHeight #-}+deleteHeight :: Height -> HeightBag -> IntMap Word+deleteHeight (Height h) b@(HeightBag _ c) = IntMap.alter decrement h c+  where+    decrement Nothing = error $ "deleteHeight: Height " <> show h <> " not present in bag " <> show b+    decrement (Just 1) = Nothing+    decrement (Just old) = Just $ pred old++{-# INLINE heightBagVerify #-}+heightBagVerify :: HeightBag -> HeightBag+#ifdef DEBUG+heightBagVerify b@(HeightBag invalidParents c) = if+  | invalidParents < 0+    -> error $ "heightBagVerify: more heights than parents: " <> show b+  | unsafeHeightAsInt invalidHeight `IntMap.member` c+    -> error $ "heightBagVerify: contains invalid height: " <> show b+  | otherwise -> b+#else+heightBagVerify = id+#endif++heightBagSuccHeight :: HeightBag -> Height+heightBagSuccHeight (HeightBag _ c) = case IntMap.lookupMax c of+  Just (h, _) -> Height (succ h)+  Nothing -> zeroHeight++--------------------------------------------------------------------------------+-- HeightQueue+--------------------------------------------------------------------------------++newtype HeightQueue a = HeightQueue (IntMap [a])+  deriving (Eq, Ord, Read, Show)++{-# INLINE heightQueueEmpty #-}+heightQueueEmpty :: HeightQueue a+heightQueueEmpty = HeightQueue IntMap.empty++{-# INLINE heightQueueInsert #-}+heightQueueInsert :: Height -> a -> HeightQueue a -> HeightQueue a+heightQueueInsert height a (HeightQueue q) =+  heightQueueVerifyKey height+    $ HeightQueue+    $ IntMap.insertWith (++) (unsafeHeightAsInt height) [a] q++{-# INLINE heightQueueNext #-}+heightQueueNext :: HeightQueue a -> Maybe (Height, [a], HeightQueue a)+heightQueueNext (HeightQueue q) = case IntMap.minViewWithKey q of+  Just ((h, as), q') -> Just (Height h, as, HeightQueue q')+  Nothing -> Nothing++{-# INLINE heightQueueVerifyKey #-}+heightQueueVerifyKey :: Height -> HeightQueue a -> HeightQueue a+#ifdef DEBUG+heightQueueVerifyKey height q = case height of+  ValidHeight -> q+  _ -> error $ "heightQueueInsert: refusing special height " <> show height+#else+heightQueueVerifyKey _ q = q+#endif
src/Reflex/Spider/Internal.hs view
@@ -1,2935 +1,3023 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-}-{-# LANGUAGE EmptyDataDecls #-}-{-# LANGUAGE ExistentialQuantification #-}-{-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE FlexibleInstances #-}-{-# LANGUAGE FunctionalDependencies #-}-{-# LANGUAGE GADTs #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-}-{-# LANGUAGE LambdaCase #-}-{-# LANGUAGE RankNTypes #-}-{-# LANGUAGE RoleAnnotations #-}-{-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE TypeFamilies #-}-{-# LANGUAGE TypeOperators #-}-{-# LANGUAGE UndecidableInstances #-}-{-# LANGUAGE PolyKinds #-}-{-# LANGUAGE DeriveFunctor #-}-{-# LANGUAGE StandaloneDeriving #-}-{-# LANGUAGE InstanceSigs #-}-{-# LANGUAGE MultiWayIf #-}-{-# OPTIONS_GHC -Wunused-binds #-}---- | This module is the implementation of the 'Spider' 'Reflex' engine.  It uses--- a graph traversal algorithm to propagate 'Event's and 'Behavior's.-module Reflex.Spider.Internal-  ( module Reflex.Spider.Internal-  ) where--import Control.Concurrent-import Control.Exception-import Control.Monad hiding (forM, forM_, mapM, mapM_)-import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)-import Control.Monad.Exception-import Control.Monad.Fix-import Control.Monad.Primitive-import Control.Monad.Reader.Class-import Control.Monad.IO.Class-import Control.Monad.ReaderIO-import Control.Monad.Ref-import qualified Control.Monad.Fail as MonadFail-import Data.Align-import Data.Coerce-import Data.Dependent.Map (DMap)-import qualified Data.Dependent.Map as DMap-import Data.Dependent.Sum (DSum (..))-import Data.FastMutableIntMap (FastMutableIntMap)-import qualified Data.FastMutableIntMap as FastMutableIntMap-import Data.Foldable hiding (concat, elem, sequence_)-import Data.Functor.Constant-import Data.Functor.Misc-import Data.Functor.Product-import Data.GADT.Compare-import Data.IntMap.Strict (IntMap)-import qualified Data.IntMap.Strict as IntMap-import Data.IORef-import Data.Kind (Type)-import Data.Maybe hiding (mapMaybe)-import Data.Proxy-import Data.These-import Data.Traversable-import Data.Type.Equality ((:~:)(Refl))-import GHC.Exts hiding (toList)-import GHC.IORef (IORef (..))-import GHC.Stack-import Reflex.FastWeak-import System.IO.Unsafe-import System.Mem.Weak-import Unsafe.Coerce-import Witherable (Filterable, mapMaybe)--#if !MIN_VERSION_base(4,18,0)-import Control.Applicative (liftA2)-import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)-import Control.Monad.Fail (MonadFail)-import Data.List (isPrefixOf)-import Data.Monoid (mempty, (<>))-#else-import Control.Monad.Identity-#endif--#ifdef MIN_VERSION_semialign-#if MIN_VERSION_these(0,8,0)-import Data.These.Combinators (justThese)-#endif-#if MIN_VERSION_semialign(1,1,0)-import Data.Zip (Zip (..))-#endif-#endif--#ifdef DEBUG_CYCLES-import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)-#endif--import Data.List.NonEmpty (NonEmpty (..), nonEmpty)-import qualified Data.List.NonEmpty as NonEmpty-import Data.Tree (Forest, Tree (..), drawForest)--#ifdef DEBUG_HIDE_INTERNALS-import Data.List (isPrefixOf)-#endif--import Data.FastWeakBag (FastWeakBag, FastWeakBagTicket)-import qualified Data.FastWeakBag as FastWeakBag--import Data.Reflection-import Data.Some (Some(Some))-import Data.Type.Coercion-import Data.Profunctor.Unsafe ((#.), (.#))-import Data.WeakBag (WeakBag, WeakBagTicket, _weakBag_children)-import qualified Data.WeakBag as WeakBag-import qualified Reflex.Class-import qualified Reflex.Class as R-import qualified Reflex.Host.Class-import Reflex.NotReady.Class-import Data.Patch-import qualified Data.Patch.DMapWithMove as PatchDMapWithMove-import Reflex.PerformEvent.Base (PerformEventT)--#ifdef DEBUG_TRACE_EVENTS-import qualified Data.ByteString.Char8 as BS8-import System.IO (stderr)-import Data.List (isPrefixOf)-#endif---- TODO stdout might not be the best channel for debug output-debugStrLn :: String -> IO ()-debugStrLn = putStrLn--#ifdef DEBUG_TRACE_EVENTS-withStackOneLine :: (BS8.ByteString -> a) -> a-withStackOneLine expr = unsafePerformIO $ do-  stack <- currentCallStack-  return (expr . BS8.pack  . unwords . dropInternal . reverse $ stack)-    where dropInternal = filterStack "Reflex.Spider.Internal"--#endif--debugPropagate :: Bool--debugInvalidateHeight :: Bool--debugInvalidate :: Bool--#ifdef DEBUG-#define DEBUG_NODEIDS--#ifdef DEBUG_TRACE_PROPAGATION-debugPropagate = True-#else-debugPropagate = False-#endif--#ifdef DEBUG_TRACE_HEIGHT-debugInvalidateHeight = True-#else-debugInvalidateHeight = False-#endif--#ifdef DEBUG_TRACE_INVALIDATION-debugInvalidate = True-#else-debugInvalidate = False-#endif--class HasNodeId a where-  getNodeId :: a -> Int--instance HasNodeId (CacheSubscribed x a) where-  getNodeId = _cacheSubscribed_nodeId--instance HasNodeId (FanInt x a) where-  getNodeId = _fanInt_nodeId--instance HasNodeId (Hold x p) where-  getNodeId = holdNodeId--instance HasNodeId (SwitchSubscribed x a) where-  getNodeId = switchSubscribedNodeId--instance HasNodeId (FanSubscribed x v a) where-  getNodeId = fanSubscribedNodeId--instance HasNodeId (CoincidenceSubscribed x a) where-  getNodeId = coincidenceSubscribedNodeId--instance HasNodeId (RootSubscribed x a) where-  getNodeId = rootSubscribedNodeId--instance HasNodeId (Pull x a) where-  getNodeId = pullNodeId--{-# INLINE showNodeId #-}-showNodeId :: HasNodeId a => a -> String-showNodeId = showNodeId' . getNodeId--showNodeId' :: Int -> String-showNodeId' = ("#"<>) . show---#else--debugPropagate = False-debugInvalidateHeight = False-debugInvalidate = False---- This must be inline, or error messages will cause memory leaks due to retaining the node in question-{-# INLINE showNodeId #-}-showNodeId :: a -> String-showNodeId _ = ""--{-# INLINE showNodeId' #-}-showNodeId' :: Int -> String-showNodeId' _ = ""--#endif--#ifdef DEBUG_NODEIDS-{-# NOINLINE nextNodeIdRef #-}-nextNodeIdRef :: IORef Int-nextNodeIdRef = unsafePerformIO $ newIORef 1--newNodeId :: IO Int-newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)-#endif------------------------------------------------------------------------------------- EventSubscription-------------------------------------------------------------------------------------NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back--- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.-data EventSubscription x = EventSubscription-  { _eventSubscription_unsubscribe :: !(IO ())-  , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)-  }--unsubscribe :: EventSubscription x -> IO ()-unsubscribe (EventSubscription u _) = u------------------------------------------------------------------------------------- Event-----------------------------------------------------------------------------------newtype Event x a = Event { unEvent :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }--{-# INLINE subscribeAndRead #-}-subscribeAndRead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)-subscribeAndRead = unEvent--{-# RULES-"cacheEvent/cacheEvent" forall e. cacheEvent (cacheEvent e) = cacheEvent e-"cacheEvent/pushCheap" forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)-"hold/cacheEvent" forall f e. hold f (cacheEvent e) = hold f e-  #-}---- | Construct an 'Event' equivalent to that constructed by 'push', but with no--- caching; if the computation function is very cheap, this is (much) more--- efficient than 'push'-{-# INLINE [1] pushCheap #-}-pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b-pushCheap !f e = Event $ \sub -> do-  (subscription, occ) <- subscribeAndRead e $ debugSubscriber' "push" $ sub-    { subscriberPropagate = \a -> do-        mb <- f a-        mapM_ (subscriberPropagate sub) mb-    }-  occ' <- join <$> mapM f occ-  return (subscription, occ')---- | A subscriber that never triggers other 'Event's-{-# INLINE terminalSubscriber #-}-terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a-terminalSubscriber p = Subscriber-  { subscriberPropagate = p-  , subscriberInvalidateHeight = \_ -> return ()-  , subscriberRecalculateHeight = \_ -> return ()-  }---- | Subscribe to an Event only for the duration of one occurrence-{-# INLINE subscribeAndReadHead #-}-subscribeAndReadHead :: Event x a -> Subscriber x a -> EventM x (EventSubscription x, Maybe a)-subscribeAndReadHead e sub = do-  subscriptionRef <- liftIO $ newIORef $ error "subscribeAndReadHead: not initialized"-  (subscription, occ) <- subscribeAndRead e $ debugSubscriber' "head" $ sub-    { subscriberPropagate = \a -> do-        liftIO $ unsubscribe =<< readIORef subscriptionRef-        subscriberPropagate sub a-    }-  liftIO $ case occ of-    Nothing -> writeIORef subscriptionRef $! subscription-    Just _ -> unsubscribe subscription-  return (subscription, occ)----TODO: Make this lazy in its input event-headE :: Defer (SomeMergeInit x) m => Event x a -> m (Event x a)-headE originalE = do-  parent <- liftIO $ newIORef $ Just originalE-  defer $ SomeMergeInit $ do --TODO: Rename SomeMergeInit appropriately-    let clearParent = liftIO $ writeIORef parent Nothing-    (_, occ) <- subscribeAndReadHead originalE $ terminalSubscriber $ const clearParent-    when (isJust occ) clearParent-  return $ Event $ \sub ->-    liftIO (readIORef parent) >>= \case-      Nothing -> subscribeAndReadNever-      Just e -> subscribeAndReadHead e sub--data CacheSubscribed x a-   = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(FastWeakBag (Subscriber x a))-                     , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)-                     , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))-#ifdef DEBUG_NODEIDS-                     , _cacheSubscribed_nodeId :: {-# UNPACK #-} !Int-#endif-                     }--nowSpiderEventM :: HasSpiderTimeline x => EventM x (R.Event (SpiderTimeline x) ())-nowSpiderEventM = SpiderEvent <$> now--now :: Defer (Some Clear) m => m (Event x ())-now = do-  nowOrNot <- liftIO $ newIORef $ Just ()-  scheduleClear nowOrNot-  return . Event $ \_ -> do-    occ <- liftIO . readIORef $ nowOrNot-    return ( EventSubscription (return ()) eventSubscribedNow-           , occ-           )---- | Construct an 'Event' whose value is guaranteed not to be recomputed--- repeatedly------TODO: Try a caching strategy where we subscribe directly to the parent when---there's only one subscriber, and then build our own FastWeakBag only when a second---subscriber joins-{-# NOINLINE [0] cacheEvent #-}-cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a-cacheEvent e =-#ifdef DEBUG_TRACE_EVENTS-  withStackOneLine $ \callSite -> Event $-#else-  Event $-#endif-  unsafePerformIO $ do-    mSubscribedRef :: IORef (FastWeak (CacheSubscribed x a))-        <- newIORef emptyFastWeak-    pure $ \sub -> {-# SCC "cacheEvent" #-} do-#ifdef DEBUG_TRACE_EVENTS-          unless (BS8.null callSite) $ liftIO $ BS8.hPutStrLn stderr callSite-#endif-          subscribedTicket <- liftIO (readIORef mSubscribedRef >>= getFastWeakTicket) >>= \case-            Just subscribedTicket -> return subscribedTicket-            Nothing -> do-#ifdef DEBUG_NODEIDS-              nodeId <- liftIO newNodeId-#endif-              subscribers <- liftIO FastWeakBag.empty-              occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below-#ifdef DEBUG_NODEIDS-              (parentSub, occ) <- subscribeAndRead e $ debugSubscriber' ("cacheEvent" <> showNodeId' nodeId) $ Subscriber-#else-              (parentSub, occ) <- subscribeAndRead e $ Subscriber-#endif-                  { subscriberPropagate = \a -> do-                      liftIO $ writeIORef occRef (Just a)-                      scheduleClear occRef-                      propagateFast a subscribers-                  , subscriberInvalidateHeight = FastWeakBag.traverse_ subscribers . invalidateSubscriberHeight-                  , subscriberRecalculateHeight = FastWeakBag.traverse_ subscribers . recalculateSubscriberHeight-                  }-              when (isJust occ) $ do-                liftIO $ writeIORef occRef occ -- Set the initial value of occRef; we don't need to do this if occ is Nothing-                scheduleClear occRef-              let !subscribed = CacheSubscribed-                    { _cacheSubscribed_subscribers = subscribers-                    , _cacheSubscribed_parent = parentSub-                    , _cacheSubscribed_occurrence = occRef-#ifdef DEBUG_NODEIDS-                    , _cacheSubscribed_nodeId = nodeId-#endif-                    }-              subscribedTicket <- liftIO $ mkFastWeakTicket subscribed-              liftIO $ writeIORef mSubscribedRef =<< getFastWeakTicketWeak subscribedTicket-              return subscribedTicket-          liftIO $ cacheSubscription sub mSubscribedRef subscribedTicket--cacheSubscription :: Subscriber x a -> IORef (FastWeak (CacheSubscribed x a))-                  -> FastWeakTicket (CacheSubscribed x a) -> IO (EventSubscription x, Maybe a)-cacheSubscription sub mSubscribedRef subscribedTicket = do-  subscribed <- getFastWeakTicketValue subscribedTicket-  ticket <- FastWeakBag.insert sub $ _cacheSubscribed_subscribers subscribed-  occ <- readIORef $ _cacheSubscribed_occurrence subscribed--  let parentSub = _cacheSubscribed_parent subscribed-      es = EventSubscription-        { _eventSubscription_unsubscribe = do-          FastWeakBag.remove ticket--          isEmpty <- FastWeakBag.isEmpty $ _cacheSubscribed_subscribers subscribed-          when isEmpty $ do-            writeIORef mSubscribedRef emptyFastWeak-            unsubscribe parentSub-          touch ticket-          touch subscribedTicket-        , _eventSubscription_subscribed = EventSubscribed-          { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub-          , eventSubscribedRetained = toAny subscribedTicket-#ifdef DEBUG_CYCLES-          , eventSubscribedGetParents = return [_eventSubscription_subscribed parentSub]-          , eventSubscribedHasOwnHeightRef = False-          , eventSubscribedWhoCreated = whoCreatedIORef mSubscribedRef-#endif-          }-        }-  return (es, occ)---subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)-subscribe e s = fst <$> subscribeAndRead e s--{-# INLINE wrap #-}-wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)-wrap tag getSpecificSubscribed sub = do-  (sln, subd, occ) <- getSpecificSubscribed sub-  let es = tag subd-  return (EventSubscription (WeakBag.remove sln >> touch sln) es, occ)--eventRoot :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Event x a-eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r--subscribeAndReadNever :: EventM x (EventSubscription x, Maybe a)-subscribeAndReadNever = return (EventSubscription (return ()) eventSubscribedNever, Nothing)--eventNever :: Event x a-eventNever = Event $ const subscribeAndReadNever--eventFan :: (GCompare k, HasSpiderTimeline x) => k a -> Fan x k v -> Event x (v a)-eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f--eventSwitch :: HasSpiderTimeline x => Switch x a -> Event x a-eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s--eventCoincidence :: HasSpiderTimeline x => Coincidence x a -> Event x a-eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c--eventHold :: Hold x p -> Event x p-eventHold !h = Event $ subscribeHoldEvent h--eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p-eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub--{-# INLINE subscribeCoincidenceInner #-}-subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Height, EventSubscribed x)-subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do-  subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe-  (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner-  innerHeight <- liftIO $ getEventSubscribedHeight innerSubd-  let height = max innerHeight outerHeight-  defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing-  return (innerOcc, height, innerSubd)------------------------------------------------------------------------------------- Subscriber-----------------------------------------------------------------------------------data Subscriber x a = Subscriber-  { subscriberPropagate :: !(a -> EventM x ())-  , subscriberInvalidateHeight :: !(Height -> IO ())-  , subscriberRecalculateHeight :: !(Height -> IO ())-  }--newSubscriberHold :: (HasSpiderTimeline x, Patch p) => Hold x p -> IO (Subscriber x p)-newSubscriberHold h = return $ Subscriber-  { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h-  , subscriberInvalidateHeight = \_ -> return ()-  , subscriberRecalculateHeight = \_ -> return ()-  }--newSubscriberFan :: forall x k v. (HasSpiderTimeline x, GCompare k) => FanSubscribed x k v -> IO (Subscriber x (DMap k v))-newSubscriberFan subscribed = debugSubscriber ("SubscriberFan " <> showNodeId subscribed)  $ Subscriber-  { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do-      subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed-      tracePropagate (Proxy :: Proxy x) $ show (DMap.size subs) <> " keys subscribed, " <> show (DMap.size a) <> " keys firing"-      liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a-      scheduleClear $ fanSubscribedOccurrence subscribed-      let f _ (Pair v subsubs) = do-            propagate v $ _fanSubscribedChildren_list subsubs-            return $ Constant ()-      _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_-      return ()-  , subscriberInvalidateHeight = \old -> do-      subscribers <- readIORef $ fanSubscribedSubscribers subscribed-      forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old-  , subscriberRecalculateHeight = \new -> do-      subscribers <- readIORef $ fanSubscribedSubscribers subscribed-      forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse_ (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new-  }--newSubscriberSwitch :: forall x a. HasSpiderTimeline x => SwitchSubscribed x a -> IO (Subscriber x a)-newSubscriberSwitch subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber-  { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do-      liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a-      scheduleClear $ switchSubscribedOccurrence subscribed-      propagate a $ switchSubscribedSubscribers subscribed-  , subscriberInvalidateHeight = \_ -> do-      oldHeight <- readIORef $ switchSubscribedHeight subscribed-      when (oldHeight /= invalidHeight) $ do-        writeIORef (switchSubscribedHeight subscribed) $! invalidHeight-        WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight-  , subscriberRecalculateHeight = (`updateSwitchHeight` subscribed)-    }--newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))-newSubscriberCoincidenceOuter subscribed = debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $ Subscriber-  { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do-      outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed-      tracePropagate (Proxy :: Proxy x) $ "  outerHeight = " <> show outerHeight-      (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed-      tracePropagate (Proxy :: Proxy x) $ "  isJust occ = " <> show (isJust occ)-      tracePropagate (Proxy :: Proxy x) $ "  innerHeight = " <> show innerHeight--      liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd-      scheduleClear $ coincidenceSubscribedInnerParent subscribed-      case occ of-        Nothing ->-          when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height-            writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight-            WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight-            WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight-        Just o -> do -- Since it's already firing, no need to adjust height-          liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ-          scheduleClear $ coincidenceSubscribedOccurrence subscribed-          propagate o $ coincidenceSubscribedSubscribers subscribed-  , subscriberInvalidateHeight  = \_ -> invalidateCoincidenceHeight subscribed-  , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed-  }--newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO (Subscriber x a)-newSubscriberCoincidenceInner subscribed = debugSubscriber ("SubscriberCoincidenceInner" <> showNodeId subscribed) $ Subscriber-  { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do-#ifdef DEBUG-      occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed-      case occ of-        Just _ -> error "Coincidence inner is propagating, but coincidence occurrence is already known?"-        Nothing -> do-#endif          -          liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a-          scheduleClear $ coincidenceSubscribedOccurrence subscribed-          propagate a $ coincidenceSubscribedSubscribers subscribed-  , subscriberInvalidateHeight  = \_ -> invalidateCoincidenceHeight subscribed-  , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed-  }--invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()-invalidateSubscriberHeight = flip subscriberInvalidateHeight--recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()-recalculateSubscriberHeight = flip subscriberRecalculateHeight---- | Propagate everything at the current height-propagate :: forall x a. a -> WeakBag (Subscriber x a) -> EventM x ()-propagate a subscribers = withIncreasedDepth (Proxy::Proxy x) $-  -- 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-  --TODO: Should we check if nodes already have their values before propagating?  Maybe we're re-doing work-  WeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a---- | Propagate everything at the current height-propagateFast :: forall x a. a -> FastWeakBag (Subscriber x a) -> EventM x ()-propagateFast a subscribers = withIncreasedDepth (Proxy::Proxy x) $-  -- 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-  --TODO: Should we check if nodes already have their values before propagating?  Maybe we're re-doing work-  FastWeakBag.traverse_ subscribers $ \s -> subscriberPropagate s a------------------------------------------------------------------------------------- EventSubscribed-----------------------------------------------------------------------------------toAny :: a -> Any-toAny = unsafeCoerce---- Why do we use Any here, instead of just giving eventSubscribedRetained an--- existential type? Sadly, GHC does not currently know how to unbox types--- with existentially quantified fields. So instead we just coerce values--- to type Any on the way in. Since we never coerce them back, this is--- perfectly safe.-data EventSubscribed x = EventSubscribed-  { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)-  , eventSubscribedRetained :: {-# NOUNPACK #-} !Any-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents :: !(IO [EventSubscribed x]) -- For debugging loops-  , eventSubscribedHasOwnHeightRef :: !Bool-  , eventSubscribedWhoCreated :: !(IO [String])-#endif-  }--eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x-eventSubscribedRoot !r = EventSubscribed-  { eventSubscribedHeightRef = zeroRef-  , eventSubscribedRetained = toAny r-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = return []-  , eventSubscribedHasOwnHeightRef = False-  , eventSubscribedWhoCreated = return ["root"]-#endif-  }--eventSubscribedNever :: EventSubscribed x-eventSubscribedNever = EventSubscribed-  { eventSubscribedHeightRef = zeroRef-  , eventSubscribedRetained = toAny ()-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = return []-  , eventSubscribedHasOwnHeightRef = False-  , eventSubscribedWhoCreated = return ["never"]-#endif-  }-eventSubscribedNow :: EventSubscribed x-eventSubscribedNow = EventSubscribed-  { eventSubscribedHeightRef = zeroRef-  , eventSubscribedRetained = toAny ()-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = return []-  , eventSubscribedHasOwnHeightRef = False-  , eventSubscribedWhoCreated = return ["now"]-#endif-  }--eventSubscribedFan :: FanSubscribed x k v -> EventSubscribed x-eventSubscribedFan !subscribed = EventSubscribed-  { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed-  , eventSubscribedRetained = toAny subscribed-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = return [_eventSubscription_subscribed $ fanSubscribedParent subscribed]-  , eventSubscribedHasOwnHeightRef = False-  , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed-#endif-  }--eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x-eventSubscribedSwitch !subscribed = EventSubscribed-  { eventSubscribedHeightRef = switchSubscribedHeight subscribed-  , eventSubscribedRetained = toAny subscribed-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = do-      s <- readIORef $ switchSubscribedCurrentParent subscribed-      return [_eventSubscription_subscribed s]-  , eventSubscribedHasOwnHeightRef = True-  , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed-#endif-  }--eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x-eventSubscribedCoincidence !subscribed = EventSubscribed-  { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed-  , eventSubscribedRetained = toAny subscribed-#ifdef DEBUG_CYCLES-  , eventSubscribedGetParents = do-      innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed-      let outerParent = _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed-          innerParents = maybeToList $ innerSubscription-      return $ outerParent : innerParents-  , eventSubscribedHasOwnHeightRef = True-  , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed-#endif-  }--getEventSubscribedHeight :: EventSubscribed x -> IO Height-getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es--#ifdef DEBUG_CYCLES-whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]-whoCreatedEventSubscribed = eventSubscribedWhoCreated--walkInvalidHeightParents :: EventSubscribed x -> IO [EventSubscribed x]-walkInvalidHeightParents s0 = do-  subscribers <- flip execStateT mempty $ ($ s0) $ fix $ \loop s -> do-    h <- liftIO $ readIORef $ eventSubscribedHeightRef s-    when (h == invalidHeight) $ do-      when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed-      modify (s :)-      mapM_ loop =<< liftIO (eventSubscribedGetParents s)-  forM_ subscribers $ \s -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight-  return subscribers-#endif--{-# INLINE subscribeHoldEvent #-}-subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (EventSubscription x, Maybe p)-subscribeHoldEvent = subscribeAndRead . holdEvent------------------------------------------------------------------------------------- Behavior-----------------------------------------------------------------------------------newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }--behaviorHold :: Hold x p -> Behavior x (PatchTarget p)-behaviorHold !h = Behavior $ readHoldTracked h--behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a-behaviorHoldIdentity = behaviorHold--behaviorConst :: a -> Behavior x a-behaviorConst !a = Behavior $ return a--behaviorPull :: Pull x a -> Behavior x a-behaviorPull !p = Behavior $ do-    val <- liftIO $ readIORef $ pullValue p-    case val of-      Just subscribed -> do-        askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))-        askInvalidator >>= mapM_ (liftIO . addInvalidatorAmortized (pullSubscribedInvalidators subscribed))-        liftIO $ touch $ pullSubscribedOwnInvalidator subscribed-        return $ pullSubscribedValue subscribed-      Nothing -> do-        i <- liftIO $ newInvalidatorPull p-        wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"-        parentsRef <- liftIO $ newIORef []-        holdInits <- askBehaviorHoldInits-        a <- liftIO $ runReaderIO (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)-        inv0 <- maybeToList <$> askInvalidator-        invsRef <- liftIO $ newIORef $ InvalidatorList (length inv0) invalidatorPruneThreshold inv0-        parents <- liftIO $ readIORef parentsRef-        let subscribed = PullSubscribed-              { pullSubscribedValue = a-              , pullSubscribedInvalidators = invsRef-              , pullSubscribedOwnInvalidator = i-              , pullSubscribedParents = parents-              }-        liftIO $ writeIORef (pullValue p) $ Just subscribed-        askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedPull subscribed)) :))-        return a--behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)-behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d--{-# INLINE readHoldTracked #-}-readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)-readHoldTracked h = do-  result <- liftIO $ readIORef $ holdValue h-  askInvalidator >>= mapM_ (liftIO . addInvalidatorAmortized (holdInvalidators h))-  askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (Some (BehaviorSubscribedHold h)) :))-  liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected-  return result--data InvalidatorList x = InvalidatorList-  { invalidatorListSize :: !Int-  , invalidatorListPruneAt :: !Int-  , invalidatorListElems :: ![Weak (Invalidator x)]-  }--emptyInvalidatorList :: InvalidatorList x-emptyInvalidatorList = InvalidatorList-  { invalidatorListSize = 0-  , invalidatorListPruneAt = invalidatorPruneThreshold-  , invalidatorListElems = []-  }---- | Add invalidator weak ref to invalidator list, pruning finalized entries--- once the list grows to its "prune at" size.-{-# INLINE addInvalidatorAmortized #-}-addInvalidatorAmortized :: IORef (InvalidatorList x) -> Weak (Invalidator x) -> IO ()-addInvalidatorAmortized ref weakInvalidator = do-  InvalidatorList listSize pruneAt weakInvalidators <- readIORef ref-  if listSize < pruneAt-    then writeIORef ref $! InvalidatorList (listSize + 1) pruneAt (weakInvalidator : weakInvalidators)-    else do-      (liveCount, liveInvalidators) <--        foldrM-        (\weakInvalidator' (!liveCount, liveInvalidators) ->-            (\case Just _ -> (liveCount + 1, weakInvalidator' : liveInvalidators)-                   Nothing -> (liveCount, liveInvalidators))-            <$> deRefWeak weakInvalidator')-        (0, [])-        weakInvalidators-      writeIORef ref $! InvalidatorList-        (liveCount + 1)-        (max invalidatorPruneThreshold (2 * liveCount))-        (weakInvalidator : liveInvalidators)--invalidatorPruneThreshold :: Int-invalidatorPruneThreshold = 100--{-# INLINABLE readBehaviorUntracked #-}-readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a-readBehaviorUntracked b = do-  holdInits <- getDeferralQueue-  liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases------------------------------------------------------------------------------------- Dynamic-----------------------------------------------------------------------------------type DynamicS x p = Dynamic x (PatchTarget p) p--data Dynamic x target p = Dynamic-  { dynamicCurrent :: !(Behavior x target)-  , dynamicUpdated :: Event x p -- This must be lazy; see the comment on holdEvent --TODO: Would this let us eliminate `Dyn`?-  }--deriving instance (HasSpiderTimeline x) => Functor (Dynamic x target)-----dynamicHold :: Hold x p -> DynamicS x p-dynamicHold !h = Dynamic-  { dynamicCurrent = behaviorHold h-  , dynamicUpdated = eventHold h-  }--dynamicHoldIdentity :: Hold x (Identity a) -> DynamicS x (Identity a)-dynamicHoldIdentity = dynamicHold--dynamicConst :: PatchTarget p -> DynamicS x p-dynamicConst !a = Dynamic-  { dynamicCurrent = behaviorConst a-  , dynamicUpdated = eventNever-  }--dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p-dynamicDyn !d = Dynamic-  { dynamicCurrent = behaviorDyn d-  , dynamicUpdated = eventDyn d-  }--dynamicDynIdentity :: HasSpiderTimeline x => Dyn x (Identity a) -> DynamicS x (Identity a)-dynamicDynIdentity = dynamicDyn------------------------------------------------------------------------------------- Combinators-------------------------------------------------------------------------------------type role Hold representational-data Hold x p-   = Hold { holdValue :: !(IORef (PatchTarget p))-          , holdInvalidators :: !(IORef (InvalidatorList x))-          , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events-          , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef-#ifdef DEBUG_NODEIDS-          , holdNodeId :: Int-#endif-          }---- | A statically allocated 'SpiderTimeline'-data Global--{-# NOINLINE globalSpiderTimelineEnv #-}-globalSpiderTimelineEnv :: SpiderTimelineEnv Global-globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv---- | Stores all global data relevant to a particular Spider timeline; only one--- value should exist for each type @x@-newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}--- We implement SpiderTimelineEnv with a newtype wrapper so--- we can get the coercions we want safely.-type role SpiderTimelineEnv nominal--data SpiderTimelineEnv' x = SpiderTimelineEnv-  { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())-  , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)-#ifdef DEBUG-  , _spiderTimeline_depth :: {-# UNPACK #-} !(IORef Int)-#endif-  }-type role SpiderTimelineEnv' phantom--instance Eq (SpiderTimelineEnv x) where-  _ == _ = True -- Since only one exists of each type--instance GEq SpiderTimelineEnv where-  a `geq` b = if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)-              then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments-              else Nothing--data EventEnv x-   = EventEnv { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe-              , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe-              , eventEnvDynInits :: !(IORef [SomeDynInit x])-              , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])-              , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe-              , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe-              , eventEnvIntClears :: !(IORef [Some IntClear])-              , eventEnvRootClears :: !(IORef [Some RootClear])-              , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe-              , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe-              , eventEnvInvalidatedCoincidences :: !(IORef [SomeCoincidenceSubscribed x]) -- Coincidences whose height was set to 'invalidHeight' this frame and must be recalculated; populated by 'invalidateCoincidenceHeight'-              , eventEnvDelayedMerges :: !(IORef (IntMap [EventM x ()]))-              }--{-# INLINE runEventM #-}-runEventM :: EventM x a -> IO a-runEventM = unEventM--asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a-asksEventEnv f = return $ f $ _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))--class MonadIO m => Defer a m where-  getDeferralQueue :: m (IORef [a])--{-# INLINE defer #-}-defer :: Defer a m => a -> m ()-defer a = do-  q <- getDeferralQueue-  liftIO $ modifyIORef' q (a:)--instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvAssignments--instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvHoldInits--instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvDynInits--instance Defer (SomeHoldInit x) (BehaviorM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = BehaviorM $ asks snd--instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvMergeUpdates--instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvMergeInits--class HasSpiderTimeline x => HasCurrentHeight x m | m -> x where-  getCurrentHeight :: m Height-  scheduleMerge :: Height -> EventM x () -> m ()--instance HasSpiderTimeline x => HasCurrentHeight x (EventM x) where-  {-# INLINE getCurrentHeight #-}-  getCurrentHeight = do-    heightRef <- asksEventEnv eventEnvCurrentHeight-    liftIO $ readIORef heightRef-  {-# INLINE scheduleMerge #-}-  scheduleMerge height subscribed = do-    delayedRef <- asksEventEnv eventEnvDelayedMerges-    liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [subscribed]--class HasSpiderTimeline x where-  -- | Retrieve the current SpiderTimelineEnv-  spiderTimeline :: SpiderTimelineEnv x--instance HasSpiderTimeline Global where-  spiderTimeline = globalSpiderTimelineEnv--putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()-putCurrentHeight h = do-  heightRef <- asksEventEnv eventEnvCurrentHeight-  liftIO $ writeIORef heightRef $! h--instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvClears--{-# INLINE scheduleClear #-}-scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()-scheduleClear r = defer $ Some $ Clear r--instance HasSpiderTimeline x => Defer (Some IntClear) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvIntClears--{-# INLINE scheduleIntClear #-}-scheduleIntClear :: Defer (Some IntClear) m => IORef (IntMap a) -> m ()-scheduleIntClear r = defer $ Some $ IntClear r--instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvRootClears--{-# INLINE scheduleRootClear #-}-scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()-scheduleRootClear r = defer $ Some $ RootClear r--instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where-  {-# INLINE getDeferralQueue #-}-  getDeferralQueue = asksEventEnv eventEnvResetCoincidences---- Note: hold cannot examine its event until after the phase is over-{-# INLINE [1] hold #-}-hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)-hold v0 e = do-  valRef <- liftIO $ newIORef v0-  invsRef <- liftIO $ newIORef emptyInvalidatorList-  parentRef <- liftIO $ newIORef Nothing-#ifdef DEBUG_NODEIDS-  nodeId <- liftIO newNodeId-#endif-  let h = Hold-        { holdValue = valRef-        , holdInvalidators = invsRef-        , holdEvent = e-        , holdParent = parentRef-#ifdef DEBUG_NODEIDS-        , holdNodeId = nodeId-#endif-        }-  defer $ SomeHoldInit h-  return h--{-# INLINE getHoldEventSubscription #-}-getHoldEventSubscription :: forall p x. (HasSpiderTimeline x, Patch p) => Hold x p -> EventM x (EventSubscription x)-getHoldEventSubscription h = do-  ep <- liftIO $ readIORef $ holdParent h-  case ep of-    Just subd -> return subd-    Nothing -> do-      let e = holdEvent h-      subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"-      (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)-      liftIO $ writeIORef subscriptionRef $! subscription-      case occ of-        Nothing -> return ()-        Just o -> do-          old <- liftIO $ readIORef $ holdValue h-          case apply o old of-            Nothing -> return ()-            Just new -> do-              -- Need to evaluate these so that we don't retain the Hold itself-              v <- liftIO $ evaluate $ holdValue h-              i <- liftIO $ evaluate $ holdInvalidators h-              defer $ SomeAssignment v i new-      liftIO $ writeIORef (holdParent h) $ Just subscription-      return subscription--type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])---- BehaviorM can sample behaviors-newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderIO (BehaviorEnv x) a }-  deriving (Functor, Applicative, MonadIO, MonadFix, MonadReader (BehaviorEnv x))--instance Monad (BehaviorM x) where-  {-# INLINE (>>=) #-}-  BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f-#if !MIN_VERSION_base(4,13,0)-  {-# INLINE fail #-}-  fail s = BehaviorM $ fail s-#endif--data BehaviorSubscribed x a-   = forall p. BehaviorSubscribedHold (Hold x p)-   | BehaviorSubscribedPull (PullSubscribed x a)--newtype SomeBehaviorSubscribed x = SomeBehaviorSubscribed (Some (BehaviorSubscribed x))----type role PullSubscribed representational-data PullSubscribed x a-   = PullSubscribed { pullSubscribedValue :: !a-                    , pullSubscribedInvalidators :: !(IORef (InvalidatorList x))-                    , pullSubscribedOwnInvalidator :: !(Invalidator x)-                    , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated-                    }----type role Pull representational-data Pull x a-   = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))-          , pullCompute :: !(BehaviorM x a)-#ifdef DEBUG_NODEIDS-          , pullNodeId :: Int-#endif-          }--data Invalidator x-   = forall a. InvalidatorPull (Pull x a)-   | forall a. InvalidatorSwitch (SwitchSubscribed x a)--data RootSubscribed x a = forall k. GCompare k => RootSubscribed-  { rootSubscribedKey :: !(k a)-  , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root-  , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))-  , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence-  , rootSubscribedUninit :: IO ()-  , rootSubscribedWeakSelf :: !(IORef (Weak (RootSubscribed x a))) --TODO: Can we make this a lazy non-IORef and then force it manually to avoid an indirection each time we use it?-#ifdef DEBUG_NODEIDS-  , rootSubscribedNodeId :: Int-#endif-  }--data Root x k-   = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event-          , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))-          , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))-          }--data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)--data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)--data SomeMergeUpdate x = SomeMergeUpdate-  { _someMergeUpdate_update :: !(EventM x [EventSubscription x])-  , _someMergeUpdate_invalidateHeight :: !(IO ())-  , _someMergeUpdate_recalculateHeight :: !(IO ())-  }--newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }---- EventM can do everything BehaviorM can, plus create holds-newtype EventM x a = EventM { unEventM :: IO a }-  deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException, MonadCatch, MonadThrow, MonadMask)--newtype MergeSubscribedParent x a = MergeSubscribedParent { unMergeSubscribedParent :: EventSubscription x }--data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove-  { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)-  , _mergeSubscribedParentWithMove_key :: !(IORef (k a))-  }--data HeightBag = HeightBag-  { _heightBag_size :: {-# UNPACK #-} !Int-  , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket-  }-  deriving (Show, Read, Eq, Ord)--heightBagEmpty :: HeightBag-heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty--heightBagSize :: HeightBag -> Int-heightBagSize = _heightBag_size--heightBagFromList :: [Height] -> HeightBag-heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights--heightBagAdd :: Height -> HeightBag -> HeightBag-heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $-  IntMap.insertWithKey (\_ _ old -> succ old) h 0 c--heightBagRemove :: Height -> HeightBag -> HeightBag-heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of-  Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b-  Just old -> HeightBag (pred s) $ case old of-    0 -> IntMap.delete h c-    _ -> IntMap.insert h (pred old) c--heightBagRemoveMaybe :: Height -> HeightBag -> Maybe HeightBag-heightBagRemoveMaybe (Height h) (HeightBag s c) = heightBagVerify . removed <$> IntMap.lookup h c where-  removed old = HeightBag (pred s) $ case old of-    0 -> IntMap.delete h c-    _ -> IntMap.insert h (pred old) c---heightBagMax :: HeightBag -> Height-heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of-  Just ((h, _), _) -> Height h-  Nothing -> zeroHeight--heightBagVerify :: HeightBag -> HeightBag-#ifdef DEBUG-heightBagVerify b@(HeightBag s c) = if-  | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))-    -> error $ "heightBagVerify: size doesn't match: " <> show b-  | unHeight invalidHeight `IntMap.member` c-    -> error $ "heightBagVerify: contains invalid height: " <> show b-  | otherwise -> b-#else-heightBagVerify = id-#endif--data FanSubscribedChildren x k v a = FanSubscribedChildren-  { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x (v a)))-  , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k v)-  , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k v)))-  }--data FanSubscribed x k v-   = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))-                   , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k v)))-                   , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k v))) -- This DMap should never be empty-                   , fanSubscribedParent :: !(EventSubscription x)-#ifdef DEBUG_NODEIDS-                   , fanSubscribedNodeId :: Int-#endif-                   }--data Fan x k v-   = Fan { fanParent :: !(Event x (DMap k v))-         , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k v)))-         }--data SwitchSubscribed x a-   = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))-                      , switchSubscribedOccurrence :: !(IORef (Maybe a))-                      , switchSubscribedHeight :: !(IORef Height)-                      , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))-                      , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)-                      , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))-                      , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])-                      , switchSubscribedParent :: !(Behavior x (Event x a))-                      , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))-                      , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))-#ifdef DEBUG_NODEIDS-                      , switchSubscribedNodeId :: Int-#endif-                      }--data Switch x a-   = Switch { switchParent :: !(Behavior x (Event x a))-            , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))-            }--{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}-data CoincidenceSubscribed x a-   = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))-                           , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))-                           , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))-                           , coincidenceSubscribedHeight :: !(IORef Height)-                           , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))-                           , coincidenceSubscribedOuterParent :: !(EventSubscription x)-                           , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))-                           , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))-#ifdef DEBUG_NODEIDS-                           , coincidenceSubscribedNodeId :: Int-#endif-                           }--data Coincidence x a-   = Coincidence { coincidenceParent :: !(Event x (Event x a))-                 , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))-                 }--{-# NOINLINE newInvalidatorSwitch #-}-newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)-newInvalidatorSwitch subd = return $! InvalidatorSwitch subd--{-# NOINLINE newInvalidatorPull #-}-newInvalidatorPull :: Pull x a -> IO (Invalidator x)-newInvalidatorPull p = return $! InvalidatorPull p--instance HasSpiderTimeline x => Filterable (Event x) where-  mapMaybe f = push $ return . f--instance HasSpiderTimeline x => Align (Event x) where-  nil = eventNever-#if MIN_VERSION_these(0, 8, 0)-instance HasSpiderTimeline x => Semialign (Event x) where-#endif-  align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $-     DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]--#ifdef MIN_VERSION_semialign-#if MIN_VERSION_semialign(1,1,0)-instance HasSpiderTimeline x => Zip (Event x) where-#endif-  zip x y = mapMaybe justThese $ align x y-#endif--data DynType x p = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)-                 | BuildDyn  !(EventM x (PatchTarget p), Event x p)-                 | HoldDyn   !(Hold x p)--newtype Dyn (x :: Type) p = Dyn { unDyn :: IORef (DynType x p) }--newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)-newMapDyn f d = dynamicDynIdentity $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)----TODO: Avoid the duplication between this and R.zipDynWith-zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)-zipDynWith f da db =-  let eab = align (dynamicUpdated da) (dynamicUpdated db)-      ec = flip push eab $ \o -> do-        (a, b) <- case o of-          This (Identity a) -> do-            b <- readBehaviorUntracked $ dynamicCurrent db-            return (a, b)-          That (Identity b) -> do-            a <- readBehaviorUntracked $ dynamicCurrent da-            return (a, b)-          These (Identity a) (Identity b) -> return (a, b)-        return $ Just $ Identity $ f a b-  in dynamicDynIdentity $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec--buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)-buildDynamic readV0 v' = do-  result <- liftIO $ newIORef $ BuildDyn (readV0, v')-  let !d = Dyn result-  defer $ SomeDynInit d-  return d--unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p-unsafeBuildDynamic readV0 v' =-  Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')---- ResultM can read behaviors and events-type ResultM = EventM--instance HasSpiderTimeline x => Functor (Event x) where-  fmap f = push $ return . Just . f--instance Functor (Behavior x) where-  fmap f = pull . fmap f . readBehaviorTracked--{-# INLINE push #-}-push :: HasSpiderTimeline x => (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b-push f e = cacheEvent (pushCheap f e)--{-# INLINABLE pull #-}-pull :: BehaviorM x a -> Behavior x a-pull a = unsafePerformIO $ do-  ref <- newIORef Nothing-#ifdef DEBUG_NODEIDS-  nid <- newNodeId-#endif-  pure $ behaviorPull $ Pull-    { pullCompute = a-    , pullValue = ref-#ifdef DEBUG_NODEIDS-    , pullNodeId = nid-#endif-    }--{-# INLINABLE switch #-}-switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a-switch a = unsafePerformIO $ do-  ref <- newIORef Nothing-  pure $ eventSwitch $ Switch-    { switchParent = a-    , switchSubscribed = ref-    }--coincidence :: HasSpiderTimeline x => Event x (Event x a) -> Event x a-coincidence a = unsafePerformIO $ do-  ref <- newIORef Nothing-  pure $ eventCoincidence $ Coincidence-    { coincidenceParent = a-    , coincidenceSubscribed = ref-    }---- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors-run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b-run roots after = do-  tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"-  let t = spiderTimeline :: SpiderTimelineEnv x-  result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do-    rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do-      occBefore <- liftIO $ do-        occBefore <- readIORef occRef-        writeIORef occRef $! DMap.insert k a occBefore-        return occBefore-      if DMap.null occBefore-        then do scheduleRootClear occRef-                return $ Just r-        else return Nothing-    forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do-      propagate a subscribersRef-    delayedRef <- asksEventEnv eventEnvDelayedMerges-    let go = do-          delayed <- liftIO $ readIORef delayedRef-          case IntMap.minViewWithKey delayed of-            Nothing -> return ()-            Just ((currentHeight, cur), future) -> do-              tracePropagate (Proxy :: Proxy x) $ "Running height " ++ show currentHeight-              putCurrentHeight $ Height currentHeight-              liftIO $ writeIORef delayedRef $! future-              sequence_ cur-              go-    go-    putCurrentHeight maxBound-    after-  tracePropagate (Proxy :: Proxy x) "Done running an event frame"-  return result--scheduleMerge' :: HasSpiderTimeline x => Height -> IORef Height -> EventM x () -> EventM x ()-scheduleMerge' initialHeight heightRef a = scheduleMerge initialHeight $ do-  height <- liftIO $ readIORef heightRef-  currentHeight <- getCurrentHeight-  case height `compare` currentHeight of-    LT -> error "Somehow a merge's height has been decreased after it was scheduled"-    GT -> scheduleMerge' height heightRef a -- The height has been increased (by a coincidence event; TODO: is this the only way?)-    EQ -> a--newtype Clear a = Clear (IORef (Maybe a))--newtype IntClear a = IntClear (IORef (IntMap a))--newtype RootClear k = RootClear (IORef (DMap k Identity))--data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef (InvalidatorList x)) a--debugFinalize :: Bool-debugFinalize = False--mkWeakPtrWithDebug :: a -> String -> IO (Weak a)-mkWeakPtrWithDebug x debugNote = do-  x' <- evaluate x-  mkWeakPtr x' $-    if debugFinalize-    then Just $ debugStrLn $ "finalizing: " ++ debugNote-    else Nothing--type CanTrace x m = (HasSpiderTimeline x, MonadIO m)-----#ifdef DEBUG--debugSubscriber :: forall x a. HasSpiderTimeline x => String -> Subscriber x a -> IO (Subscriber x a)-debugSubscriber description = return . debugSubscriber' description--debugSubscriber' :: forall x a. HasSpiderTimeline x => String -> Subscriber x a -> Subscriber x a-debugSubscriber' description subscribed = Subscriber-  {-    subscriberPropagate = \m -> do-      tracePropagate (Proxy :: Proxy x) ("subscriberPropagate: " <> description)-      subscriberPropagate subscribed m-  , subscriberInvalidateHeight = \old -> do-      traceInvalidateHeight $ "invalidateSubscriberHeight: " <> description <> ", old = " <> show (unHeight old)-      subscriberInvalidateHeight subscribed old-      traceInvalidateHeight $ "invalidateSubscriberHeight: " <> description <> ", done"-  , subscriberRecalculateHeight = \new -> do-      traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", new = " <> show (unHeight new)-      subscriberRecalculateHeight subscribed new-      traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", done"-  }---{-# INLINE withIncreasedDepth #-}-withIncreasedDepth :: forall proxy x m a. CanTrace x m => proxy x -> m a -> m a-withIncreasedDepth _ a = do-  liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) succ-  result <- a-  liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) pred-  return result--{-# INLINE tracePropagate #-}-tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()-tracePropagate p = when debugPropagate . trace p--{-# INLINE traceInvalidate #-}-traceInvalidate :: String -> IO ()-traceInvalidate = when debugInvalidate . liftIO . debugStrLn--{-# INLINE traceInvalidateHeight #-}-traceInvalidateHeight :: String -> IO ()-traceInvalidateHeight = when debugInvalidateHeight . liftIO . debugStrLn--{-# INLINE trace #-}-trace :: (CanTrace x m) => proxy x ->  String -> m ()-trace p message = traceM p $ return message--{-# INLINE traceM #-}-traceM :: forall x proxy m. (CanTrace x m) => proxy x -> m String -> m ()-traceM _ getMessage = do-  message <- getMessage-  d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)-  liftIO $ debugStrLn $ replicate d ' ' <> message--#else--{-# INLINE withIncreasedDepth #-}-withIncreasedDepth ::  proxy x -> m a -> m a-withIncreasedDepth _ = id--{-# INLINE tracePropagate #-}-tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()-tracePropagate _ _ = return ()--{-# INLINE traceInvalidate #-}-traceInvalidate :: String -> IO ()-traceInvalidate _ = return ()--{-# INLINE traceInvalidateHeight #-}-traceInvalidateHeight :: String -> IO ()-traceInvalidateHeight _ = return ()--{-# INLINE debugSubscriber #-}-debugSubscriber :: String -> Subscriber x a -> IO (Subscriber x a)-debugSubscriber _ = return--{-# INLINE debugSubscriber' #-}-debugSubscriber' :: String -> Subscriber x a -> Subscriber x a-debugSubscriber' _ = id----{-# INLINE trace #-}-trace :: (CanTrace x m) => proxy x ->  String -> m ()-trace _ _ = return ()--{-# INLINE traceM #-}-traceM :: (CanTrace x m) => proxy x -> m String -> m ()-traceM _ _ = return ()--#endif--whoCreatedIORef :: IORef a -> IO [String]-whoCreatedIORef (IORef a) = whoCreated $! a--groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]-groupByHead = \case-  [] -> []-  (x :| xs) : t -> case groupByHead t of-    [] -> [(x, xs :| [])]-    l@((y, yss) : t')-      | x == y -> (x, xs `NonEmpty.cons` yss) : t'-      | otherwise -> (x, xs :| []) : l--listsToForest :: Eq a => [[a]] -> Forest a-listsToForest lists = buildForest <$> groupByHead (mapMaybe nonEmpty lists)-    where buildForest (a, lists') = Node a $ listsToForest $ toList lists'--showStacks :: [[String]] -> String-showStacks = drawForest . listsToForest . fmap (filterStack "Reflex.Spider.Internal")--filterStack :: String -> [String] -> [String]-#ifdef DEBUG_HIDE_INTERNALS-filterStack prefix = filter (not . (prefix `isPrefixOf`))-#else-filterStack _prefix = id-#endif--#ifdef DEBUG_CYCLES--data EventLoopException = EventLoopException [[String]]-instance Exception EventLoopException--instance Show EventLoopException where-  show (EventLoopException stacks) = "causality loop detected:\n" <> if null stacks-    then "no location information, compile with profiling enabled for stack tree"-    else showStacks stacks--#else--data EventLoopException = EventLoopException-instance Exception EventLoopException--instance Show EventLoopException where-  show EventLoopException = "causality loop detected: \n" <>-    "compile reflex with flag 'debug-cycles' and compile with profiling enabled for stack tree"--#endif---{-# INLINE propagateSubscriberHold #-}-propagateSubscriberHold :: forall x p. (HasSpiderTimeline x, Patch p) => Hold x p -> p -> EventM x ()-propagateSubscriberHold h a = do-  {-# SCC "trace" #-} when debugPropagate $ traceM (Proxy :: Proxy x) $ liftIO $ do-    InvalidatorList n _ _ <- liftIO $ readIORef $ holdInvalidators h-    return $ "SubscriberHold" <> showNodeId h <> ": " ++ show n--  v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h-  case {-# SCC "apply" #-} apply a v of-    Nothing -> return ()-    Just v' -> do-      {-# SCC "trace2" #-} withIncreasedDepth (Proxy :: Proxy x) $-        tracePropagate (Proxy :: Proxy x) ("propagateSubscriberHold: assigning Hold" <> showNodeId h)-      vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h-      iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h-      defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'---- | 'CoincidenceSubscribed' is present only when the coincidence raised its height while subscribing to the inner event.-data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a))-data SomeCoincidenceSubscribed x = forall a. SomeCoincidenceSubscribed !(CoincidenceSubscribed x a)--runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a-runBehaviorM a mwi holdInits = runReaderIO (unBehaviorM a) (mwi, holdInits)--askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))-askInvalidator = do-  (!m, _) <- ask-  case m of-    Nothing -> return Nothing-    Just (!wi, _) -> return $ Just wi--askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))-askParentsRef = do-  (!m, _) <- ask-  case m of-    Nothing -> return Nothing-    Just (_, !p) -> return $ Just p--askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])-askBehaviorHoldInits = do-  (_, !his) <- ask-  return his--{-# INLINE getDynHold #-}-getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)-getDynHold d = do-  mh <- liftIO $ readIORef $ unDyn d-  case mh of-    HoldDyn h -> return h-    UnsafeDyn (readV0, v') -> do-      holdInits <- getDeferralQueue-      v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits-      hold' v0 v'-    BuildDyn (readV0, v') -> do-      v0 <- liftIO $ runEventM readV0-      hold' v0 v'-  where-    hold' v0 v' = do-      h <- hold v0 v'-      liftIO $ writeIORef (unDyn d) $ HoldDyn h-      return h----- Always refers to 0-{-# NOINLINE zeroRef #-}-zeroRef :: IORef Height-zeroRef = unsafePerformIO $ newIORef zeroHeight--getRootSubscribed :: forall k x a. (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)-getRootSubscribed k r sub = do-  mSubscribed <- readIORef $ rootSubscribed r-  let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r-  case DMap.lookup k mSubscribed of-    Just subscribed -> {-# SCC "hitRoot" #-} do-      sln <- subscribeRootSubscribed subscribed sub-      occ <- getOcc-      return (sln, subscribed, occ)-    Nothing -> {-# SCC "missRoot" #-} do-      weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"-      let !cached = rootSubscribed r-      uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"-      (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed--      tracePropagate (Proxy::Proxy x) $  "getRootSubscribed: calling rootInit"--      uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)-      writeIORef uninitRef $! uninit-#ifdef DEBUG_NODEIDS-      nid <- newNodeId-#endif-      let !subscribed = RootSubscribed-            { rootSubscribedKey = k-            , rootSubscribedCachedSubscribed = cached-            , rootSubscribedOccurrence = getOcc-            , rootSubscribedSubscribers = subs-            , rootSubscribedUninit = uninit-            , rootSubscribedWeakSelf = weakSelf-#ifdef DEBUG_NODEIDS-            , rootSubscribedNodeId = nid-#endif-            }-          -- If we die at the same moment that all our children die, they will-          -- try to clean us up but will fail because their Weak reference to us-          -- will also be dead.  So, if we are dying, check if there are any-          -- children; since children don't bother cleaning themselves up if-          -- their parents are already dead, I don't think there's a race-          -- condition here.  However, if there are any children, then we can-          -- infer that we need to clean ourselves up, so we do.-          finalCleanup = do-            cs <- readIORef $ _weakBag_children subs-            when (not $ IntMap.null cs) (cleanupRootSubscribed subscribed)-      writeIORef weakSelf =<< evaluate =<< mkWeakPtr subscribed (Just finalCleanup)-      modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it-      occ <- getOcc-      return (sln, subscribed, occ)--{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}-cleanupRootSubscribed :: RootSubscribed x a -> IO ()-cleanupRootSubscribed self@RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached } = do-  rootSubscribedUninit self-  modifyIORef' cached $ DMap.delete k--{-# INLINE subscribeRootSubscribed #-}-subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket-subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed--newtype EventSelectorInt x a = EventSelectorInt { selectInt :: Int -> Event x a }--data FanInt x a = FanInt-  { _fanInt_subscribers :: {-# UNPACK #-} !(FastMutableIntMap (FastWeakBag (Subscriber x a))) --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty-  , _fanInt_subscriptionRef :: {-# UNPACK #-} !(IORef (EventSubscription x)) -- This should have a valid subscription iff subscribers is non-empty-  , _fanInt_occRef :: {-# UNPACK #-} !(IORef (IntMap a))-#ifdef DEBUG_NODEIDS-  , _fanInt_nodeId :: {-# UNPACK #-} !Int-#endif-  }--newFanInt :: IO (FanInt x a)-newFanInt = do-  subscribers <- FastMutableIntMap.newEmpty --TODO: Clean up the keys in here when their child weak bags get empty --TODO: Remove our own subscription when the subscribers list is completely empty-  subscriptionRef <- newIORef $ error "fanInt: no subscription"-  occRef <- newIORef $ error "fanInt: no occurrence"-#ifdef DEBUG_NODEIDS-  nodeId <- newNodeId-#endif-  return $ FanInt-    { _fanInt_subscribers = subscribers-    , _fanInt_subscriptionRef = subscriptionRef-    , _fanInt_occRef = occRef-#ifdef DEBUG_NODEIDS-    , _fanInt_nodeId = nodeId-#endif-    }--fanInt :: HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a-fanInt p = unsafePerformIO $ do-  self <- newFanInt-  pure $ EventSelectorInt $ \k -> Event $ \sub -> do-    isEmpty <- liftIO $ FastMutableIntMap.isEmpty (_fanInt_subscribers self)-    when isEmpty $ do -- This is the first subscriber, so we need to subscribe to our input-      let desc = "fanInt" <> showNodeId self <> ", k = "  <> show k-      (subscription, parentOcc) <- subscribeAndRead p $ debugSubscriber' desc $ Subscriber-        { subscriberPropagate = \m -> do-            liftIO $ writeIORef (_fanInt_occRef self) m-            scheduleIntClear $ _fanInt_occRef self-            FastMutableIntMap.forIntersectionWithImmutable_ (_fanInt_subscribers self) m $ \b v ->  --TODO: Do we need to know that no subscribers are being added as we traverse?-              FastWeakBag.traverse_ b $ \s ->-                subscriberPropagate s v-        , subscriberInvalidateHeight = \old ->-            FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b ->-              FastWeakBag.traverse_ b $ \s ->-                subscriberInvalidateHeight s old-        , subscriberRecalculateHeight = \new ->-            FastMutableIntMap.for_ (_fanInt_subscribers self) $ \b ->-              FastWeakBag.traverse_ b $ \s ->-                subscriberRecalculateHeight s new-        }-      liftIO $ do-        writeIORef (_fanInt_subscriptionRef self) subscription-        writeIORef (_fanInt_occRef self) $ fromMaybe IntMap.empty parentOcc-      scheduleIntClear $ _fanInt_occRef self-    liftIO $ do-      b <- FastMutableIntMap.lookup (_fanInt_subscribers self) k >>= \case-        Nothing -> do-          b <- FastWeakBag.empty-          FastMutableIntMap.insert (_fanInt_subscribers self) k b-          return b-        Just b -> return b-      ticket <- liftIO $ FastWeakBag.insert sub b-      currentOcc <- readIORef (_fanInt_occRef self)--      subscribed <- fanIntSubscribed ticket self-      return (EventSubscription (FastWeakBag.remove ticket) subscribed, IntMap.lookup k currentOcc)--fanIntSubscribed :: FastWeakBagTicket k -> FanInt x a -> IO (EventSubscribed x)-fanIntSubscribed ticket self = do-  subscribedParent <- _eventSubscription_subscribed <$> readIORef (_fanInt_subscriptionRef self)-  return $ EventSubscribed-    { eventSubscribedHeightRef = eventSubscribedHeightRef subscribedParent-    , eventSubscribedRetained = toAny (_fanInt_subscriptionRef self, ticket)-#ifdef DEBUG_CYCLES-    , eventSubscribedGetParents = return [subscribedParent]-    , eventSubscribedHasOwnHeightRef = False-    , eventSubscribedWhoCreated = whoCreatedIORef $ _fanInt_subscriptionRef self-#endif-    }---{-# INLINABLE getFanSubscribed #-}-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))-getFanSubscribed k f sub = do-  mSubscribed <- liftIO $ readIORef $ fanSubscribed f-  case mSubscribed of-    Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do-      sln <- subscribeFanSubscribed k subscribed sub-      occ <- readIORef $ fanSubscribedOccurrence subscribed-      return (sln, subscribed, coerce $ DMap.lookup k =<< occ)-    Nothing -> {-# SCC "missFan" #-} do-      subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"-      subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef-      s <- liftIO $ newSubscriberFan subscribedUnsafe-      (subscription, parentOcc) <- subscribeAndRead (fanParent f) s-      weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"-      (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed-      subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"-      occRef <- liftIO $ newIORef parentOcc-      when (isJust parentOcc) $ scheduleClear occRef-#ifdef DEBUG_NODEIDS-      nid <- liftIO newNodeId-#endif-      let subscribed = FanSubscribed-            { fanSubscribedCachedSubscribed = fanSubscribed f-            , fanSubscribedOccurrence = occRef-            , fanSubscribedParent = subscription-            , fanSubscribedSubscribers = subscribersRef-#ifdef DEBUG_NODEIDS-            , fanSubscribedNodeId = nid-#endif-            }-      let !self = (k, subscribed)-      liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf-      liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"-      liftIO $ writeIORef subscribedRef $! subscribed-      liftIO $ writeIORef (fanSubscribed f) $ Just subscribed-      return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)--cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k v) -> IO ()-cleanupFanSubscribed (k, subscribed) = do-  subscribers <- readIORef $ fanSubscribedSubscribers subscribed-  let reducedSubscribers = DMap.delete k subscribers-  if DMap.null reducedSubscribers-    then do-      unsubscribe $ fanSubscribedParent subscribed-      -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers-      writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing-    else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers--{-# INLINE subscribeFanSubscribed #-}-subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k v -> Subscriber x (v a) -> IO WeakBagTicket-subscribeFanSubscribed k subscribed sub = do-  subscribers <- readIORef $ fanSubscribedSubscribers subscribed-  case DMap.lookup k subscribers of-    Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do-      let !self = (k, subscribed)-      weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"-      (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed-      writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers-      return sln-    Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed--{-# INLINABLE getSwitchSubscribed #-}-getSwitchSubscribed :: HasSpiderTimeline x => Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a)-getSwitchSubscribed s sub = do-  mSubscribed <- liftIO $ readIORef $ switchSubscribed s-  case mSubscribed of-    Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do-      sln <- subscribeSwitchSubscribed subscribed sub-      occ <- readIORef $ switchSubscribedOccurrence subscribed-      return (sln, subscribed, occ)-    Nothing -> {-# SCC "missSwitch" #-} do-      subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"-      subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef-      i <- liftIO $ newInvalidatorSwitch subscribedUnsafe-      mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe-      wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"-      wiRef <- liftIO $ newIORef wi-      parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior-      holdInits <- getDeferralQueue-      e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits-      (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub-      heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd-      subscriptionRef <- liftIO $ newIORef subscription-      occRef <- liftIO $ newIORef parentOcc-      when (isJust parentOcc) $ scheduleClear occRef-      weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"-      (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed-#ifdef DEBUG_NODEIDS-      nid <- liftIO newNodeId-#endif-      let !subscribed = SwitchSubscribed-            { switchSubscribedCachedSubscribed = switchSubscribed s-            , switchSubscribedOccurrence = occRef-            , switchSubscribedHeight = heightRef-            , switchSubscribedSubscribers = subs-            , switchSubscribedOwnInvalidator = i-            , switchSubscribedOwnWeakInvalidator = wiRef-            , switchSubscribedBehaviorParents = parentsRef-            , switchSubscribedParent = switchParent s-            , switchSubscribedCurrentParent = subscriptionRef-            , switchSubscribedWeakSelf = weakSelf-#ifdef DEBUG_NODEIDS-            , switchSubscribedNodeId = nid-#endif-            }-      liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"-      liftIO $ writeIORef subscribedRef $! subscribed-      liftIO $ writeIORef (switchSubscribed s) $ Just subscribed-      return (slnForSub, subscribed, parentOcc)--cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()-cleanupSwitchSubscribed subscribed = do-  unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)-  finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead-  writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing--{-# INLINE subscribeSwitchSubscribed #-}-subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket-subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed--{-# INLINABLE getCoincidenceSubscribed #-}-getCoincidenceSubscribed :: forall x a. HasSpiderTimeline x => Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)-getCoincidenceSubscribed c sub = do-  mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c-  case mSubscribed of-    Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do-      sln <- subscribeCoincidenceSubscribed subscribed sub-      occ <- readIORef $ coincidenceSubscribedOccurrence subscribed-      return (sln, subscribed, occ)-    Nothing -> {-# SCC "missCoincidence" #-} do-      subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"-      subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef-      subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe-      (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter-      outerHeight <- liftIO $ getEventSubscribedHeight outerSubd-      (occ, height, mInnerSubd) <- case outerOcc of-        Nothing -> return (Nothing, outerHeight, Nothing)-        Just o -> do-          (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe-          return (occ, height, Just innerSubd)-      occRef <- liftIO $ newIORef occ-      when (isJust occ) $ scheduleClear occRef-      heightRef <- liftIO $ newIORef height-      innerSubdRef <- liftIO $ newIORef mInnerSubd-      scheduleClear innerSubdRef-      weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"-      (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed-#ifdef DEBUG_NODEIDS-      nid <- liftIO newNodeId-#endif-      let subscribed = CoincidenceSubscribed-            { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c-            , coincidenceSubscribedOccurrence = occRef-            , coincidenceSubscribedHeight = heightRef-            , coincidenceSubscribedSubscribers = subs-            , coincidenceSubscribedOuter = subOuter-            , coincidenceSubscribedOuterParent = outerSubscription-            , coincidenceSubscribedInnerParent = innerSubdRef-            , coincidenceSubscribedWeakSelf = weakSelf-#ifdef DEBUG_NODEIDS-            , coincidenceSubscribedNodeId = nid-#endif-            }-      liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"-      liftIO $ writeIORef subscribedRef $! subscribed-      liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed-      return (slnForSub, subscribed, occ)--cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()-cleanupCoincidenceSubscribed subscribed = do-  unsubscribe $ coincidenceSubscribedOuterParent subscribed-  writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing--{-# INLINE subscribeCoincidenceSubscribed #-}-subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket-subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed--{-# INLINE mergeG #-}-mergeG :: forall k q x v. (HasSpiderTimeline x, GCompare k)-  => (forall a. q a -> Event x (v a))-  -> DynamicS x (PatchDMap k q) -> Event x (DMap k v)-mergeG nt d = cacheEvent (mergeCheap nt d)--{-# INLINE mergeWithMove #-}-mergeWithMove :: forall k v q x. (HasSpiderTimeline x, GCompare k)-  => (forall a. q a -> Event x (v a))-  -> DynamicS x (PatchDMapWithMove k q) -> Event x (DMap k v)-mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)--{-# INLINE [1] mergeCheap #-}-mergeCheap-  :: forall k x q v. (HasSpiderTimeline x, GCompare k)-  => (forall a. q a -> Event x (v a))-  -> DynamicS x (PatchDMap k q)-  -> Event x (DMap k v)-mergeCheap nt = mergeGCheap' unMergeSubscribedParent getInitialSubscribers updateMe destroy-  where-      updateMe :: MergeUpdateFunc k v x (PatchDMap k q) (MergeSubscribedParent x)-      updateMe subscriber heightBagRef oldParents (PatchDMap p) = do-        let f (subscriptionsToKill, ps) (k :=> ComposeMaybe me) = do-              (mOldSubd, newPs) <- case me of-                Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps-                Just e -> do-                  let s = subscriber $ return k-                  subscription@(EventSubscription _ subd) <- subscribe (nt e) s-                  newParentHeight <- liftIO $ getEventSubscribedHeight subd-                  let newParent = MergeSubscribedParent subscription-                  liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight-                  return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps-              forM_ mOldSubd $ \oldSubd -> do-                oldHeight <- liftIO $ getEventSubscribedHeight $-                  _eventSubscription_subscribed $ unMergeSubscribedParent oldSubd--                liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight-              return (maybeToList (unMergeSubscribedParent <$> mOldSubd) ++ subscriptionsToKill, newPs)-        foldM f ([], oldParents) $ DMap.toList p--      getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParent x)-      getInitialSubscribers initialParents subscriber = do-        subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do-          let s = subscriber $ return k-          (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s-          height <- liftIO $ getEventSubscribedHeight parentSubd-          return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParent subscription)-        return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers-               , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here-               , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers-               )--      destroy :: MergeDestroyFunc k (MergeSubscribedParent x)-      destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParent sub) -> unsubscribe sub--{-# INLINE [1] mergeCheapWithMove #-}-mergeCheapWithMove :: forall k x v q. (HasSpiderTimeline x, GCompare k)-  => (forall a. q a -> Event x (v a))-  -> DynamicS x (PatchDMapWithMove k q)-  -> Event x (DMap k v)-mergeCheapWithMove nt = mergeGCheap' _mergeSubscribedParentWithMove_subscription getInitialSubscribers updateMe destroy-  where-      updateMe :: MergeUpdateFunc k v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)-      updateMe subscriber heightBagRef oldParents p = do-        -- Prepare new parents for insertion-        let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)-            subscribeParent k e = do-              keyRef <- liftIO $ newIORef k-              let s = subscriber $ liftIO $ readIORef keyRef-              subscription@(EventSubscription _ subd) <- subscribe e s-              liftIO $ do-                newParentHeight <- getEventSubscribedHeight subd-                modifyIORef' heightBagRef $ heightBagAdd newParentHeight-                return $ MergeSubscribedParentWithMove subscription keyRef-        p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p-        -- Collect old parents for deletion and update the keys of moved parents-        let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a-            moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of-              Nothing -> do-                oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $-                  _mergeSubscribedParentWithMove_subscription parent--                liftIO $ modifyIORef heightBagRef $ heightBagRemove oldHeight-                return $ Just $ _mergeSubscribedParentWithMove_subscription parent-              Just toKey -> do-                liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey-                return Nothing-        toDelete <- fmap catMaybes $ mapM (\(_ :=> v) -> getConstant v) $ DMap.toList $-          DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents--        return (toDelete, applyAlways p' oldParents)-      getInitialSubscribers :: MergeInitFunc k v q x (MergeSubscribedParentWithMove x k)-      getInitialSubscribers initialParents subscriber = do-        subscribers <- forM (DMap.toList initialParents) $ \(k :=> e) -> do-          keyRef <- liftIO $ newIORef k-          let s = subscriber $ liftIO $ readIORef keyRef-          (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead (nt e) s-          height <- liftIO $ getEventSubscribedHeight parentSubd-          return (fmap (k :=>) parentOcc, height, k :=> MergeSubscribedParentWithMove subscription keyRef)-        return ( DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers-               , fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here-               , DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers-               )--      destroy :: MergeDestroyFunc k (MergeSubscribedParentWithMove x k)-      destroy s = forM_ (DMap.toList s) $ \(_ :=> MergeSubscribedParentWithMove sub _) -> unsubscribe sub--type MergeUpdateFunc k v x p s-   = (forall a. EventM x (k a) -> Subscriber x (v a))-  -> IORef HeightBag-  -> DMap k s-  -> p-  -> EventM x ([EventSubscription x], DMap k s)--type MergeGetSubscription x s = forall a. s a -> EventSubscription x--type MergeInitFunc k v q x s-   = DMap k q-  -> (forall a. EventM x (k a) -> Subscriber x (v a))-  -> EventM x (DMap k v, [Height], DMap k s)--type MergeDestroyFunc k s-   = DMap k s-  -> IO ()--data Merge x k v s = Merge-  { _merge_parentsRef :: {-# UNPACK #-} !(IORef (DMap k s))-  , _merge_heightBagRef :: {-# UNPACK #-} !(IORef HeightBag)-  , _merge_heightRef :: {-# UNPACK #-} !(IORef Height)-  , _merge_sub :: {-# UNPACK #-} !(Subscriber x (DMap k v))-  , _merge_accumRef :: {-# UNPACK #-} !(IORef (DMap k v))-  }--invalidateMergeHeight :: Merge x k v s -> IO ()-invalidateMergeHeight m = invalidateMergeHeight' (_merge_heightRef m) (_merge_sub m)--invalidateMergeHeight' :: IORef Height -> Subscriber x a -> IO ()-invalidateMergeHeight' heightRef sub = do-  oldHeight <- readIORef heightRef-  -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents-  when (oldHeight /= invalidHeight) $ do-    writeIORef heightRef $! invalidHeight-    subscriberInvalidateHeight sub oldHeight--revalidateMergeHeight :: Merge x k v s -> IO ()-revalidateMergeHeight m = do-  currentHeight <- readIORef $ _merge_heightRef m--  -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check-  when (currentHeight == invalidHeight) $ do-    heights <- readIORef $ _merge_heightBagRef m-    parents <- readIORef $ _merge_parentsRef m-    -- When the number of heights in the bag reaches the number of parents, we should have a valid height-    case heightBagSize heights `compare` DMap.size parents of-      LT -> return ()-      EQ -> do-        let height = succHeight $ heightBagMax heights-        traceInvalidateHeight $ "recalculateSubscriberHeight: height: " <> show height-        writeIORef (_merge_heightRef m) $! height-        subscriberRecalculateHeight (_merge_sub m) height-      GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show (DMap.size parents) <> ") for Merge"--scheduleMergeSelf :: HasSpiderTimeline x => Merge x k v s -> Height -> EventM x ()-scheduleMergeSelf m height = scheduleMerge' height (_merge_heightRef m) $ do-  vals <- liftIO $ readIORef $ _merge_accumRef m-  -- 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-  liftIO $ writeIORef (_merge_accumRef m) $! DMap.empty-  --TODO: Assert that m is not empty-  subscriberPropagate (_merge_sub m) vals--checkCycle :: EventSubscribed x -> EventM x ()-checkCycle subscribed = liftIO $ do-    height <- readIORef (eventSubscribedHeightRef subscribed)--    -- currentHeight <- getCurrentHeight-    -- when (height <= currentHeight) $ if height /= invalidHeight-    --     then do-    --       myStack <- liftIO $ whoCreatedIORef undefined --TODO-    --       error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)-    --     else liftIO $-    when (height == invalidHeight) $-#ifdef DEBUG_CYCLES-          do-            nodesInvolvedInCycle <- walkInvalidHeightParents subscribed-            stacks <- forM nodesInvolvedInCycle whoCreatedEventSubscribed-            throwIO (EventLoopException stacks)-#else-          throwIO EventLoopException-#endif---mergeSubscriber :: forall x k v s a. (HasSpiderTimeline x, GCompare k) => EventSubscribed x -> Merge x k v s -> EventM x (k a) -> Subscriber x (v a)-mergeSubscriber subscribed m getKey = Subscriber-  { subscriberPropagate = \a -> do-      oldM <- liftIO $ readIORef $ _merge_accumRef m-      k <- getKey-      let newM = DMap.insertWith (error "Same key fired multiple times for Merge") k a oldM-      tracePropagate (Proxy :: Proxy x) $ "  DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)-      liftIO $ writeIORef (_merge_accumRef m) $! newM-      when (DMap.null oldM) $ do -- Only schedule the firing once-        height <- liftIO $ readIORef $ _merge_heightRef m-        checkCycle subscribed--        scheduleMergeSelf m height-  , subscriberInvalidateHeight = \old -> do --TODO: When removing a parent doesn't actually change the height, maybe we can avoid invalidating-      modifyIORef' (_merge_heightBagRef m) $ heightBagRemove old-      invalidateMergeHeight m-  , subscriberRecalculateHeight = \new -> do-      modifyIORef' (_merge_heightBagRef m) $ heightBagAdd new-      revalidateMergeHeight m-  }----TODO: Be able to run as much of this as possible promptly-updateMerge :: (HasSpiderTimeline x, GCompare k) => EventSubscribed x -> Merge x k v s -> MergeUpdateFunc k v x p s -> p -> SomeMergeUpdate x-updateMerge subscribed m updateFunc p = SomeMergeUpdate updateMe (invalidateMergeHeight m) (revalidateMergeHeight m)-  where updateMe = do-          oldParents <- liftIO $ readIORef $ _merge_parentsRef m-          (subscriptionsToKill, newParents) <- updateFunc (mergeSubscriber subscribed m) (_merge_heightBagRef m) oldParents p-          liftIO $ writeIORef (_merge_parentsRef m) $! newParents-          return subscriptionsToKill--{-# INLINE mergeGCheap' #-}-mergeGCheap' :: forall k v x p s q. (HasSpiderTimeline x, GCompare k, PatchTarget p ~ DMap k q)-  => MergeGetSubscription x s -> MergeInitFunc k v q x s -> MergeUpdateFunc k v x p s -> MergeDestroyFunc k s -> DynamicS x p -> Event x (DMap k v)-mergeGCheap' _ getInitialSubscribers updateFunc destroy d = Event $ \sub -> do-  initialParents <- readBehaviorUntracked $ dynamicCurrent d-  accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"-  heightRef <- liftIO $ newIORef $ error "merge: heightRef not yet initialized"-  heightBagRef <- liftIO $ newIORef $ error "merge: heightBagRef not yet initialized"-  parentsRef :: IORef (DMap k s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"-  changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"--  let subscribed = EventSubscribed-        { eventSubscribedHeightRef = heightRef-        , eventSubscribedRetained = toAny (parentsRef, changeSubdRef)-#ifdef DEBUG_CYCLES-      , eventSubscribedGetParents = do-          let getParent' (_ :=> v) = _eventSubscription_subscribed (getParent v)-          fmap getParent' . DMap.toList  <$> readIORef parentsRef-      , eventSubscribedHasOwnHeightRef = False-      , eventSubscribedWhoCreated = whoCreatedIORef heightRef-#endif-      }--      m = Merge-        { _merge_parentsRef = parentsRef-        , _merge_heightBagRef = heightBagRef-        , _merge_heightRef = heightRef-        , _merge_sub = sub-        , _merge_accumRef = accumRef-        }-  (dm, heights, initialParentState) <- getInitialSubscribers initialParents $ mergeSubscriber subscribed m-  let myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights-      myHeight = if invalidHeight `elem` heights-                 then invalidHeight-                 else succHeight $ heightBagMax myHeightBag-  currentHeight <- getCurrentHeight-  let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now-                     then (if DMap.null dm then Nothing else Just dm, DMap.empty)-                     else (Nothing, dm)-  unless (DMap.null accum) $ scheduleMergeSelf m myHeight-  liftIO $ writeIORef accumRef $! accum-  liftIO $ writeIORef heightRef $! myHeight-  liftIO $ writeIORef heightBagRef $! myHeightBag-  liftIO $ writeIORef parentsRef $! initialParentState-  defer $ SomeMergeInit $ do-    let changeSubscriber = Subscriber-          { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do-              tracePropagate (Proxy :: Proxy x) "SubscriberMerge/Change"-              defer $ updateMerge subscribed m updateFunc a-          , subscriberInvalidateHeight = \_ -> return ()-          , subscriberRecalculateHeight = \_ -> return ()-          }-    (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) changeSubscriber-    forM_ change $ \c -> defer $ updateMerge subscribed m updateFunc c-    -- We explicitly hold on to the unsubscribe function from subscribing to the update event.-    -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain-    -- its subscription.-    liftIO $ writeIORef changeSubdRef (changeSubscriber, changeSubscription)-  let unsubscribeAll = destroy =<< readIORef parentsRef--  return (EventSubscription unsubscribeAll subscribed, occ)---mergeInt :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)-mergeInt = cacheEvent . mergeIntCheap--{-# INLINABLE mergeIntCheap #-}-mergeIntCheap :: forall x a. (HasSpiderTimeline x) => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)-mergeIntCheap d = Event $ \sub -> do-  initialParents <- readBehaviorUntracked $ dynamicCurrent d-  accum <- liftIO $ FastMutableIntMap.newEmpty-  heightRef <- liftIO $ newIORef zeroHeight-  heightBagRef <- liftIO $ newIORef heightBagEmpty-  parents <- liftIO $ FastMutableIntMap.newEmpty-  changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"-  let subscribed = EventSubscribed-        { eventSubscribedHeightRef = heightRef-        , eventSubscribedRetained = toAny (parents, changeSubdRef)-#ifdef DEBUG_CYCLES-        , eventSubscribedGetParents = fmap (_eventSubscription_subscribed . snd) <$> FastMutableIntMap.toList parents-        , eventSubscribedHasOwnHeightRef = False-        , eventSubscribedWhoCreated = whoCreatedIORef heightRef-#endif-        }-  let scheduleSelf = do-        height <- liftIO $ readIORef $ heightRef-        scheduleMerge' height heightRef $ do-          vals <- liftIO $ FastMutableIntMap.getFrozenAndClear accum-          subscriberPropagate sub vals-      invalidateMyHeight = invalidateMergeHeight' heightRef sub-      recalculateMyHeight = do-        currentHeight <- readIORef heightRef-        when (currentHeight == invalidHeight) $ do --TODO: This will almost always be true; can we get rid of this check and just proceed to the next one always?-          heights <- readIORef heightBagRef-          numParents <- FastMutableIntMap.size parents-          case heightBagSize heights `compare` numParents of-            LT -> return ()-            EQ -> do-              let height = succHeight $ heightBagMax heights-              traceInvalidateHeight $ "recalculateSubscriberHeight: height: " <> show height-              writeIORef heightRef $! height-              subscriberRecalculateHeight sub height-            GT -> error $ "revalidateMergeHeight: more heights (" <> show (heightBagSize heights) <> ") than parents (" <> show numParents <> ") for Merge"-      mySubscriber k = Subscriber-        { subscriberPropagate = \a -> do-            checkCycle subscribed--            wasEmpty <- liftIO $ FastMutableIntMap.isEmpty accum-            liftIO $ FastMutableIntMap.insert accum k a-            when wasEmpty scheduleSelf-        , subscriberInvalidateHeight = \old -> do-            modifyIORef' heightBagRef $ heightBagRemove old-            invalidateMyHeight-        , subscriberRecalculateHeight = \new -> do-            modifyIORef' heightBagRef $ heightBagAdd new-            recalculateMyHeight-        }-  forM_ (IntMap.toList initialParents) $ \(k, p) -> do-    (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead p $ mySubscriber k-    liftIO $ do-      forM_ parentOcc $ FastMutableIntMap.insert accum k-      FastMutableIntMap.insert parents k subscription-      height <- getEventSubscribedHeight parentSubd-      if height == invalidHeight-        then writeIORef heightRef invalidHeight-        else do-          modifyIORef' heightBagRef $ heightBagAdd height-          modifyIORef' heightRef $ \oldHeight ->-            if oldHeight == invalidHeight-            then invalidHeight-            else max (succHeight height) oldHeight-  myHeight <- liftIO $ readIORef heightRef-  currentHeight <- getCurrentHeight-  isEmpty <- liftIO $ FastMutableIntMap.isEmpty accum-  occ <- if currentHeight >= myHeight -- If we should have fired by now-    then if isEmpty-         then return Nothing-         else liftIO $ Just <$> FastMutableIntMap.getFrozenAndClear accum-    else do when (not isEmpty) scheduleSelf -- We have things accumulated, but we shouldn't have fired them yet-            return Nothing-  defer $ SomeMergeInit $ do-    let updateMe a = SomeMergeUpdate u invalidateMyHeight recalculateMyHeight-          where-            u = do-              let f k newParent = do-                    subscription@(EventSubscription _ subd) <- subscribe newParent $ mySubscriber k-                    newParentHeight <- liftIO $ getEventSubscribedHeight subd-                    liftIO $ modifyIORef' heightBagRef $ heightBagAdd newParentHeight-                    return subscription-              newSubscriptions <- FastMutableIntMap.traverseIntMapPatchWithKey f a-              oldParents <- liftIO $ FastMutableIntMap.applyPatch parents newSubscriptions-              liftIO $ for_ oldParents $ \oldParent -> do-                oldParentHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed oldParent-                modifyIORef' heightBagRef $ heightBagRemove oldParentHeight-              return $ IntMap.elems oldParents-    let changeSubscriber = Subscriber-          { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do-              tracePropagate (Proxy :: Proxy x) $ "SubscriberMergeInt/Change"-              defer $ updateMe a-          , subscriberInvalidateHeight = \_ -> return ()-          , subscriberRecalculateHeight = \_ -> return ()-          }-    (changeSubscription, change) <- subscribeAndRead (dynamicUpdated d) changeSubscriber-    forM_ change $ \c -> defer $ updateMe c-    -- We explicitly hold on to the unsubscribe function from subscribing to the update event.-    -- If we don't do this, there are certain cases where mergeCheap will fail to properly retain-    -- its subscription.-    liftIO $ writeIORef changeSubdRef (changeSubscriber, changeSubscription)-  let unsubscribeAll = traverse_ (unsubscribe . snd) =<< FastMutableIntMap.toList parents---  return (EventSubscription unsubscribeAll subscribed, occ)--newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }-newtype EventSelectorG x k v = EventSelectorG { selectG :: forall a. k a -> Event x (v a) }--fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v-fanG e = unsafePerformIO $ do-  ref <- newIORef Nothing-  let f = Fan-        { fanParent = e-        , fanSubscribed = ref-        }-  pure $ EventSelectorG $ \k -> eventFan k f--runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()-runHoldInits holdInitRef dynInitRef mergeInitRef = do-  holdInits <- liftIO $ readIORef holdInitRef-  dynInits <- liftIO $ readIORef dynInitRef-  mergeInits <- liftIO $ readIORef mergeInitRef-  unless (null holdInits && null dynInits && null mergeInits) $ do-    liftIO $ writeIORef holdInitRef []-    liftIO $ writeIORef dynInitRef []-    liftIO $ writeIORef mergeInitRef []-    mapM_ initHold holdInits-    mapM_ initDyn dynInits-    mapM_ unSomeMergeInit mergeInits-    runHoldInits holdInitRef dynInitRef mergeInitRef--initHold :: HasSpiderTimeline x => SomeHoldInit x -> EventM x ()-initHold (SomeHoldInit h) = void $ getHoldEventSubscription h--initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()-initDyn (SomeDynInit d) = void $ getDynHold d--newEventEnv :: IO (EventEnv x)-newEventEnv = do-  toAssignRef <- newIORef [] -- This should only actually get used when events are firing-  holdInitRef <- newIORef []-  dynInitRef <- newIORef []-  mergeUpdateRef <- newIORef []-  mergeInitRef <- newIORef []-  heightRef <- newIORef zeroHeight-  toClearRef <- newIORef []-  toClearIntRef <- newIORef []-  toClearRootRef <- newIORef []-  coincidenceInfosRef <- newIORef []-  invalidatedCoincidencesRef <- newIORef []-  delayedRef <- newIORef IntMap.empty-  return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef invalidatedCoincidencesRef delayedRef--clearEventEnv :: EventEnv x -> IO ()-clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearIntRef toClearRootRef heightRef coincidenceInfosRef invalidatedCoincidencesRef delayedRef) = do-  writeIORef toAssignRef []-  writeIORef holdInitRef []-  writeIORef dynInitRef []-  writeIORef mergeUpdateRef []-  writeIORef mergeInitRef []-  writeIORef heightRef zeroHeight-  writeIORef toClearRef []-  writeIORef toClearIntRef []-  writeIORef toClearRootRef []-  writeIORef coincidenceInfosRef []-  writeIORef invalidatedCoincidencesRef []-  writeIORef delayedRef IntMap.empty---- | Run an event action outside of a frame-runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex-runFrame a = SpiderHost $ do-  let env = _spiderTimeline_eventEnv $ unSTE (spiderTimeline :: SpiderTimelineEnv x)-  let go = do-        result <- a-        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-        return result-  result <- runEventM go-  toClear <- readIORef $ eventEnvClears env-  forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing-  toClearInt <- readIORef $ eventEnvIntClears env-  forM_ toClearInt $ \(Some (IntClear ref)) -> {-# SCC "intClear" #-} writeIORef ref $! IntMap.empty-  toClearRoot <- readIORef $ eventEnvRootClears env-  forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty-  toAssign <- readIORef $ eventEnvAssignments env-  toReconnectRef <- newIORef []-  coincidenceInfos <- readIORef $ eventEnvResetCoincidences env-  forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do-    writeIORef vRef v-    traceInvalidate $ "Invalidating Hold"-    writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef-  mergeUpdates <- readIORef $ eventEnvMergeUpdates env-  writeIORef (eventEnvMergeUpdates env) []-  tracePropagate (Proxy::Proxy x) $ "Updating merges"-  mergeSubscriptionsToKill <- runEventM $ concat <$> mapM _someMergeUpdate_update mergeUpdates-  tracePropagate (Proxy::Proxy x) $ "Updating merges done"-  toReconnect <- readIORef toReconnectRef-  clearEventEnv env-  switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do-    oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed-    wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed-    traceInvalidate $ "Finalizing invalidator for Switch" <> showNodeId subscribed-    finalize wi-    i <- evaluate $ switchSubscribedOwnInvalidator subscribed-    wi' <- mkWeakPtrWithDebug i "wi'"-    writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'-    writeIORef (switchSubscribedBehaviorParents subscribed) []-    writeIORef (eventEnvHoldInits env) [] --TODO: Should we reuse this?-    e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) $ eventEnvHoldInits env-    runEventM $ runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env) --TODO: Is this actually OK? It seems like it should be, since we know that no events are firing at this point, but it still seems inelegant-    --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times-    sub <- newSubscriberSwitch subscribed-    subscription <- unSpiderHost $ runFrame $ {-# SCC "subscribeSwitch" #-} subscribe e sub --TODO: Assert that the event isn't firing --TODO: This should not loop because none of the events should be firing, but still, it is inefficient-    {--    stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)-    liftIO $ debugStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of-      EventRoot _ -> "EventRoot"-      EventNever -> "EventNever"-      _ -> "something else"-    -}-    writeIORef (switchSubscribedCurrentParent subscribed) $! subscription-    return oldSubscription-  liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill-  liftIO $ mapM_ unsubscribe switchSubscriptionsToKill-  forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do-    EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed-    parentHeight <- getEventSubscribedHeight subd'-    myHeight <- readIORef $ switchSubscribedHeight subscribed-    when (parentHeight /= myHeight) $ do-      writeIORef (switchSubscribedHeight subscribed) $! invalidHeight-      WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight-  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-  forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mInvalidate) -> do-    unsubscribe subscription-    mapM_ invalidateCoincidenceHeight mInvalidate-  invalidatedCoincidences <- readIORef $ eventEnvInvalidatedCoincidences env-  writeIORef (eventEnvInvalidatedCoincidences env) []-  forM_ invalidatedCoincidences $ \(SomeCoincidenceSubscribed subscribed) -> recalculateCoincidenceHeight subscribed-  mapM_ _someMergeUpdate_recalculateHeight mergeUpdates-  forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do-    height <- calculateSwitchHeight subscribed-    updateSwitchHeight height subscribed-  return result--newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)--{-# INLINE zeroHeight #-}-zeroHeight :: Height-zeroHeight = Height 0--{-# INLINE invalidHeight #-}-invalidHeight :: Height-invalidHeight = Height (-1000)--#ifdef DEBUG_CYCLES--- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents-{-# INLINE invalidHeightBeingTraversed #-}-invalidHeightBeingTraversed :: Height-invalidHeightBeingTraversed = Height (-1001)-#endif--{-# INLINE succHeight #-}-succHeight :: Height -> Height-succHeight h@(Height a) =-  if h == invalidHeight-  then invalidHeight-  else Height $ succ a--invalidateCoincidenceHeight :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO ()-invalidateCoincidenceHeight subscribed = do-  oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed-  when (oldHeight /= invalidHeight) $ do-    writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight-    let env = _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))-    modifyIORef' (eventEnvInvalidatedCoincidences env) (SomeCoincidenceSubscribed subscribed :)-    WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight--updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()-updateSwitchHeight new subscribed = do-  oldHeight <- readIORef $ switchSubscribedHeight subscribed-  when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion-    when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion-      writeIORef (switchSubscribedHeight subscribed) $! new-      WeakBag.traverse_ (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new--recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()-recalculateCoincidenceHeight subscribed = do-  oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed-  when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion-    height <- calculateCoincidenceHeight subscribed-    when (height /= invalidHeight) $ do-      writeIORef (coincidenceSubscribedHeight subscribed) $! height-      WeakBag.traverse_ (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height--calculateSwitchHeight :: SwitchSubscribed x a -> IO Height-calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)--calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height-calculateCoincidenceHeight subscribed = do-  outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed-  innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)-  return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight--data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)--invalidate :: IORef [SomeSwitchSubscribed x] -> InvalidatorList x -> IO (InvalidatorList x)-invalidate toReconnectRef (InvalidatorList _ _ wis) = do-  forM_ wis $ \wi -> do-    mi <- deRefWeak wi-    case mi of-      Nothing -> do-        traceInvalidate "invalidate Dead"-        return () --TODO: Should we clean this up here?-      Just i -> do-        finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict-        case i of-          InvalidatorPull p -> do-            traceInvalidate $ "invalidate: Pull" <> showNodeId p-            mVal <- readIORef $ pullValue p-            forM_ mVal $ \val -> do-              writeIORef (pullValue p) Nothing-              writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)-          InvalidatorSwitch subscribed -> do-            traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed-            modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)-  return emptyInvalidatorList -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them------------------------------------------------------------------------------------- Reflex integration------------------------------------------------------------------------------------- | Designates the default, global Spider timeline-data SpiderTimeline x-type role SpiderTimeline nominal---- | The default, global Spider environment-type Spider = SpiderTimeline Global--instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where-  {-# INLINABLE sample #-}-  sample (SpiderBehavior b) = readBehaviorUntracked b--instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where-  {-# INLINABLE hold #-}-  hold = holdSpiderEventM-  {-# INLINABLE holdDyn #-}-  holdDyn = holdDynSpiderEventM-  {-# INLINABLE holdIncremental #-}-  holdIncremental = holdIncrementalSpiderEventM-  {-# INLINABLE buildDynamic #-}-  buildDynamic = buildDynamicSpiderEventM-  {-# INLINABLE headE #-}-  headE = R.slowHeadE---  headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e-  {-# INLINABLE now #-}-  now = nowSpiderEventM--instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where-  {-# INLINABLE sample #-}-  sample = coerce . readBehaviorTracked . unSpiderBehavior--instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where-  {-# INLINABLE sample #-}-  sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b--instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where-  {-# INLINABLE hold #-}-  hold v0 e = Reflex.Class.current <$> Reflex.Class.holdDyn v0 e-  {-# INLINABLE holdDyn #-}-  holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce e-  {-# INLINABLE holdIncremental #-}-  holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e-  {-# INLINABLE buildDynamic #-}-  buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e-  {-# INLINABLE headE #-}-  headE = R.slowHeadE---  headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e-  {-# INLINABLE now #-}-  now = SpiderPushM nowSpiderEventM---instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where-  {-# INLINE (>>=) #-}-  x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x-#if !MIN_VERSION_base(4,13,0)-  {-# INLINE fail #-}-  fail _ = error "Dynamic does not support 'fail'"-#endif--{-# INLINABLE newJoinDyn #-}-newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)-newJoinDyn d =-  let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)-      eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d-      eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d-      eBoth = Reflex.Spider.Internal.coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d-      v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]-  in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'--instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where-  fmap = mapDynamicSpider-  x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d--mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b-mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic-{-# INLINE [1] mapDynamicSpider #-}--instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where-  pure = SpiderDynamic . dynamicConst-  liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)-  SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b-  a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]-  (<*) = flip (*>) -- There are no effects, so order doesn't matter--holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)-holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e--holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)-holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e--holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)-holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e--buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)-buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e--instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where-  {-# INLINABLE hold #-}-  hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e-  {-# INLINABLE holdDyn #-}-  holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e-  {-# INLINABLE holdIncremental #-}-  holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e-  {-# INLINABLE buildDynamic #-}-  buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e-  {-# INLINABLE headE #-}-  headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e-  {-# INLINABLE now #-}-  now = runFrame . runSpiderHostFrame $ Reflex.Class.now---instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where-  sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can--instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where-  {-# INLINABLE hold #-}-  hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e-  {-# INLINABLE holdDyn #-}-  holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e-  {-# INLINABLE holdIncremental #-}-  holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e-  {-# INLINABLE buildDynamic #-}-  buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDynIdentity) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e-  {-# INLINABLE headE #-}-  headE = R.slowHeadE---  headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e-  {-# INLINABLE now #-}-  now = SpiderHostFrame Reflex.Class.now--instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where-  {-# INLINABLE sample #-}-  sample = runFrame . readBehaviorUntracked . unSpiderBehavior--instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where-  {-# INLINABLE sample #-}-  sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample--instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where-  {-# INLINABLE hold #-}-  hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e-  {-# INLINABLE holdDyn #-}-  holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e-  {-# INLINABLE holdIncremental #-}-  holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e-  {-# INLINABLE buildDynamic #-}-  buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e-  {-# INLINABLE headE #-}-  headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e-  {-# INLINABLE now #-}-  now = Reflex.Spider.Internal.ReadPhase Reflex.Class.now------------------------------------------------------------------------------------- Deprecated items------------------------------------------------------------------------------------- | 'SpiderEnv' is the old name for 'SpiderTimeline'-{-# DEPRECATED SpiderEnv "Use 'SpiderTimelineEnv' instead" #-}-type SpiderEnv = SpiderTimeline-instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where-  {-# INLINABLE subscribeEvent #-}-  subscribeEvent e = SpiderHostFrame $ do-    --TODO: Unsubscribe eventually (manually and/or with weak ref)-    val <- liftIO $ newIORef Nothing-    subscription <- subscribe (unSpiderEvent e) $ Subscriber-      { subscriberPropagate = \a -> do-          liftIO $ writeIORef val $ Just a-          scheduleClear val-      , subscriberInvalidateHeight = \_ -> return ()-      , subscriberRecalculateHeight = \_ -> return ()-      }-    return $ SpiderEventHandle-      { spiderEventHandleSubscription = subscription-      , spiderEventHandleValue = val-      }--instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where-  type EventTrigger (SpiderTimeline x) = RootTrigger x-  type EventHandle (SpiderTimeline x) = SpiderEventHandle x-  type HostFrame (SpiderTimeline x) = SpiderHostFrame x--instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where-  {-# NOINLINE readEvent #-}-  readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do-    result <- readIORef $ spiderEventHandleValue h-    touch h-    return result--instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where-  newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO-  newFanEventWithTrigger f = SpiderHost $ do-    es <- newFanEventWithTriggerIO f-    return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es--instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where-  newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO-  newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do-    es <- newFanEventWithTriggerIO f-    return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es--instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where-  {-# INLINABLE subscribeEvent #-}-  subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent--instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where-  type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x-  fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a-  runHostFrame = runFrame . runSpiderHostFrame--unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)-unsafeNewSpiderTimelineEnv = do-  lock <- newMVar ()-  env <- newEventEnv-#ifdef DEBUG-  depthRef <- newIORef 0-#endif-  return $ STE $ SpiderTimelineEnv-    { _spiderTimeline_lock = lock-    , _spiderTimeline_eventEnv = env-#ifdef DEBUG-    , _spiderTimeline_depth = depthRef-#endif-    }---- | Create a new SpiderTimelineEnv-newSpiderTimeline :: IO (Some SpiderTimelineEnv)-newSpiderTimeline = withSpiderTimeline (pure . Some)--data LocalSpiderTimeline (x :: Type) s--instance Reifies s (SpiderTimelineEnv x) =>-         HasSpiderTimeline (LocalSpiderTimeline x s) where-  spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)--localSpiderTimeline-  :: proxy s-  -> SpiderTimelineEnv x-  -> SpiderTimelineEnv (LocalSpiderTimeline x s)-localSpiderTimeline _ = coerce---- | Pass a new timeline to the given function.-withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r-withSpiderTimeline k = do-  env <- unsafeNewSpiderTimelineEnv-  reify env $ \s -> k $ localSpiderTimeline s env--newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)--type ComputeM = EventM--newtype SpiderPushM (x :: Type) a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)--instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where-  {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}-  newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }-  newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }-  newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: DynamicS x (Identity a) } -- deriving (Functor, Applicative, Monad)-  newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: DynamicS x p }-  type PullM (SpiderTimeline x) = SpiderPullM x-  type PushM (SpiderTimeline x) = SpiderPushM x-  {-# INLINABLE never #-}-  never = SpiderEvent eventNever-  {-# INLINABLE constant #-}-  constant = SpiderBehavior . behaviorConst-  {-# INLINE push #-}-  push f = SpiderEvent . push (coerce f) . unSpiderEvent-  {-# INLINE pushCheap #-}-  pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent-  {-# INLINABLE pull #-}-  pull = SpiderBehavior . pull . coerce-  {-# INLINABLE fanG #-}-  fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))-  {-# INLINABLE mergeG #-}-  mergeG-    :: forall k2 (k :: k2 -> Type) q (v :: k2 -> Type). GCompare k-    => (forall a. q a -> R.Event (SpiderTimeline x) (v a))-    -> DMap k q-    -> R.Event (SpiderTimeline x) (DMap k v)-  mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst-  {-# INLINABLE switch #-}-  switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior-  {-# INLINABLE coincidence #-}-  coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent-  {-# INLINABLE current #-}-  current = SpiderBehavior . dynamicCurrent . unSpiderDynamic-  {-# INLINABLE updated #-}-  updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic-  {-# INLINABLE unsafeBuildDynamic #-}-  unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'-  {-# INLINABLE unsafeBuildIncremental #-}-  unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv-  {-# INLINABLE mergeIncrementalG #-}-  mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental-  {-# INLINABLE mergeIncrementalWithMoveG #-}-  mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental-  {-# INLINABLE currentIncremental #-}-  currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental-  {-# INLINABLE updatedIncremental #-}-  updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental-  {-# INLINABLE incrementalToDynamic #-}-  incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do-    c <- readBehaviorUntracked $ dynamicCurrent i-    return $ Identity <$> apply p c --TODO: Avoid the redundant 'apply'-  eventCoercion Coercion = Coercion-  behaviorCoercion Coercion = Coercion-  dynamicCoercion Coercion = Coercion-  incrementalCoercion Coercion Coercion = Coercion-  {-# INLINABLE mergeIntIncremental #-}-  mergeIntIncremental = SpiderEvent . mergeInt . coerce-  {-# INLINABLE fanInt #-}-  fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))--data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)--data SpiderEventHandle x a = SpiderEventHandle-  { spiderEventHandleSubscription :: EventSubscription x-  , spiderEventHandleValue :: IORef (Maybe a)-  }--instance MonadRef (EventM x) where-  type Ref (EventM x) = Ref IO-  {-# INLINABLE newRef #-}-  {-# INLINABLE readRef #-}-  {-# INLINABLE writeRef #-}-  newRef = liftIO . newRef-  readRef = liftIO . readRef-  writeRef r a = liftIO $ writeRef r a--instance MonadAtomicRef (EventM x) where-  {-# INLINABLE atomicModifyRef #-}-  atomicModifyRef r f = liftIO $ atomicModifyRef r f---- | The monad for actions that manipulate a Spider timeline identified by @x@-newtype SpiderHost (x :: Type) a = SpiderHost { unSpiderHost :: IO a }-  deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)--instance Monad (SpiderHost x) where-  {-# INLINABLE (>>=) #-}-  SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f-#if !MIN_VERSION_base(4,13,0)-  {-# INLINABLE fail #-}-  fail = MonadFail.fail-#endif--instance MonadFail (SpiderHost x) where-  {-# INLINABLE fail #-}-  fail s = SpiderHost $ MonadFail.fail s---- | Run an action affecting the global Spider timeline; this will be guarded by--- a mutex for that timeline-runSpiderHost :: SpiderHost Global a -> IO a-runSpiderHost (SpiderHost a) = a---- | Run an action affecting a given Spider timeline; this will be guarded by a--- mutex for that timeline-runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a-runSpiderHostForTimeline (SpiderHost a) _ = a--newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame { runSpiderHostFrame :: EventM x a }-  deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException, MonadMask, MonadThrow, MonadCatch)--instance Monad (SpiderHostFrame x) where-  {-# INLINABLE (>>=) #-}-  SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f-#if !MIN_VERSION_base(4,13,0)-  {-# INLINABLE fail #-}-  fail s = SpiderHostFrame $ fail s-#endif--instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where-  notReadyUntil _ = pure ()-  notReady = pure ()--newEventWithTriggerIO :: forall x a. HasSpiderTimeline x => (RootTrigger x a -> IO (IO ())) -> IO (Event x a)-newEventWithTriggerIO f = do-  es <- newFanEventWithTriggerIO $ \Refl -> f-  return $ select es Refl--newFanEventWithTriggerIO :: (HasSpiderTimeline x, GCompare k) => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)-newFanEventWithTriggerIO f = do-  occRef <- newIORef DMap.empty-  subscribedRef <- newIORef DMap.empty-  let !r = Root-        { rootOccurrence = occRef-        , rootSubscribed = subscribedRef-        , rootInit = f-        }-  return $ EventSelector $ \k -> eventRoot k r--newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)+{-# LANGUAGE DeriveFunctor #-}+{-# LANGUAGE EmptyDataDecls #-}+{-# LANGUAGE ExistentialQuantification #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE FlexibleInstances #-}+{-# LANGUAGE GADTs #-}+{-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE InstanceSigs #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiParamTypeClasses #-}+{-# LANGUAGE PolyKinds #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RoleAnnotations #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE StandaloneDeriving #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE UndecidableInstances #-}+{-# OPTIONS_GHC -Wunused-binds #-}++-- | This module is the implementation of the 'Spider' 'Reflex' engine.  It uses+-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.+module Reflex.Spider.Internal+  ( module Reflex.Spider.Internal+  ) where++import Control.Concurrent+import Control.Exception+import Control.Monad hiding (forM, forM_, mapM, mapM_)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)+import Control.Monad.Exception+import qualified Control.Monad.Fail as MonadFail+import Control.Monad.Fix+import Control.Monad.IO.Class+import Control.Monad.Primitive+import Control.Monad.Reader.Class+import Control.Monad.Ref+import Data.Align+import Data.Coerce+import Data.Dependent.Map (DMap)+import qualified Data.Dependent.Map as DMap+import Data.Dependent.Sum (DSum (..))+import Data.Foldable hiding (concat, elem, sequence_)+import Data.Functor.Constant+import Data.Functor.Misc+import Data.Functor.Product+import Data.GADT.Compare+import Data.IORef+import Data.IntMap.Strict (IntMap)+import qualified Data.IntMap.Strict as IntMap+import Data.Kind (Type)+import Data.Maybe hiding (catMaybes, mapMaybe)+import Data.Proxy+import Data.These+import Data.Traversable+import Data.Type.Equality ((:~:) (Refl))+import GHC.Exts hiding (build, toList)+import GHC.IORef (IORef (..))++import Control.Monad.ReaderIO+#if MIN_VERSION_base(4,13,0)+import GHC.IORef (atomicModifyIORef'_)+#endif+import GHC.Stack+import System.IO.Unsafe+import System.Mem.Weak+import Unsafe.Coerce+import Witherable (Filterable (..), mapMaybe)++#if !MIN_VERSION_base(4,18,0)+import Control.Applicative (liftA2)+import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_)+import Control.Monad.Fail (MonadFail)+import Data.List (isPrefixOf)+import Data.Monoid (mempty, (<>))+#else+import Control.Monad.Identity+#endif++#ifdef MIN_VERSION_semialign+#if MIN_VERSION_these(0,8,0)+import Data.These.Combinators (justThese)+#endif+#if MIN_VERSION_semialign(1,1,0)+import Data.Zip (Zip (..))+#endif+#endif++import Data.List.NonEmpty (NonEmpty (..), nonEmpty)+import qualified Data.List.NonEmpty as NonEmpty+import Data.Tree (Forest, Tree (..), drawForest)++#ifdef DEBUG_HIDE_INTERNALS+import Data.List (isPrefixOf)+#endif++import Data.Patch+import qualified Data.Patch.DMapWithMove as PatchDMapWithMove+import Data.Profunctor.Unsafe ((#.), (.#))+import Data.Reflection+import Data.Some (Some (Some))+import Data.Type.Coercion+import Prelude hiding (filter)++import Data.WeakBag (WeakBag)+import qualified Data.WeakBag as WeakBag+import qualified Reflex.Class+import qualified Reflex.Class as R+import qualified Reflex.Host.Class+import Reflex.NotReady.Class+import Reflex.PerformEvent.Base (PerformEventT)++#ifdef DEBUG_TRACE_EVENTS+import qualified Data.ByteString.Char8 as BS8+import System.IO (stderr)+import Data.List (isPrefixOf)+#endif++import Reflex.Spider.Height++-- TODO stdout might not be the best channel for debug output+debugStrLn :: String -> IO ()+debugStrLn = putStrLn++#ifdef DEBUG_TRACE_EVENTS+withStackOneLine :: (BS8.ByteString -> a) -> a+withStackOneLine expr = unsafePerformIO $ do+  stack <- currentCallStack+  return (expr . BS8.pack  . unwords . dropInternal . reverse $ stack)+    where dropInternal = filterStack "Reflex.Spider.Internal"++printCallSite :: BS8.ByteString -> IO ()+printCallSite callSite = unless (BS8.null callSite) $ BS8.hPutStrLn stderr callSite++#else++{-# INLINE withStackOneLine #-}+withStackOneLine :: (() -> a) -> a+withStackOneLine expr = expr ()++{-# INLINE printCallSite #-}+printCallSite :: () -> IO ()+printCallSite _ = pure ()++#endif++#ifdef DEBUG+#define DEBUG_NODEIDS+#define DEBUG_FRAME+#endif++debugEnabled :: Bool+#ifdef DEBUG+debugEnabled = True+#else+debugEnabled = False+#endif++debugFrame :: Bool+#ifdef DEBUG_FRAME+debugFrame = True+#else+debugFrame = False+#endif++debugPropagate :: Bool+debugInvalidateHeight :: Bool+debugInvalidate :: Bool++#ifdef DEBUG++#ifdef DEBUG_TRACE_PROPAGATION+debugPropagate = True+#else+debugPropagate = False+#endif++#ifdef DEBUG_TRACE_HEIGHT+debugInvalidateHeight = True+#else+debugInvalidateHeight = False+#endif++#ifdef DEBUG_TRACE_INVALIDATION+debugInvalidate = True+#else+debugInvalidate = False+#endif++class HasNodeId a where+  getNodeId :: a -> NodeId++instance HasNodeId (CacheSubscribed x a) where+  getNodeId = _cacheSubscribed_nodeId++instance HasNodeId (Hold x p) where+  getNodeId = holdNodeId++instance HasNodeId (SwitchSubscribed x a) where+  getNodeId = switchSubscribedNodeId++instance HasNodeId (FanSubscribed x map v) where+  getNodeId = fanSubscribedNodeId++instance HasNodeId (CoincidenceSubscribed x a) where+  getNodeId = coincidenceSubscribedNodeId++instance HasNodeId (RootSubscribed x a) where+  getNodeId = rootSubscribedNodeId++instance HasNodeId (Pull x a) where+  getNodeId = pullNodeId++{-# INLINE showNodeId #-}+showNodeId :: HasNodeId a => a -> String+showNodeId = showNodeId' . getNodeId++showNodeId' :: NodeId -> String+showNodeId' = ("#"<>) . show++-- | The indentation depth of trace messages.+type TraceDepthRef = IORef Int++newTraceDepthRef :: IO TraceDepthRef+newTraceDepthRef = newIORef 0++#else++debugPropagate = False+debugInvalidateHeight = False+debugInvalidate = False++-- This must be inline, or error messages will cause memory leaks due to retaining the node in question+{-# INLINE showNodeId #-}+showNodeId :: a -> String+showNodeId _ = ""++{-# INLINE showNodeId' #-}+showNodeId' :: NodeId -> String+showNodeId' _ = ""++type TraceDepthRef = ()++{-# INLINE newTraceDepthRef #-}+newTraceDepthRef :: IO TraceDepthRef+newTraceDepthRef = pure ()++#endif++#ifdef DEBUG_NODEIDS+type NodeId = Int++{-# NOINLINE nextNodeIdRef #-}+nextNodeIdRef :: IORef Int+nextNodeIdRef = unsafePerformIO $ newIORef 1++newNodeId :: IO NodeId+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)+#else+type NodeId = ()++{-# INLINE newNodeId #-}+newNodeId :: IO NodeId+newNodeId = pure ()+#endif++debugOccurrence :: Applicative m => String -> Maybe a -> m ()+debugOccurrence message = \case+  Just _ -> error message+  Nothing -> pure ()++--------------------------------------------------------------------------------+-- EventSubscription+--------------------------------------------------------------------------------++-- NB: Once you subscribe to an Event, you must always hold on the the WHOLE EventSubscription you get back+-- If you do not retain the subscription, you may be prematurely unsubscribed from the parent event.++-- Why do we use Any here, instead of just giving _eventSubscription_retained an+-- existential type? Sadly, GHC does not currently know how to unbox types+-- with existentially quantified fields. So instead we just coerce values+-- to type Any on the way in. Since we never coerce them back, this is+-- perfectly safe.+data EventSubscription x = EventSubscription+  { _eventSubscription_unsubscribe :: !(IO ())+  , _eventSubscription_retained :: {-# NOUNPACK #-} !Any+  , _eventSubscription_node :: {-# NOUNPACK #-} !(EventNode x)+  }++unsubscribe :: EventSubscription x -> IO ()+unsubscribe (EventSubscription u _ _) = u++--------------------------------------------------------------------------------+-- Event+--------------------------------------------------------------------------------++newtype Event x a = Event {subscribeAndRead :: Subscriber x a -> EventM x (SubscribeResult x a)}++data SubscribeResult x a = SubscribeResult+  { subscribeSubscription :: EventSubscription x+  , subscribeOccurrence :: Maybe a+  }++-- Rewrite rules for cached events+--+-- Before phase 1, the "expand" rules rewrite each cached primitive to+-- cacheEvent over its uncached event, and the other rules simplify the result.+-- From phase 1, the "contract" rules turn each remaining cacheEvent over an+-- uncached event back into the cached primitive, or into a fused primitive such+-- as pushSwitch when there is a pushCheap in between. cacheEvent, the uncached+-- events, the cached primitives and holdBehavior are not inlined before+-- phase 0, so that the rules can match them. fanG, fanInt and headE are only+-- in rules that are active before phase 1, so they are not inlined before+-- phase 1.+{-# RULES+"push/expand" [~1] forall f e. push f e = cacheEvent (pushCheap f e)+"switch/expand" [~1] forall b. switch b = cacheEvent (switchUncached b)+"coincidence/expand" [~1] forall e. coincidence e = cacheEvent (coincidenceUncached e)+"mergeInt/expand" [~1] forall d. mergeInt d = cacheEvent (mergeIntCheap d)+"mergeG/expand" [~1] forall (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMap k q)). mergeG nt d = cacheEvent (mergeCheap nt d)+"mergeWithMove/expand" [~1] forall (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMapWithMove k q)). mergeWithMove nt d = cacheEvent (mergeCheapWithMove nt d)+"cacheEvent/cacheEvent" [~1] forall e. cacheEvent (cacheEvent e) = cacheEvent e+"pushCheap/cacheEvent" [~1] forall f e. pushCheap f (cacheEvent e) = cacheEvent (pushCheap f e)+"pushCheap/pushCheap" [~1] forall f g e. pushCheap f (pushCheap g e) = pushCheap (composePush f g) e+"coincidenceUncached/cacheEvent" [~1] forall e. cacheEvent (coincidenceUncached (cacheEvent e)) = cacheEvent (coincidenceUncached e)+"pushCheap/coincidenceUncached/cacheEvent" [~1] forall f e. cacheEvent (pushCheap f (coincidenceUncached (cacheEvent e))) = cacheEvent (pushCheap f (coincidenceUncached e))+"fanG/cacheEvent" [~1] forall e. fanG (cacheEvent e) = fanG e+"fanInt/cacheEvent" [~1] forall e. fanInt (cacheEvent e) = fanInt e+"headE/cacheEvent" [~1] forall e. headE (cacheEvent e) = headE e+"holdBehavior/cacheEvent" [~1] forall v e. holdBehavior v (cacheEvent e) = holdBehavior v e+"push/contract" [1] forall f e. cacheEvent (pushCheap f e) = push f e+"switch/contract" [1] forall b. cacheEvent (switchUncached b) = switch b+"coincidence/contract" [1] forall e. cacheEvent (coincidenceUncached e) = coincidence e+"mergeInt/contract" [1] forall d. cacheEvent (mergeIntCheap d) = mergeInt d+"mergeG/contract" [1] forall (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMap k q)). cacheEvent (mergeCheap nt d) = mergeG nt d+"mergeWithMove/contract" [1] forall (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMapWithMove k q)). cacheEvent (mergeCheapWithMove nt d) = mergeWithMove nt d+"pushSwitch/contract" [1] forall f b. cacheEvent (pushCheap f (switchUncached b)) = pushSwitch f b+"pushCoincidence/contract" [1] forall f e. cacheEvent (pushCheap f (coincidenceUncached e)) = pushCoincidence f e+"pushMergeInt/contract" [1] forall f d. cacheEvent (pushCheap f (mergeIntCheap d)) = pushMergeInt f d+"pushMergeG/contract" [1] forall (f :: DMap k v -> EventM x (Maybe c)) (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMap k q)). cacheEvent (pushCheap f (mergeCheap nt d)) = pushMergeG f nt d+"pushMergeWithMove/contract" [1] forall (f :: DMap k v -> EventM x (Maybe c)) (nt :: forall a. q a -> Event x (v a)) (d :: DynamicS x (PatchDMapWithMove k q)). cacheEvent (pushCheap f (mergeCheapWithMove nt d)) = pushMergeWithMove f nt d+  #-}++-- | Used by the rule "pushCheap/pushCheap".+{-# INLINE composePush #-}+composePush :: (b -> EventM x (Maybe c)) -> (a -> EventM x (Maybe b)) -> a -> EventM x (Maybe c)+composePush f g a = g a >>= maybe (return Nothing) f++-- | Construct an 'Event' equivalent to that constructed by 'push', but with no+-- caching; if the computation function is very cheap, this is (much) more+-- efficient than 'push'+{-# INLINE [0] pushCheap #-}+pushCheap :: forall (x :: Type) a b. HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b+pushCheap = pushCheapImpl++{-# INLINE pushCheapImpl #-}+pushCheapImpl :: forall (x :: Type) a b. HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b+pushCheapImpl !f e = Event $ \sub -> do+  SubscribeResult subscription occ <-+    subscribeAndRead e+      $ debugSubscriber "push"+      $ sub+        { subscriberPropagate = \a -> do+            mb <- f a+            mapM_ (subscriberPropagate sub) mb+        }+  SubscribeResult subscription <$> maybe (return Nothing) f occ++-- | A subscriber that never triggers other 'Event's+{-# INLINE terminalSubscriber #-}+terminalSubscriber :: (a -> EventM x ()) -> Subscriber x a+terminalSubscriber p =+  Subscriber+    { subscriberPropagate = p+    , subscriberInvalidateHeight = \_ -> pure ()+    , subscriberRecalculateHeight = \_ -> pure ()+    }++{-# INLINE ownHeightSubscriber #-}+ownHeightSubscriber :: IORef Height -> (Height -> IO ()) -> (Height -> IO ()) -> (a -> EventM x ()) -> Subscriber x a+ownHeightSubscriber heightRef invalidateSubscribers recalculateSubscribers propagateOccurrence =+  Subscriber+    { subscriberPropagate = propagateOccurrence+    , subscriberInvalidateHeight = \_ -> invalidateOwnHeight heightRef invalidateSubscribers+    , subscriberRecalculateHeight = recalculateOwnHeight heightRef recalculateSubscribers . pure+    }++data HeadESubscribed x a = HeadESubscribed+  { headESubscribedSubscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))+  , headESubscribedParent :: !(EventSubscription x)+  , headESubscribedOccurrence :: {-# UNPACK #-} !(IORef (Maybe a))+  , headESubscribedNode :: {-# NOUNPACK #-} !(EventNode x)+  }++-- | State of a 'headE' node, retains exactly what's needed for each phase.+data HeadEState x a+  = HeadEStateInitial (Event x a)+  | HeadEStateSubscribed !(HeadESubscribed x a)+  | HeadEStateOccurred {-# UNPACK #-} !(IORef (Maybe a))++-- | Specialized implementation of 'Reflex.Class.slowHeadE'.+{-# NOINLINE [1] headE #-}+headE :: forall x m a. (HasSpiderTimeline x, Defer (SomeMergeInit x) m) => Event x a -> m (Event x a)+headE originalE = do+  stateRef <- liftIO $ newIORef (HeadEStateInitial originalE :: HeadEState x a)+  let unsubscribeAfterOccurrence occRef =+        liftIO (readIORef stateRef) >>= \case+          HeadEStateSubscribed subscribed -> liftIO $ do+            writeIORef stateRef $ HeadEStateOccurred occRef+            unsubscribe $ headESubscribedParent subscribed+            deferRecalculateHeight @x $ SomeRecalculateHeight $ do+              let heightRef = eventNodeHeightRef $ headESubscribedNode subscribed+                  subscribers = headESubscribedSubscribers subscribed+              invalidateOwnHeight heightRef $ invalidateBagHeight subscribers+              recalculateOwnHeight heightRef (recalculateBagHeight subscribers) (pure zeroHeight)+          _ -> pure ()+      subscribeUntilHead :: EventM x (HeadEState x a)+      subscribeUntilHead =+        liftIO (readIORef stateRef) >>= \case+          HeadEStateInitial parentEvent -> do+            subscribers <- liftIO WeakBag.empty+            occRef <- liftIO $ newIORef Nothing+            node <-+              mkEventNode+                zeroHeight+                ( readIORef stateRef >>= \case+                    HeadEStateSubscribed subscribed -> pure [_eventSubscription_node $ headESubscribedParent subscribed]+                    _ -> pure []+                )+                (whoCreatedIORef stateRef)+            let heightRef = eventNodeHeightRef node+            SubscribeResult parentSubscription occ <- subscribeAndRead parentEvent $+              ownHeightSubscriber heightRef (invalidateBagHeight subscribers) (recalculateBagHeight subscribers) $ \a -> do+                setOccurrence "headE" occRef a+                -- Propagating before unsubscribing can help avoid+                -- teardown-then-revive when downstream would re-subscribe:+                propagate a subscribers+                unsubscribeAfterOccurrence occRef+            liftIO $ writeIORef heightRef =<< eventSubscriptionHeight parentSubscription+            let !subscribed =+                  HeadESubscribed+                    { headESubscribedSubscribers = subscribers+                    , headESubscribedParent = parentSubscription+                    , headESubscribedOccurrence = occRef+                    , headESubscribedNode = node+                    }+            liftIO $ writeIORef stateRef $ HeadEStateSubscribed subscribed+            case occ of+              Just a -> do+                setOccurrence "headE" occRef a+                unsubscribeAfterOccurrence occRef+                pure $ HeadEStateOccurred occRef+              Nothing -> pure $ HeadEStateSubscribed subscribed+          alreadySubscribed -> pure alreadySubscribed+  defer $ SomeMergeInit $ void subscribeUntilHead+  pure $ Event $ \sub -> do+    liftIO $ touch stateRef+    state <-+      liftIO (readIORef stateRef) >>= \case+        HeadEStateInitial _ -> subscribeUntilHead+        alreadySubscribed -> pure alreadySubscribed+    case state of+      HeadEStateInitial _ -> error "headE in impossible HeadEStateInitial state"+      HeadEStateSubscribed subscribed -> liftIO $ do+        ticket <- WeakBag.insert sub $ headESubscribedSubscribers subscribed+        occ <- readIORef $ headESubscribedOccurrence subscribed+        pure $+          SubscribeResult+            ( EventSubscription+                { _eventSubscription_unsubscribe = do+                    WeakBag.remove ticket+                    touch ticket+                , _eventSubscription_retained = toAny stateRef+                , _eventSubscription_node = headESubscribedNode subscribed+                }+            )+            occ+      HeadEStateOccurred occRef -> do+        occ <- liftIO $ readIORef occRef+        pure $ SubscribeResult eventSubscriptionNever occ++data CacheSubscribed x a+  = CacheSubscribed+  { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))+  , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)+  , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))+  , _cacheSubscribed_nodeId :: {-# UNPACK #-} !NodeId+  }++nowSpiderEventM :: HasSpiderTimeline x => EventM x (R.Event (SpiderTimeline x) ())+nowSpiderEventM = SpiderEvent <$> now++now :: Defer (Some Clear) m => m (Event x ())+now = do+  nowOrNot <- liftIO $ newIORef $ Just ()+  scheduleClear nowOrNot+  return . Event $ \_ -> do+    SubscribeResult eventSubscriptionNever <$> (liftIO . readIORef $ nowOrNot)++-- | Construct an 'Event' whose value is guaranteed not to be recomputed+-- repeatedly+--+-- The cached primitives use cacheEventImpl and the Impl versions of the+-- uncached events, because the "push/contract" rule would rewrite the body of+-- push (@cacheEvent (pushCheap f e)@) into a call to push.+{-# NOINLINE [0] cacheEvent #-}+{-# SPECIALIZE cacheEvent :: Event Global a -> Event Global a #-}+cacheEvent :: forall x a. HasSpiderTimeline x => Event x a -> Event x a+cacheEvent = cacheEventImpl++{-# INLINE cacheEventImpl #-}+cacheEventImpl :: forall x a. HasSpiderTimeline x => Event x a -> Event x a+cacheEventImpl e =+  withStackOneLine $ \callSite -> Event $+    unsafePerformIO $ do+      mSubscribedRef :: IORef (Maybe (Weak (CacheSubscribed x a)))+        <- newIORef Nothing+      pure $ \sub ->+        {-# SCC "cacheEvent" #-}+        do+          liftIO $ printCallSite callSite+          subscribeCached mSubscribedRef "CacheSubscribed" (build mSubscribedRef) $ \subscribed -> do+            -- 'lazy' stops GHC <= 9.0 from reboxing subscribed, so that+            -- '_eventSubscription_retained' keeps the key of the weak pointer in+            -- 'mSubscribedRef' alive:+            let fields = lazy subscribed+            ticket <- liftIO $ WeakBag.insert sub $ _cacheSubscribed_subscribers fields+            occ <- liftIO $ readIORef $ _cacheSubscribed_occurrence fields+            let parentSub = _cacheSubscribed_parent fields+                -- Prevent reboxing of the unpacked _cacheSubscribed_parent on every+                -- subscribe.+                unsubscribeParent = _eventSubscription_unsubscribe parentSub+                es =+                  EventSubscription+                    { _eventSubscription_unsubscribe = do+                        WeakBag.remove ticket+                        isEmpty <- WeakBag.isEmpty $ _cacheSubscribed_subscribers fields+                        when isEmpty $ do+                          writeIORef mSubscribedRef Nothing+                          unsubscribeParent+                        touch ticket+                    , _eventSubscription_retained = toAny subscribed+                    , _eventSubscription_node = _eventSubscription_node parentSub+                    }+            pure $ SubscribeResult es occ+  where+    build mSubscribedRef = do+      nodeId <- liftIO newNodeId+      subscribers <- liftIO WeakBag.empty+      occRef <- liftIO $ newIORef Nothing -- This should never be read prior to being set below+      let checkNotReleased = checkRecordNotReleased "cacheEvent" mSubscribedRef ((== occRef) . _cacheSubscribed_occurrence)+      SubscribeResult parentSub occ <-+        subscribeAndRead e+          $ debugSubscriber ("cacheEvent" <> showNodeId' nodeId)+          $ Subscriber+            { subscriberPropagate = \a -> do+                liftIO checkNotReleased+                setOccurrence "cacheEvent" occRef a+                propagate a subscribers+            , subscriberInvalidateHeight = \old -> do+                checkNotReleased+                invalidateBagHeight subscribers old+            , subscriberRecalculateHeight = \new -> do+                checkNotReleased+                recalculateBagHeight subscribers new+            }+      for_ occ $ setOccurrence "cacheEvent" occRef+      pure $!+        CacheSubscribed+          { _cacheSubscribed_subscribers = subscribers+          , _cacheSubscribed_parent = parentSub+          , _cacheSubscribed_occurrence = occRef+          , _cacheSubscribed_nodeId = nodeId+          }++{-# INLINE subscribeCached #-}+subscribeCached+  :: IORef (Maybe (Weak r))+  -> String+  -> EventM x r+  -> (r -> EventM x (SubscribeResult x b))+  -> EventM x (SubscribeResult x b)+subscribeCached weakSubscribedRef debugNote build addSubscriber =+  liftIO (readIORef weakSubscribedRef >>= maybe (pure Nothing) deRefWeak) >>= maybe buildRecord addSubscriber+  where+    buildRecord = do+      subscribed <- build+      liftIO $ writeIORef weakSubscribedRef . Just =<< mkWeakPtrWithDebug subscribed debugNote+      addSubscriber subscribed++subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)+subscribe e s = subscribeSubscription <$> subscribeAndRead e s++-- | DEBUG_FRAME: fail if a parent notifies a released 'cacheEvent' or fan+-- record. A finalized weak pointer passes, since we can't tell which it was.+{-# INLINE checkRecordNotReleased #-}+checkRecordNotReleased :: String -> IORef (Maybe (Weak r)) -> (r -> Bool) -> IO ()+checkRecordNotReleased debugNote weakSubscribedRef isThisRecord =+  when debugFrame $ do+    released <-+      readIORef weakSubscribedRef >>= \case+        Nothing -> pure True+        Just weakCurrent -> maybe False (not . isThisRecord) <$> deRefWeak weakCurrent+    when released $ error $ debugNote <> ": a node notifies the subscriber of a released record"++eventRoot :: (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Event x a+eventRoot !k !r = Event $ liftIO . subscribeAndReadRoot k r++{-# NOINLINE neverNode #-}+neverNode :: EventNode x+neverNode = unsafePerformIO $ mkEventNode zeroHeight (pure []) (pure ["never"])++eventSubscriptionNever :: EventSubscription x+eventSubscriptionNever = EventSubscription (pure ()) (toAny ()) neverNode++subscribeAndReadNever :: EventM x (SubscribeResult x a)+subscribeAndReadNever = pure $ SubscribeResult eventSubscriptionNever Nothing++eventNever :: Event x a+eventNever = Event $ const subscribeAndReadNever++#if !MIN_VERSION_base(4,13,0)+-- | 'GHC.IORef.atomicModifyIORef'_', which base < 4.13 does not have.+atomicModifyIORef'_ :: IORef a -> (a -> a) -> IO (a, a)+atomicModifyIORef'_ ref f = atomicModifyIORef' ref $ \old -> let !new = f old in (new, (old, new))+#endif++{-# INLINE eventFan #-}+eventFan :: forall x map v a. (HasSpiderTimeline x, IsMap map) => MapKey map a -> Event x (map v) -> Fan x map v -> Event x (v a)+eventFan !k p (Fan !weakMaybeFanSubscribed) = Event $ \sub ->+  subscribeCached weakMaybeFanSubscribed "FanSubscribed" build $ \subscribed -> liftIO $ do+    let fields = lazy subscribed -- see 'cacheEventImpl' for 'lazy' reason+        subscribersRef = fanSubscribedSubscribers fields+    sub' <- evaluate sub+    -- Unlike the key map, the finalizer never changes fanSubscribedNextId, so a+    -- plain read and write are enough.+    i <- readIORef $ fanSubscribedNextId fields+    writeIORef (fanSubscribedNextId fields) $! succ i+    let removeSubscriber (FanSubscribers s) =+          let remaining = IntMap.delete i s+          in if IntMap.null remaining then Nothing else Just (FanSubscribers remaining)+    w <- mkWeakPtr sub' $ Just $ void $ atomicModifyIORef'_ subscribersRef $ mapUpdate removeSubscriber k+    let !onlySubscriber = FanSubscribers $ IntMap.singleton i w+    void $ atomicModifyIORef'_ subscribersRef $ mapInsertWith (\_ (FanSubscribers s) -> FanSubscribers $ IntMap.insert i w s) k onlySubscriber+    currentOcc <- readIORef $ fanSubscribedOccurrence fields+    let unsubscribeKey = do+          finalize w+          noKeys <- mapNull <$> readIORef subscribersRef+          when noKeys $ do+            slotSubscribed <- readIORef weakMaybeFanSubscribed >>= maybe (pure Nothing) deRefWeak+            for_ slotSubscribed $ \current -> when (fanSubscribedSubscribers current == subscribersRef) $ do+              writeIORef weakMaybeFanSubscribed Nothing+              unsubscribe $ fanSubscribedParent fields+          touch sub'+    pure $ SubscribeResult (EventSubscription unsubscribeKey (toAny subscribed) (_eventSubscription_node $ fanSubscribedParent fields)) $ mapLookup k =<< currentOcc+  where+    build = do+      nodeId <- liftIO newNodeId+      subscribersRef <- liftIO $ newIORef mapEmpty+      nextIdRef <- liftIO $ newIORef 0+      occRef <- liftIO $ newIORef Nothing+      let checkNotReleased = checkRecordNotReleased "fan" weakMaybeFanSubscribed ((== subscribersRef) . fanSubscribedSubscribers)+      SubscribeResult parentSub parentOcc <-+        subscribeAndRead p+          $ debugSubscriber ("SubscriberFan " <> showNodeId' nodeId)+          $ Subscriber+            { subscriberPropagate = \a ->+                {-# SCC "traverseFan" #-}+                do+                  liftIO checkNotReleased+                  subs <- liftIO $ readIORef subscribersRef+                  tracePropagate (Proxy :: Proxy x) $ show (mapSize subs) <> " keys subscribed, " <> show (mapSize a) <> " keys firing"+                  setOccurrence "fan" occRef a+                  mapForIntersection_ subs a $ \(FanSubscribers s) v ->+                    withIncreasedDepth (Proxy :: Proxy x) $ WeakBag.traverseWeakIntMap_ s $ \c -> subscriberPropagate c v+            , subscriberInvalidateHeight = \old -> do+                checkNotReleased+                subs <- readIORef subscribersRef+                mapFor_ subs $ \(FanSubscribers s) ->+                  WeakBag.traverseWeakIntMap_ s $ \c -> subscriberInvalidateHeight c old+            , subscriberRecalculateHeight = \new -> do+                checkNotReleased+                subs <- readIORef subscribersRef+                mapFor_ subs $ \(FanSubscribers s) ->+                  WeakBag.traverseWeakIntMap_ s $ \c -> subscriberRecalculateHeight c new+            }+      for_ parentOcc $ setOccurrence "fan" occRef+      pure $!+        FanSubscribed+          { fanSubscribedSubscribers = subscribersRef+          , fanSubscribedNextId = nextIdRef+          , fanSubscribedOccurrence = occRef+          , fanSubscribedParent = parentSub+          , fanSubscribedNodeId = nodeId+          }++eventHold :: Hold x p -> Event x p+eventHold !h = Event $ subscribeHoldEvent h++eventDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> Event x p+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub++{-# INLINE subscribeCoincidenceInner #-}++-- | Returns Maybe Height where Nothing means the height was not raised to the inner's height.+subscribeCoincidenceInner :: HasSpiderTimeline x => Event x a -> Height -> CoincidenceSubscribed x a -> EventM x (Maybe a, Maybe Height, EventNode x)+subscribeCoincidenceInner inner outerHeight subscribed = do+  SubscribeResult subscription@(EventSubscription _ _ innerSubd) innerOcc <- subscribeAndRead inner $ newSubscriberCoincidenceInner subscribed+  innerHeight <- liftIO $ getEventNodeHeight innerSubd+  let maybeRaised = raiseHeight outerHeight innerHeight+  defer $ SomeResetCoincidence subscription $ subscribed <$ maybeRaised+  return (innerOcc, maybeRaised, innerSubd)++--------------------------------------------------------------------------------+-- Subscriber+--------------------------------------------------------------------------------++data Subscriber x a = Subscriber+  { subscriberPropagate :: !(a -> EventM x ())+  , subscriberInvalidateHeight :: !(Height -> IO ())+  , subscriberRecalculateHeight :: !(Height -> IO ())+  }++{-# INLINE newSubscriberCoincidenceOuter #-}+newSubscriberCoincidenceOuter :: forall x b. HasSpiderTimeline x => CoincidenceSubscribed x b -> Subscriber x (Event x b)+newSubscriberCoincidenceOuter subscribed =+  debugSubscriber ("SubscriberCoincidenceOuter" <> showNodeId subscribed) $+    Subscriber+      { subscriberPropagate = \a ->+          {-# SCC "traverseCoincidenceOuter" #-}+          do+            outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed+            tracePropagate (Proxy :: Proxy x) $ "  outerHeight = " <> show outerHeight+            (occ, maybeRaisedToInnerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed+            tracePropagate (Proxy :: Proxy x) $ "  isJust occ = " <> show (isJust occ)+            tracePropagate (Proxy :: Proxy x) $ "  innerHeight = " <> show maybeRaisedToInnerHeight++            liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd+            scheduleClear $ coincidenceSubscribedInnerParent subscribed+            case occ of+              Nothing ->+                for_ maybeRaisedToInnerHeight $ \innerHeight -> liftIO $ do+                  -- During event propagation heights have to stay valid, so invalidate and immediately recalculate+                  -- TODO: Why not delay?+                  invalidateOwnHeight (coincidenceSubscribedHeight subscribed) (invalidateCoincidenceSubscribers subscribed)+                  recalculateOwnHeight (coincidenceSubscribedHeight subscribed) (recalculateCoincidenceSubscribers subscribed) (pure innerHeight)+              Just o ->+                -- Since it's already firing, no need to adjust height+                subscriberPropagate (coincidenceSubscribedSubscriber subscribed) o+      , subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed+      , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed+      }++{-# INLINE newSubscriberCoincidenceInner #-}+newSubscriberCoincidenceInner :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> Subscriber x a+newSubscriberCoincidenceInner subscribed =+  debugSubscriber ("SubscriberCoincidenceInner" <> showNodeId subscribed) $+    (coincidenceSubscribedSubscriber subscribed)+      { subscriberInvalidateHeight = \_ -> invalidateCoincidenceHeight subscribed+      , subscriberRecalculateHeight = \_ -> recalculateCoincidenceHeight subscribed+      }++-- Callers apply this to the 'WeakBag' only, and GHC inlines an INLINE function+-- only when it is applied to all the arguments on its left-hand side, hence+-- the lambda.+{- HLINT ignore invalidateBagHeight "Redundant lambda" -}+{-# INLINE invalidateBagHeight #-}+invalidateBagHeight :: WeakBag (Subscriber x a) -> Height -> IO ()+invalidateBagHeight subscribers = \old -> WeakBag.traverse_ subscribers $ \sub -> subscriberInvalidateHeight sub old++-- See 'invalidateBagHeight' for why this uses a lambda.+{- HLINT ignore recalculateBagHeight "Redundant lambda" -}+{-# INLINE recalculateBagHeight #-}+recalculateBagHeight :: WeakBag (Subscriber x a) -> Height -> IO ()+recalculateBagHeight subscribers = \new -> WeakBag.traverse_ subscribers $ \sub -> subscriberRecalculateHeight sub new++-- | Propagate everything at the current height+propagate :: forall x a. HasSpiderTimeline x => a -> WeakBag (Subscriber x a) -> EventM x ()+propagate a subscribers = withIncreasedDepth (Proxy :: Proxy x) $+  -- 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+  -- TODO: Should we check if nodes already have their values before propagating?  Maybe we're re-doing work+  WeakBag.traverse_ subscribers $+    \s -> subscriberPropagate s a++--------------------------------------------------------------------------------+-- EventNode+--------------------------------------------------------------------------------++toAny :: a -> Any+toAny = unsafeCoerce++-- | A node of the graph on which the height protocol operates. Not every+-- combinator is a node. A combinator such as 'cacheEvent' or 'fan' fires+-- exactly when its parent fires, so the subscriptions that it returns carry+-- the node of the parent instead of a node of its own.+data EventNode x = EventNode+  { eventNodeHeightRef :: {-# UNPACK #-} !(IORef Height)+  -- ^ The height of the node.+  , eventNodeGetParents :: !(IfDebugCycles (IO [EventNode x]))+  , eventNodeWhoCreated :: !(IfDebugCycles (IO [String]))+  }++#ifdef DEBUG_CYCLES+type IfDebugCycles a = a++{-# INLINE ifDebugCycles #-}+ifDebugCycles :: a -> IfDebugCycles a+ifDebugCycles = id+#else+type IfDebugCycles a = ()++{-# INLINE ifDebugCycles #-}+ifDebugCycles :: a -> IfDebugCycles a+ifDebugCycles _ = ()+#endif++{-# INLINE mkEventNode #-}+mkEventNode+  :: MonadIO m+  => Height+  -> IO [EventNode x]+  -> IO [String]+  -> m (EventNode x)+mkEventNode initialHeight getParents whoCreatedNode = liftIO $ do+  heightRef <- newIORef initialHeight+  pure+    EventNode+      { eventNodeHeightRef = heightRef+      , eventNodeGetParents = ifDebugCycles getParents+      , eventNodeWhoCreated = ifDebugCycles whoCreatedNode+      }++getEventNodeHeight :: EventNode x -> IO Height+getEventNodeHeight node = readIORef $ eventNodeHeightRef node++{-# INLINE eventSubscriptionHeightRef #-}+eventSubscriptionHeightRef :: EventSubscription x -> IORef Height+eventSubscriptionHeightRef = eventNodeHeightRef . _eventSubscription_node++{-# INLINE eventSubscriptionHeight #-}+eventSubscriptionHeight :: EventSubscription x -> IO Height+eventSubscriptionHeight = getEventNodeHeight . _eventSubscription_node++#ifdef DEBUG_CYCLES+walkInvalidHeightParents :: EventNode x -> IO [EventNode x]+walkInvalidHeightParents s0 = do+  traversedRef <- newIORef []+  let loop s = do+        h <- readIORef $ eventNodeHeightRef s+        when (isUnmarkedInvalidHeight h) $ do+          writeIORef (eventNodeHeightRef s) $! invalidHeightBeingTraversed+          modifyIORef' traversedRef (s :)+          mapM_ loop =<< eventNodeGetParents s+  loop s0+  subscribers <- readIORef traversedRef+  forM_ subscribers $ \s -> writeIORef (eventNodeHeightRef s) $! invalidHeight+  return subscribers+#endif++{-# INLINE subscribeHoldEvent #-}+subscribeHoldEvent :: Hold x p -> Subscriber x p -> EventM x (SubscribeResult x p)+subscribeHoldEvent h subscriber = do+  HoldLive e _ _ <- liftIO $ readIORef $ holdState h+  subscribeAndRead e subscriber++--------------------------------------------------------------------------------+-- Behavior+--------------------------------------------------------------------------------++newtype Behavior x a = Behavior {readBehaviorTracked :: BehaviorM x a}++behaviorHold :: Hold x p -> Behavior x (PatchTarget p)+behaviorHold !h = Behavior $ readHoldTracked h++-- | Unlike with hold, the Hold is the only subscriber of the input event, so+-- the rule "holdBehavior/cacheEvent" can drop a cacheEvent on it.+{-# INLINE [0] holdBehavior #-}+holdBehavior :: Defer (SomeHoldInit x) m => a -> Event x a -> m (Behavior x a)+holdBehavior v0 e = behaviorHold @_ @(Identity _) <$> hold v0 (coerce e)++behaviorConst :: a -> Behavior x a+behaviorConst !a = Behavior $ return a++behaviorPull :: Pull x a -> Behavior x a+behaviorPull !p = Behavior $ do+  val <- liftIO $ readIORef $ pullValue p+  case val of+    Just subscribed -> do+      trackRead (pullSubscribedInvalidators subscribed) $ BehaviorSubscribedPull subscribed+      liftIO $ touch $ pullSubscribedOwnInvalidator subscribed+      return $ pullSubscribedValue subscribed+    Nothing -> do+      i <- liftIO $ newInvalidatorPull p+      wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"+      parentsRef <- liftIO $ newIORef []+      !holdInits <- asks behaviorEnvHoldInits+      a <- liftIO $ runBehaviorM (pullCompute p) $ BehaviorEnv (Just wi) (Just parentsRef) holdInits+      inv0 <- maybeToList <$> asks behaviorEnvInvalidator+      invsRef <- liftIO $ newIORef $! InvalidatorList (length inv0) invalidatorPruneThreshold inv0+      parents <- liftIO $ readIORef parentsRef+      let subscribed =+            PullSubscribed+              { pullSubscribedValue = a+              , pullSubscribedInvalidators = invsRef+              , pullSubscribedOwnInvalidator = i+              , pullSubscribedParents = parents+              }+      liftIO $ writeIORef (pullValue p) $ Just subscribed+      asks behaviorEnvParents >>= mapM_ (\r -> liftIO $ modifyIORef' r (BehaviorSubscribedPull subscribed :))+      return a++behaviorDyn :: Patch p => Dyn x p -> Behavior x (PatchTarget p)+behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d++{-# INLINE readHoldTracked #-}+readHoldTracked :: Hold x p -> BehaviorM x (PatchTarget p)+readHoldTracked h = do+  result <- liftIO $ readIORef $ holdValue h+  HoldLive _ invalidators _ <- liftIO $ readIORef $ holdState h+  trackRead invalidators $ BehaviorSubscribedHold h+  liftIO $ touch h -- Otherwise, if this gets inlined enough, the hold's parent reference may get collected+  return result++{-# INLINE trackRead #-}+trackRead :: IORef (InvalidatorList x) -> SomeBehaviorSubscribed x -> BehaviorM x ()+trackRead invalidatorsRef subscribed = do+  asks behaviorEnvInvalidator >>= mapM_ (liftIO . addInvalidatorAmortized invalidatorsRef)+  asks behaviorEnvParents >>= mapM_ (\r -> liftIO $ modifyIORef' r (subscribed :))++data InvalidatorList x = InvalidatorList+  { invalidatorListSize :: !Int+  , invalidatorListPruneAt :: !Int+  , invalidatorListElems :: ![Weak (Invalidator x)]+  }++emptyInvalidatorList :: InvalidatorList x+emptyInvalidatorList =+  InvalidatorList+    { invalidatorListSize = 0+    , invalidatorListPruneAt = invalidatorPruneThreshold+    , invalidatorListElems = []+    }++-- | Add invalidator weak ref to invalidator list, pruning finalized entries+-- once the list grows to its "prune at" size.+{-# INLINE addInvalidatorAmortized #-}+addInvalidatorAmortized :: IORef (InvalidatorList x) -> Weak (Invalidator x) -> IO ()+addInvalidatorAmortized ref weakInvalidator = do+  InvalidatorList listSize pruneAt weakInvalidators <- readIORef ref+  if listSize < pruneAt+    then writeIORef ref $! InvalidatorList (listSize + 1) pruneAt (weakInvalidator : weakInvalidators)+    else do+      (liveCount, liveInvalidators) <-+        foldrM+          ( \weakInvalidator' (!liveCount, liveInvalidators) ->+              ( \case+                  Just _ -> (liveCount + 1, weakInvalidator' : liveInvalidators)+                  Nothing -> (liveCount, liveInvalidators)+              )+                <$> deRefWeak weakInvalidator'+          )+          (0, [])+          weakInvalidators+      writeIORef ref $!+        InvalidatorList+          (liveCount + 1)+          (max invalidatorPruneThreshold (2 * liveCount))+          (weakInvalidator : liveInvalidators)++invalidatorPruneThreshold :: Int+invalidatorPruneThreshold = 100++{-# INLINEABLE readBehaviorUntracked #-}+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a+readBehaviorUntracked b = do+  holdInits <- getDeferralQueue+  liftIO $ runBehaviorM (readBehaviorTracked b) $ BehaviorEnv Nothing Nothing holdInits -- TODO: Specialize readBehaviorTracked to the Nothing and Just cases++--------------------------------------------------------------------------------+-- Dynamic+--------------------------------------------------------------------------------++type DynamicS x p = Dynamic x (PatchTarget p) p++data Dynamic x target p = Dynamic+  { dynamicCurrent :: !(Behavior x target)+  , dynamicUpdated :: Event x p -- This must be lazy; see the comment on HoldState --TODO: Would this let us eliminate `Dyn`?+  }++deriving instance HasSpiderTimeline x => Functor (Dynamic x target)++dynamicHold :: Hold x p -> DynamicS x p+dynamicHold !h =+  Dynamic+    { dynamicCurrent = behaviorHold h+    , dynamicUpdated = eventHold h+    }++dynamicConst :: PatchTarget p -> DynamicS x p+dynamicConst !a =+  Dynamic+    { dynamicCurrent = behaviorConst a+    , dynamicUpdated = eventNever+    }++dynamicDyn :: (HasSpiderTimeline x, Patch p) => Dyn x p -> DynamicS x p+dynamicDyn !d =+  Dynamic+    { dynamicCurrent = behaviorDyn d+    , dynamicUpdated = eventDyn d+    }++--------------------------------------------------------------------------------+-- Combinators+--------------------------------------------------------------------------------++data Hold x p+  = Hold+  { holdValue :: !(IORef (PatchTarget p))+  , holdState :: !(IORef (HoldState x p))+  , holdNodeId :: {-# UNPACK #-} !NodeId+  }++data HoldState x p+  = -- | The subscription to the event is Nothing until the hold's init runs.+    -- The event field must stay lazy, or holds cannot be defined before their+    -- input events.+    HoldLive (Event x p) !(IORef (InvalidatorList x)) !(Maybe (EventSubscription x))++-- | A statically allocated 'SpiderTimeline'+data Global++{-# NOINLINE globalSpiderTimelineEnv #-}+globalSpiderTimelineEnv :: SpiderTimelineEnv Global+globalSpiderTimelineEnv = unsafePerformIO unsafeNewSpiderTimelineEnv++-- | Stores all global data relevant to a particular Spider timeline; only one+-- value should exist for each type @x@+newtype SpiderTimelineEnv x = STE {unSTE :: SpiderTimelineEnv' x}++-- We implement SpiderTimelineEnv with a newtype wrapper so+-- we can get the coercions we want safely.+type role SpiderTimelineEnv nominal++data SpiderTimelineEnv' x = SpiderTimelineEnv+  { _spiderTimeline_lock :: {-# UNPACK #-} !(MVar ())+  , _spiderTimeline_eventEnv :: {-# UNPACK #-} !(EventEnv x)+  , _spiderTimeline_depth :: {-# UNPACK #-} !TraceDepthRef+  }+type role SpiderTimelineEnv' phantom++instance Eq (SpiderTimelineEnv x) where+  _ == _ = True -- Since only one exists of each type++instance GEq SpiderTimelineEnv where+  a `geq` b =+    if _spiderTimeline_lock (unSTE a) == _spiderTimeline_lock (unSTE b)+      then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimelineEnv can't have two different 'x' arguments+      else Nothing++data EventEnv x+  = EventEnv+  { eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe+  , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe+  , eventEnvDynInits :: !(IORef [SomeDynInit x])+  , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])+  , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe+  , eventEnvClears :: !(IORef [Some Clear]) -- Needed for Subscribe+  , eventEnvRootClears :: !(IORef [Some RootClear])+  , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe+  , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe+  , eventEnvPendingRecalculations :: !(IORef [SomeRecalculateHeight x])+  , eventEnvDelayedMerges :: !(IORef (HeightQueue (EventM x ())))+  }++{-# INLINE runEventM #-}+runEventM :: EventM x a -> IO a+runEventM = unEventM++{-# INLINE spiderEventEnv #-}+spiderEventEnv :: forall x. HasSpiderTimeline x => EventEnv x+spiderEventEnv = _spiderTimeline_eventEnv (unSTE (spiderTimeline :: SpiderTimelineEnv x))++asksEventEnv :: forall x a. HasSpiderTimeline x => (EventEnv x -> a) -> EventM x a+asksEventEnv f = pure $ f $ spiderEventEnv @x++class MonadIO m => Defer a m where+  getDeferralQueue :: m (IORef [a])++{-# INLINE defer #-}+defer :: Defer a m => a -> m ()+defer a = do+  q <- getDeferralQueue+  liftIO $ modifyIORef' q (a :)++instance HasSpiderTimeline x => Defer (SomeAssignment x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvAssignments++instance HasSpiderTimeline x => Defer (SomeHoldInit x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvHoldInits++instance HasSpiderTimeline x => Defer (SomeDynInit x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvDynInits++instance Defer (SomeHoldInit x) (BehaviorM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asks behaviorEnvHoldInits++instance HasSpiderTimeline x => Defer (SomeMergeUpdate x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvMergeUpdates++instance HasSpiderTimeline x => Defer (SomeMergeInit x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvMergeInits++{-# INLINE getCurrentHeight #-}+getCurrentHeight :: HasSpiderTimeline x => EventM x Height+getCurrentHeight = do+  heightRef <- asksEventEnv eventEnvCurrentHeight+  liftIO $ readIORef heightRef++{-# INLINE scheduleMerge #-}+scheduleMerge :: HasSpiderTimeline x => Height -> EventM x () -> EventM x ()+scheduleMerge height subscribed = do+  delayedRef <- asksEventEnv eventEnvDelayedMerges+  liftIO $ modifyIORef' delayedRef $ heightQueueInsert height subscribed++class HasSpiderTimeline x where+  -- | Retrieve the current SpiderTimelineEnv+  spiderTimeline :: SpiderTimelineEnv x++instance HasSpiderTimeline Global where+  spiderTimeline = globalSpiderTimelineEnv++putCurrentHeight :: HasSpiderTimeline x => Height -> EventM x ()+putCurrentHeight h = do+  heightRef <- asksEventEnv eventEnvCurrentHeight+  liftIO $ writeIORef heightRef $! h++instance HasSpiderTimeline x => Defer (Some Clear) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvClears++{-# INLINE scheduleClear #-}+scheduleClear :: Defer (Some Clear) m => IORef (Maybe a) -> m ()+scheduleClear r = defer $ Some $ Clear r++{-# INLINE setOccurrence #-}+setOccurrence :: HasSpiderTimeline x => String -> IORef (Maybe a) -> a -> EventM x ()+setOccurrence nodeName occRef a = do+  when debugFrame+    $ liftIO+    $ readIORef occRef >>= debugOccurrence (nodeName <> ": two occurrences in one frame")+  liftIO $ writeIORef occRef $ Just a+  scheduleClear occRef++instance HasSpiderTimeline x => Defer (Some RootClear) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvRootClears++{-# INLINE scheduleRootClear #-}+scheduleRootClear :: Defer (Some RootClear) m => IORef (DMap k Identity) -> m ()+scheduleRootClear r = defer $ Some $ RootClear r++instance HasSpiderTimeline x => Defer (SomeResetCoincidence x) (EventM x) where+  {-# INLINE getDeferralQueue #-}+  getDeferralQueue = asksEventEnv eventEnvResetCoincidences++-- Note: hold cannot examine its event until after the phase is over+{-# INLINE [1] hold #-}+hold :: (Patch p, Defer (SomeHoldInit x) m) => PatchTarget p -> Event x p -> m (Hold x p)+hold v0 e = do+  valRef <- liftIO $ newIORef v0+  invsRef <- liftIO $ newIORef emptyInvalidatorList+  stateRef <- liftIO $ newIORef $ HoldLive e invsRef Nothing+  nodeId <- liftIO newNodeId+  let h =+        Hold+          { holdValue = valRef+          , holdState = stateRef+          , holdNodeId = nodeId+          }+  defer $ SomeHoldInit h+  return h++data BehaviorEnv x = BehaviorEnv+  { behaviorEnvInvalidator :: !(Maybe (Weak (Invalidator x)))+  , behaviorEnvParents :: !(Maybe (IORef [SomeBehaviorSubscribed x]))+  , behaviorEnvHoldInits :: IORef [SomeHoldInit x]+  }++-- BehaviorM can sample behaviors+newtype BehaviorM x a = BehaviorM {unBehaviorM :: ReaderIO (BehaviorEnv x) a}+  deriving (Applicative, Functor, MonadFix, MonadIO, MonadReader (BehaviorEnv x))++instance Monad (BehaviorM x) where+  {-# INLINE (>>=) #-}+  BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f+#if !MIN_VERSION_base(4,13,0)+  {-# INLINE fail #-}+  fail s = BehaviorM $ fail s+#endif++data SomeBehaviorSubscribed x+  = forall p. BehaviorSubscribedHold (Hold x p)+  | forall a. BehaviorSubscribedPull (PullSubscribed x a)++data PullSubscribed x a+  = PullSubscribed+  { pullSubscribedValue :: !a+  , pullSubscribedInvalidators :: !(IORef (InvalidatorList x))+  , pullSubscribedOwnInvalidator :: !(Invalidator x)+  , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated+  }++data Pull x a+  = Pull+  { pullValue :: !(IORef (Maybe (PullSubscribed x a)))+  , pullCompute :: !(BehaviorM x a)+  , pullNodeId :: {-# UNPACK #-} !NodeId+  }++data Invalidator x+  = forall a. InvalidatorPull (Pull x a)+  | forall a. InvalidatorSwitch (SwitchSubscribed x a)++data RootSubscribed x a = RootSubscribed+  { rootSubscribedSubscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))+  , rootSubscribedNodeId :: {-# UNPACK #-} !NodeId+  }++data RootKey x a = RootKey+  { rootKeySubscribed :: {-# UNPACK #-} !(Weak (RootSubscribed x a))+  , rootKeyTeardown :: {-# UNPACK #-} !(MVar (Maybe (IO ())))+  }++data Root x k+  = Root+  { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event+  , rootSubscribed :: !(IORef (DMap k (RootKey x)))+  , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))+  , rootNode :: {-# NOUNPACK #-} !(EventNode x)+  }++data SomeHoldInit x = forall p. Patch p => SomeHoldInit !(Hold x p)++data SomeDynInit x = forall p. Patch p => SomeDynInit !(Dyn x p)++data SomeMergeUpdate x = SomeMergeUpdate+  { _someMergeUpdate_update :: !(EventM x [EventSubscription x])+  , _someMergeUpdate_invalidateHeight :: !(IO ())+  , _someMergeUpdate_recalculateHeight :: !(IO ())+  }++newtype SomeMergeInit x = SomeMergeInit {unSomeMergeInit :: EventM x ()}++-- EventM can do everything BehaviorM can, plus create holds+newtype EventM x a = EventM {unEventM :: IO a}+  deriving (Applicative, Functor, Monad, MonadAsyncException, MonadCatch, MonadException, MonadFix, MonadIO, MonadMask, MonadThrow)++newtype MergeSubscribedParent x a = MergeSubscribedParent {unMergeSubscribedParent :: EventSubscription x}++data MergeSubscribedParentWithMove x k a = MergeSubscribedParentWithMove+  { _mergeSubscribedParentWithMove_subscription :: !(EventSubscription x)+  , _mergeSubscribedParentWithMove_key :: !(IORef (k a))+  }++class IsMap (map :: (i -> Type) -> Type) where+  type MapKey map :: i -> Type+  mapEmpty :: map v+  mapNull :: map v -> Bool+  mapSize :: map v -> Int+  mapLookup :: MapKey map a -> map v -> Maybe (v a)+  mapInsert :: MapKey map a -> v a -> map v -> map v+  mapInsertLookup :: MapKey map a -> v a -> map v -> (Maybe (v a), map v)+  mapDeleteLookup :: MapKey map a -> map v -> (Maybe (v a), map v)+  mapInsertWith :: (v a -> v a -> v a) -> MapKey map a -> v a -> map v -> map v+  mapUpdate :: (v a -> Maybe (v a)) -> MapKey map a -> map v -> map v+  mapForIntersection_ :: Monad m => map v -> map w -> (forall a. v a -> w a -> m ()) -> m ()+  mapFor_ :: Monad m => map v -> (forall a. v a -> m ()) -> m ()+  mapToList :: map v -> [DSum (MapKey map) v]+  mapFromDistinctAscList :: [DSum (MapKey map) v] -> map v++instance GCompare k => IsMap (DMap k) where+  type MapKey (DMap k) = k+  mapEmpty = DMap.empty+  mapNull = DMap.null+  mapSize = DMap.size+  mapLookup = DMap.lookup+  mapInsert = DMap.insert+  mapInsertLookup k v m = (DMap.lookup k m, DMap.insert k v m)+  mapDeleteLookup k m = (DMap.lookup k m, DMap.delete k m)+  mapInsertWith = DMap.insertWith'+  mapUpdate = DMap.update+  mapForIntersection_ left right f =+    DMap.foldrWithKey (\_ (Pair v w) rest -> f v w >> rest) (pure ()) $+      DMap.intersectionWithKey (const Pair) left right+  mapFor_ m f = DMap.foldrWithKey (\_ v rest -> f v >> rest) (pure ()) m+  mapToList = DMap.toList+  mapFromDistinctAscList = DMap.fromDistinctAscList++newtype IntMapOf a v = IntMapOf (IntMap (v a))++instance IsMap (IntMapOf a) where+  type MapKey (IntMapOf a) = Const2 Int a+  mapEmpty = IntMapOf IntMap.empty+  mapNull (IntMapOf m) = IntMap.null m+  mapSize (IntMapOf m) = IntMap.size m+  mapLookup (Const2 k) (IntMapOf m) = IntMap.lookup k m+  mapInsert (Const2 k) v (IntMapOf m) = IntMapOf $ IntMap.insert k v m+  mapInsertLookup (Const2 k) v (IntMapOf m) = IntMapOf <$> IntMap.insertLookupWithKey (\_ new _ -> new) k v m+  mapDeleteLookup (Const2 k) (IntMapOf m) = IntMapOf <$> IntMap.updateLookupWithKey (\_ _ -> Nothing) k m+  mapInsertWith f (Const2 k) v (IntMapOf m) = IntMapOf $ IntMap.insertWith f k v m+  mapUpdate f (Const2 k) (IntMapOf m) = IntMapOf $ IntMap.update f k m+  mapForIntersection_ (IntMapOf left) (IntMapOf right) f = traverse_ (uncurry f) $ IntMap.intersectionWith (,) left right+  mapFor_ (IntMapOf m) f = traverse_ f m+  mapToList (IntMapOf m) = (\(k, v) -> Const2 k :=> v) <$> IntMap.toList m+  mapFromDistinctAscList entries = IntMapOf $ IntMap.fromDistinctAscList $ fmap toPair entries+    where+      toPair :: forall b w. DSum (Const2 Int b) w -> (Int, w b)+      toPair (Const2 k :=> v) = (k, v)++newtype FanSubscribers x v a = FanSubscribers (IntMap (Weak (Subscriber x (v a))))++newtype Fan x map v = Fan (IORef (Maybe (Weak (FanSubscribed x map v))))++-- We don't re-use WeakBag in Fan so that we can get atomic modification of the entire 'fanSubscribedSubscribers':+data FanSubscribed x map v = FanSubscribed+  { fanSubscribedSubscribers :: {-# UNPACK #-} !(IORef (map (FanSubscribers x v)))+  , fanSubscribedNextId :: {-# UNPACK #-} !(IORef Int)+  , fanSubscribedOccurrence :: {-# UNPACK #-} !(IORef (Maybe (map v)))+  , fanSubscribedParent :: {-# UNPACK #-} !(EventSubscription x)+  , fanSubscribedNodeId :: {-# UNPACK #-} !NodeId+  }++{-# INLINE newFan #-}+newFan :: IO (Fan x map v)+newFan = Fan <$> newIORef Nothing++data SwitchSubscribed x a+  = SwitchSubscribed+  { switchSubscribedNode :: {-# NOUNPACK #-} !(EventNode x)+  , switchSubscribedSubscriber :: !(Subscriber x a)+  , switchSubscribedOwnInvalidator :: !(IORef (Invalidator x))+  , switchSubscribedState :: !(IORef (SwitchState x a))+  , switchSubscribedNodeId :: {-# UNPACK #-} !NodeId+  }++switchSubscribedHeight :: SwitchSubscribed x a -> IORef Height+switchSubscribedHeight = eventNodeHeightRef . switchSubscribedNode++data SwitchState x a+  = SwitchLive !(Behavior x (Event x a)) !(IORef [SomeBehaviorSubscribed x]) !(Weak (Invalidator x)) !(EventSubscription x)+  | SwitchParentUnsubscribed++data CoincidenceSubscribed x a+  = CoincidenceSubscribed+  { coincidenceSubscribedNode :: {-# NOUNPACK #-} !(EventNode x)+  , coincidenceSubscribedSubscriber :: !(Subscriber x a)+  , coincidenceSubscribedOuterParent :: !(IORef (Maybe (EventSubscription x)))+  -- ^ Nothing once unsubscribed.+  , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventNode x)))+  , coincidenceSubscribedNodeId :: {-# UNPACK #-} !NodeId+  }++coincidenceSubscribedHeight :: CoincidenceSubscribed x a -> IORef Height+coincidenceSubscribedHeight = eventNodeHeightRef . coincidenceSubscribedNode++{-# NOINLINE newInvalidatorSwitch #-}+newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)+newInvalidatorSwitch subd = return $! InvalidatorSwitch subd++{-# NOINLINE newInvalidatorPull #-}+newInvalidatorPull :: Pull x a -> IO (Invalidator x)+newInvalidatorPull p = return $! InvalidatorPull p++instance HasSpiderTimeline x => Filterable (Event x) where+  mapMaybe f = push $ return . f++instance HasSpiderTimeline x => Align (Event x) where+  nil = eventNever+#if !MIN_VERSION_these(0, 8, 0)+  align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $+     DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]+#endif++#if MIN_VERSION_these(0, 8, 0)+instance HasSpiderTimeline x => Semialign (Event x) where+  align ea eb = mapMaybe dmapToThese $ mergeG coerce $ dynamicConst $+     DMap.fromDistinctAscList [LeftTag :=> ea, RightTag :=> eb]+#ifdef MIN_VERSION_semialign+#if !MIN_VERSION_semialign(1,1,0)+  zip x y = mapMaybe justThese $ align x y+#endif+#endif+#endif++#ifdef MIN_VERSION_semialign+#if MIN_VERSION_semialign(1,1,0)+instance HasSpiderTimeline x => Zip (Event x) where+  zip x y = mapMaybe justThese $ align x y+#endif+#endif++data DynType x p+  = UnsafeDyn !(BehaviorM x (PatchTarget p), Event x p)+  | BuildDyn !(EventM x (PatchTarget p), Event x p)+  | HoldDyn {-# NOUNPACK #-} !(Hold x p)++newtype Dyn (x :: Type) p = Dyn {unDyn :: IORef (DynType x p)}++newMapDyn :: HasSpiderTimeline x => (a -> b) -> DynamicS x (Identity a) -> DynamicS x (Identity b)+newMapDyn f d = dynamicDyn $ unsafeBuildDynamic (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)++-- TODO: Avoid the duplication between this and R.zipDynWith+zipDynWith :: HasSpiderTimeline x => (a -> b -> c) -> DynamicS x (Identity a) -> DynamicS x (Identity b) -> DynamicS x (Identity c)+zipDynWith f da db =+  let eab = align (dynamicUpdated da) (dynamicUpdated db)+      ec = flip push eab $ \o -> do+        (a, b) <- case o of+          This (Identity a) -> do+            b <- readBehaviorUntracked $ dynamicCurrent db+            return (a, b)+          That (Identity b) -> do+            a <- readBehaviorUntracked $ dynamicCurrent da+            return (a, b)+          These (Identity a) (Identity b) -> return (a, b)+        return $ Just $ Identity $ f a b+  in dynamicDyn $ unsafeBuildDynamic (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec++buildDynamic :: (Defer (SomeDynInit x) m, Patch p) => EventM x (PatchTarget p) -> Event x p -> m (Dyn x p)+buildDynamic readV0 v' = do+  result <- liftIO $ newIORef $ BuildDyn (readV0, v')+  let !d = Dyn result+  defer $ SomeDynInit d+  return d++unsafeBuildDynamic :: BehaviorM x (PatchTarget p) -> Event x p -> Dyn x p+unsafeBuildDynamic readV0 v' =+  Dyn $ unsafePerformIO $ newIORef $ UnsafeDyn (readV0, v')++instance HasSpiderTimeline x => Functor (Event x) where+  fmap f = push $ return . Just . f++instance Functor (Behavior x) where+  fmap f = pull . fmap f . readBehaviorTracked++-- | See the comment at cacheEvent for why this is not+-- @cacheEvent (pushCheap f e)@.+{-# NOINLINE [0] push #-}+{-# SPECIALIZE push :: (a -> EventM Global (Maybe b)) -> Event Global a -> Event Global b #-}+push :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Event x a -> Event x b+push f e = cacheEventImpl (pushCheapImpl f e)++{-# NOINLINE [0] pushSwitch #-}+{-# SPECIALIZE pushSwitch :: (a -> EventM Global (Maybe b)) -> Behavior Global (Event Global a) -> Event Global b #-}+pushSwitch :: HasSpiderTimeline x => (a -> EventM x (Maybe b)) -> Behavior x (Event x a) -> Event x b+pushSwitch f b = cacheEventImpl (pushCheapImpl f (switchUncachedImpl b))++{-# NOINLINE [0] pushCoincidence #-}+{-# SPECIALIZE pushCoincidence :: (a -> EventM Global (Maybe c)) -> Event Global (R.Event (SpiderTimeline Global) a) -> Event Global c #-}+pushCoincidence :: HasSpiderTimeline x => (a -> EventM x (Maybe c)) -> Event x (R.Event (SpiderTimeline x) a) -> Event x c+pushCoincidence f e = cacheEventImpl (pushCheapImpl f (coincidenceUncachedImpl e))++{-# NOINLINE [0] pushMergeInt #-}+{-# SPECIALIZE pushMergeInt :: (IntMap a -> EventM Global (Maybe b)) -> DynamicS Global (PatchIntMap (Event Global a)) -> Event Global b #-}+pushMergeInt :: HasSpiderTimeline x => (IntMap a -> EventM x (Maybe b)) -> DynamicS x (PatchIntMap (Event x a)) -> Event x b+pushMergeInt f d = cacheEventImpl (pushCheapImpl f (mergeIntCheapImpl d))++{-# INLINE [0] pushMergeG #-}+pushMergeG+  :: forall k q x v c+   . (HasSpiderTimeline x, GCompare k)+  => (DMap k v -> EventM x (Maybe c))+  -> (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMap k q)+  -> Event x c+pushMergeG f nt d = cacheEventImpl (pushCheapImpl f (mergeCheapImpl nt d))++{-# INLINE [0] pushMergeWithMove #-}+pushMergeWithMove+  :: forall k q x v c+   . (HasSpiderTimeline x, GCompare k)+  => (DMap k v -> EventM x (Maybe c))+  -> (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMapWithMove k q)+  -> Event x c+pushMergeWithMove f nt d = cacheEventImpl (pushCheapImpl f (mergeCheapWithMoveImpl nt d))++{-# INLINEABLE pull #-}+pull :: BehaviorM x a -> Behavior x a+pull a = unsafePerformIO $ do+  ref <- newIORef Nothing+  nid <- newNodeId+  pure+    $ behaviorPull+    $ Pull+      { pullCompute = a+      , pullValue = ref+      , pullNodeId = nid+      }++{-# NOINLINE [0] switch #-}+{-# SPECIALIZE switch :: Behavior Global (Event Global a) -> Event Global a #-}+switch :: HasSpiderTimeline x => Behavior x (Event x a) -> Event x a+switch b = cacheEventImpl (switchUncachedImpl b)++{-# NOINLINE [0] switchUncached #-}+{-# SPECIALIZE switchUncached :: Behavior Global (Event Global a) -> Event Global a #-}+switchUncached :: forall x a. HasSpiderTimeline x => Behavior x (Event x a) -> Event x a+switchUncached = switchUncachedImpl++{-# INLINE switchUncachedImpl #-}+switchUncachedImpl :: forall x a. HasSpiderTimeline x => Behavior x (Event x a) -> Event x a+switchUncachedImpl b = Event $ \sub -> do+  stateRef <- liftIO $ newIORef $ error "switchUncached: current parent not yet subscribed"+  node <-+    mkEventNode+      (error "switchUncached: height not yet known")+      ( readIORef stateRef >>= \case+          SwitchLive _ _ _ parent -> pure [_eventSubscription_node parent]+          SwitchParentUnsubscribed -> pure []+      )+      (whoCreatedIORef stateRef)+  let heightRef = eventNodeHeightRef node+  invalidatorRef <- liftIO $ newIORef $ error "switchUncached: invalidator not yet created"+  readSetRef <- liftIO $ newIORef [] -- TODO: This should be unnecessary, because it will always be filled with just the single parent behavior+  nid <- liftIO newNodeId+  let !subscribed =+        SwitchSubscribed+          { switchSubscribedNode = node+          , switchSubscribedSubscriber =+              debugSubscriber ("SubscriberSwitch" <> showNodeId subscribed) $+                ownHeightSubscriber heightRef (subscriberInvalidateHeight sub) (subscriberRecalculateHeight sub) (subscriberPropagate sub)+          , switchSubscribedOwnInvalidator = invalidatorRef+          , switchSubscribedState = stateRef+          , switchSubscribedNodeId = nid+          }+  liftIO $ writeIORef invalidatorRef =<< newInvalidatorSwitch subscribed+  holdInits <- getDeferralQueue+  SubscribeResult subscription parentOcc <- liftIO $+    subscribeSwitchCurrentParent subscribed b readSetRef holdInits $+      \parent subscriber -> runEventM $ subscribeAndRead parent subscriber+  liftIO $ writeIORef heightRef =<< eventSubscriptionHeight subscription+  pure $+    SubscribeResult+      ( EventSubscription+          { _eventSubscription_unsubscribe = do+              readIORef stateRef >>= \case+                SwitchLive _ _ weakInvalidator parent -> do+                  unsubscribe parent+                  finalize weakInvalidator+                SwitchParentUnsubscribed -> pure ()+              writeIORef stateRef SwitchParentUnsubscribed+          , _eventSubscription_retained = toAny subscribed+          , _eventSubscription_node = node+          }+      )+      parentOcc++{-# INLINE subscribeSwitchCurrentParent #-}+subscribeSwitchCurrentParent+  :: SwitchSubscribed x a+  -> Behavior x (Event x a)+  -> IORef [SomeBehaviorSubscribed x]+  -> IORef [SomeHoldInit x]+  -> (Event x a -> Subscriber x a -> IO (SubscribeResult x a))+  -> IO (SubscribeResult x a)+subscribeSwitchCurrentParent subscribed parentBehavior readSetRef holdInits subscribeToParent = do+  i <- readIORef $ switchSubscribedOwnInvalidator subscribed+  wi <- mkWeakPtrWithDebug i "InvalidatorSwitch"+  e <-+    runBehaviorM (readBehaviorTracked parentBehavior) $+      BehaviorEnv (Just wi) (Just readSetRef) holdInits+  result <- subscribeToParent e $ switchSubscribedSubscriber subscribed+  writeIORef (switchSubscribedState subscribed) $! SwitchLive parentBehavior readSetRef wi $ subscribeSubscription result+  pure result++-- The inner events on coincidence have the type of the Reflex instance, so that+-- the instance passes the outer event to coincidence without a coerce: the+-- rules that drop a cacheEvent on the outer event don't match through a cast.+{-# NOINLINE [0] coincidence #-}+{-# SPECIALIZE coincidence :: Event Global (R.Event (SpiderTimeline Global) a) -> Event Global a #-}+coincidence :: HasSpiderTimeline x => Event x (R.Event (SpiderTimeline x) a) -> Event x a+coincidence e = cacheEventImpl (coincidenceUncachedImpl e)++{-# NOINLINE [0] coincidenceUncached #-}+{-# SPECIALIZE coincidenceUncached :: Event Global (R.Event (SpiderTimeline Global) a) -> Event Global a #-}+coincidenceUncached :: forall x a. HasSpiderTimeline x => Event x (R.Event (SpiderTimeline x) a) -> Event x a+coincidenceUncached = coincidenceUncachedImpl++{-# INLINE coincidenceUncachedImpl #-}+coincidenceUncachedImpl :: forall x a. HasSpiderTimeline x => Event x (R.Event (SpiderTimeline x) a) -> Event x a+coincidenceUncachedImpl outer = Event $ \sub -> do+  outerParentRef <- liftIO $ newIORef $ error "coincidenceUncached: outer parent not yet subscribed"+  innerParentRef <- liftIO $ newIORef Nothing+  node <-+    mkEventNode+      (error "coincidenceUncached: height not yet known")+      ( do+          outerParents <- maybeToList . fmap _eventSubscription_node <$> readIORef outerParentRef+          innerParents <- maybeToList <$> readIORef innerParentRef+          pure $ outerParents <> innerParents+      )+      (whoCreatedIORef outerParentRef)+  let heightRef = eventNodeHeightRef node+  nid <- liftIO newNodeId+  let !subscribed =+        CoincidenceSubscribed+          { coincidenceSubscribedNode = node+          , coincidenceSubscribedSubscriber = sub+          , coincidenceSubscribedOuterParent = outerParentRef+          , coincidenceSubscribedInnerParent = innerParentRef+          , coincidenceSubscribedNodeId = nid+          }+  SubscribeResult outerSubscription outerOcc <- subscribeAndRead outer $ coerce $ newSubscriberCoincidenceOuter subscribed+  liftIO $ writeIORef outerParentRef $ Just outerSubscription+  outerHeight <- liftIO $ eventSubscriptionHeight outerSubscription+  (occ, height, mInnerSubd) <- case outerOcc of+    Nothing -> return (Nothing, outerHeight, Nothing)+    Just o -> do+      (occ, maybeRaisedToInnerHeight, innerSubd) <- subscribeCoincidenceInner (unSpiderEvent o) outerHeight subscribed+      return (occ, fromMaybe outerHeight maybeRaisedToInnerHeight, Just innerSubd)+  liftIO $ writeIORef heightRef $! height+  liftIO $ writeIORef innerParentRef mInnerSubd+  when (isJust mInnerSubd) $ scheduleClear innerParentRef+  pure $+    SubscribeResult+      ( EventSubscription+          { _eventSubscription_unsubscribe =+              readIORef outerParentRef >>= \case+                Just subscription -> do+                  unsubscribe subscription+                  writeIORef outerParentRef Nothing+                -- A subscription is unsubscribed at most once.+                Nothing -> error "coincidence: unsubscribe from an unsubscribed coincidence"+          , _eventSubscription_retained = toAny subscribed+          , _eventSubscription_node = node+          }+      )+      occ++-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors+run :: forall x b. HasSpiderTimeline x => [DSum (RootTrigger x) Identity] -> EventM x b -> SpiderHost x b+run roots after = do+  tracePropagate (Proxy :: Proxy x) $ "Running an event frame with " <> show (length roots) <> " events"+  let t = spiderTimeline :: SpiderTimelineEnv x+  result <- SpiderHost $ withMVar (_spiderTimeline_lock (unSTE t)) $ \_ -> unSpiderHost $ runFrame $ do+    forM_ roots $ \(RootTrigger (_, occRef, k) :=> a) -> do+      occBefore <- liftIO $ do+        occBefore <- readIORef occRef+        when debugFrame+          $ debugOccurrence "run: one trigger fired twice in one frame"+          $ DMap.lookup k occBefore+        writeIORef occRef $! DMap.insert k a occBefore+        return occBefore+      when (DMap.null occBefore) $ scheduleRootClear occRef+    forM_ roots $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) ->+      propagate a subscribersRef+    delayedRef <- asksEventEnv eventEnvDelayedMerges+    let go = do+          delayed <- liftIO $ readIORef delayedRef+          case heightQueueNext delayed of+            Nothing -> return ()+            Just (currentHeight, cur, future) -> do+              tracePropagate (Proxy :: Proxy x) $ "Running height " <> show currentHeight+              putCurrentHeight currentHeight+              liftIO $ writeIORef delayedRef $! future+              sequence_ cur+              go+    go+    putCurrentHeight maxHeight+    after+  tracePropagate (Proxy :: Proxy x) "Done running an event frame"+  return result++newtype Clear a = Clear (IORef (Maybe a))++newtype RootClear k = RootClear (IORef (DMap k Identity))++data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef (InvalidatorList x)) a++debugFinalize :: Bool+debugFinalize = False++mkWeakPtrWithDebug :: a -> String -> IO (Weak a)+mkWeakPtrWithDebug x debugNote = do+  x' <- evaluate x+  mkWeakPtr x' $+    if debugFinalize+      then Just $ debugStrLn $ "finalizing: " <> debugNote+      else Nothing++type CanTrace x m = (HasSpiderTimeline x, MonadIO m)++#ifdef DEBUG++debugSubscriber :: forall x a. HasSpiderTimeline x => String -> Subscriber x a -> Subscriber x a+debugSubscriber description subscribed = Subscriber+  {+    subscriberPropagate = \m -> do+      tracePropagate (Proxy :: Proxy x) ("subscriberPropagate: " <> description)+      subscriberPropagate subscribed m+  , subscriberInvalidateHeight = \old -> do+      traceInvalidateHeight $ "subscriberInvalidateHeight: " <> description <> ", old = " <> show old+      subscriberInvalidateHeight subscribed old+      traceInvalidateHeight $ "subscriberInvalidateHeight: " <> description <> ", done"+  , subscriberRecalculateHeight = \new -> do+      traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", new = " <> show new+      subscriberRecalculateHeight subscribed new+      traceInvalidateHeight $ "subscriberRecalculateHeight: " <> description <> ", done"+  }+++{-# INLINE withIncreasedDepth #-}+withIncreasedDepth :: forall proxy x m a. CanTrace x m => proxy x -> m a -> m a+withIncreasedDepth _ a = do+  liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) succ+  result <- a+  liftIO $ modifyIORef' (_spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)) pred+  return result++{-# INLINE tracePropagate #-}+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()+tracePropagate p = when debugPropagate . trace p++{-# INLINE traceInvalidate #-}+traceInvalidate :: String -> IO ()+traceInvalidate = when debugInvalidate . liftIO . debugStrLn++{-# INLINE traceInvalidateHeight #-}+traceInvalidateHeight :: String -> IO ()+traceInvalidateHeight = when debugInvalidateHeight . liftIO . debugStrLn++{-# INLINE trace #-}+trace :: (CanTrace x m) => proxy x ->  String -> m ()+trace p message = traceM p $ return message++{-# INLINE traceM #-}+traceM :: forall x proxy m. (CanTrace x m) => proxy x -> m String -> m ()+traceM _ getMessage = do+  message <- getMessage+  d <- liftIO $ readIORef $ _spiderTimeline_depth $ unSTE (spiderTimeline :: SpiderTimelineEnv x)+  liftIO $ debugStrLn $ replicate d ' ' <> message++#else++{-# INLINE withIncreasedDepth #-}+withIncreasedDepth ::  proxy x -> m a -> m a+withIncreasedDepth _ = id++{-# INLINE tracePropagate #-}+tracePropagate :: (CanTrace x m) => proxy x -> String -> m ()+tracePropagate _ _ = return ()++{-# INLINE traceInvalidate #-}+traceInvalidate :: String -> IO ()+traceInvalidate _ = return ()++{-# INLINE traceInvalidateHeight #-}+traceInvalidateHeight :: String -> IO ()+traceInvalidateHeight _ = return ()++{-# INLINE debugSubscriber #-}+debugSubscriber :: String -> Subscriber x a -> Subscriber x a+debugSubscriber _ = id++++{-# INLINE trace #-}+trace :: (CanTrace x m) => proxy x ->  String -> m ()+trace _ _ = return ()++{-# INLINE traceM #-}+traceM :: (CanTrace x m) => proxy x -> m String -> m ()+traceM _ _ = return ()++#endif++whoCreatedIORef :: IORef a -> IO [String]+whoCreatedIORef (IORef a) = whoCreated $! a++groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]+groupByHead = \case+  [] -> []+  (x :| xs) : t -> case groupByHead t of+    [] -> [(x, xs :| [])]+    l@((y, yss) : t')+      | x == y -> (x, xs `NonEmpty.cons` yss) : t'+      | otherwise -> (x, xs :| []) : l++listsToForest :: Eq a => [[a]] -> Forest a+listsToForest lists = buildForest <$> groupByHead (mapMaybe nonEmpty lists)+  where+    buildForest (a, lists') = Node a $ listsToForest $ toList lists'++showStacks :: [[String]] -> String+showStacks = drawForest . listsToForest . fmap (filterStack "Reflex.Spider.Internal")++filterStack :: String -> [String] -> [String]+#ifdef DEBUG_HIDE_INTERNALS+filterStack prefix = filter (not . (prefix `isPrefixOf`))+#else+filterStack _prefix = id+#endif++#ifdef DEBUG_CYCLES++newtype EventLoopException = EventLoopException [[String]]+instance Exception EventLoopException++instance Show EventLoopException where+  show (EventLoopException stacks) = "causality loop detected:\n" <> if all null stacks+    then "no location information, compile with profiling enabled for stack tree"+    else showStacks stacks++throwEventLoopException :: EventNode x -> IO a+throwEventLoopException subscribed = do+  nodesInvolvedInCycle <- walkInvalidHeightParents subscribed+  stacks <- forM nodesInvolvedInCycle eventNodeWhoCreated+  throwIO (EventLoopException stacks)++#else++data EventLoopException = EventLoopException+instance Exception EventLoopException++instance Show EventLoopException where+  show EventLoopException = "causality loop detected: \n" <>+    "compile reflex with flag 'debug-cycles' and compile with profiling enabled for stack tree"++throwEventLoopException :: EventNode x -> IO a+throwEventLoopException _ = throwIO EventLoopException++#endif++-- | 'CoincidenceSubscribed' is present only when the coincidence raised its height while subscribing to the inner event.+data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a))++data SomeRaisedCoincidence x = forall a. SomeRaisedCoincidence (CoincidenceSubscribed x a)++newtype SomeRecalculateHeight x = SomeRecalculateHeight (IO ())++runBehaviorM :: BehaviorM x a -> BehaviorEnv x -> IO a+runBehaviorM a = runReaderIO (unBehaviorM a)++{-# INLINE getDynHold #-}+getDynHold :: (Defer (SomeHoldInit x) m, Patch p) => Dyn x p -> m (Hold x p)+getDynHold d = do+  mh <- liftIO $ readIORef $ unDyn d+  case mh of+    HoldDyn h -> return h+    UnsafeDyn (readV0, v') -> do+      holdInits <- getDeferralQueue+      v0 <- liftIO $ runBehaviorM readV0 $ BehaviorEnv Nothing Nothing holdInits+      hold' v0 v'+    BuildDyn (readV0, v') -> do+      v0 <- liftIO $ runEventM readV0+      hold' v0 v'+  where+    hold' v0 v' = do+      h <- hold v0 v'+      liftIO $ writeIORef (unDyn d) $ HoldDyn h+      return h++subscribeAndReadRoot :: forall k x a. (GCompare k, HasSpiderTimeline x) => k a -> Root x k -> Subscriber x a -> IO (SubscribeResult x a)+subscribeAndReadRoot k r sub = do+  entry <- DMap.lookup k <$> readIORef (rootSubscribed r)+  live <- case entry of+    Just RootKey {rootKeySubscribed = w} -> fmap (w,) <$> deRefWeak w+    Nothing -> pure Nothing+  (weakSubscribed, subscribed) <- case live of+    Just found -> {-# SCC "hitRoot" #-} pure found+    Nothing ->+      {-# SCC "missRoot" #-}+      do+        for_ entry $ runRootKeyTeardown (rootSubscribed r) . rootKeyTeardown+        subscribers <- WeakBag.empty+        tracePropagate (Proxy :: Proxy x) "subscribeAndReadRoot: calling rootInit"+        teardown <- rootInit r k $ RootTrigger (subscribers, rootOccurrence r, k)+        nid <- newNodeId+        let !subscribed =+              RootSubscribed+                { rootSubscribedSubscribers = subscribers+                , rootSubscribedNodeId = nid+                }+        teardownVar <- newMVar $ Just teardown+        weakSubscribed <- mkWeakPtr subscribed $ Just $ runRootKeyTeardown (rootSubscribed r) teardownVar+        void $ atomicModifyIORef'_ (rootSubscribed r) $ DMap.insert k $ RootKey weakSubscribed teardownVar+        pure (weakSubscribed, lazy subscribed)+  let fields = lazy subscribed -- 'lazy' used as in 'cacheEventImpl'+      subscribers = rootSubscribedSubscribers fields+  ticket <- WeakBag.insert sub subscribers+  occ <- coerce . DMap.lookup k <$> readIORef (rootOccurrence r)+  let unsubscribeRoot = do+        WeakBag.remove ticket+        noSubscribers <- WeakBag.isEmpty subscribers+        when noSubscribers $ finalize weakSubscribed+        touch ticket+  return $ SubscribeResult (EventSubscription unsubscribeRoot (toAny subscribed) (rootNode r)) occ+  where+    runRootKeyTeardown :: IORef (DMap k (RootKey x)) -> MVar (Maybe (IO ())) -> IO ()+    runRootKeyTeardown rootMap teardownVar = Control.Exception.mask $ \restore -> do+      teardown <- takeMVar teardownVar+      restore (sequence_ teardown)+        `Control.Exception.finally` ( do+                                        putMVar teardownVar Nothing+                                        void+                                          $ atomicModifyIORef'_ rootMap+                                          $ DMap.update (\e -> if rootKeyTeardown e == teardownVar then Nothing else Just e) k+                                    )++newtype EventSelectorInt x a = EventSelectorInt {selectInt :: Int -> Event x a}++{-# INLINE [0] mergeG #-}+mergeG+  :: forall k q x v+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMap k q)+  -> Event x (DMap k v)+mergeG nt d = cacheEventImpl (mergeCheapImpl nt d)++{-# INLINE [0] mergeWithMove #-}+mergeWithMove+  :: forall k v q x+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMapWithMove k q)+  -> Event x (DMap k v)+mergeWithMove nt d = cacheEventImpl (mergeCheapWithMoveImpl nt d)++{-# INLINE [0] mergeCheap #-}+mergeCheap+  :: forall k x q v+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMap k q)+  -> Event x (DMap k v)+mergeCheap = mergeCheapImpl++{-# INLINE mergeCheapImpl #-}+mergeCheapImpl+  :: forall k x q v+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMap k q)+  -> Event x (DMap k v)+mergeCheapImpl nt = genericMergeCheap unMergeSubscribedParent getInitialSubscribers updateMe+  where+    updateMe :: MergeUpdateFunc (DMap k) v x (PatchDMap k q) (MergeSubscribedParent x)+    updateMe subscriber heightBagRef oldParents (PatchDMap p) =+      updateMergeParents nt subscriber heightBagRef oldParents p++    getInitialSubscribers :: MergeInitFunc (DMap k) v (DMap k q) x (MergeSubscribedParent x)+    getInitialSubscribers = initMergeParents nt (\k -> pure (pure k, MergeSubscribedParent))++{-# INLINE [0] mergeCheapWithMove #-}+mergeCheapWithMove+  :: forall k x v q+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMapWithMove k q)+  -> Event x (DMap k v)+mergeCheapWithMove = mergeCheapWithMoveImpl++{-# INLINE mergeCheapWithMoveImpl #-}+mergeCheapWithMoveImpl+  :: forall k x v q+   . (HasSpiderTimeline x, GCompare k)+  => (forall a. q a -> Event x (v a))+  -> DynamicS x (PatchDMapWithMove k q)+  -> Event x (DMap k v)+mergeCheapWithMoveImpl nt = genericMergeCheap _mergeSubscribedParentWithMove_subscription getInitialSubscribers updateMe+  where+    updateMe :: MergeUpdateFunc (DMap k) v x (PatchDMapWithMove k q) (MergeSubscribedParentWithMove x k)+    updateMe subscriber heightBagRef oldParents p = do+      -- Prepare new parents for insertion+      let subscribeParent :: forall a. k a -> Event x (v a) -> EventM x (MergeSubscribedParentWithMove x k a)+          subscribeParent k e = do+            keyRef <- liftIO $ newIORef k+            (`MergeSubscribedParentWithMove` keyRef) . subscribeSubscription+              <$> subscribeMergeParent heightBagRef e (subscriber $ liftIO $ readIORef keyRef)+      p' <- PatchDMapWithMove.traversePatchDMapWithMoveWithKey (\k q -> subscribeParent k (nt q)) p+      -- Collect old parents for deletion and update the keys of moved parents+      let moveOrDelete :: forall a. k a -> PatchDMapWithMove.NodeInfo k q a -> MergeSubscribedParentWithMove x k a -> Constant (EventM x (Maybe (EventSubscription x))) a+          moveOrDelete _ ni parent = Constant $ case getComposeMaybe $ PatchDMapWithMove._nodeInfo_to ni of+            Nothing -> do+              let subscription = _mergeSubscribedParentWithMove_subscription parent+              liftIO $ forgetMergeParentHeight heightBagRef subscription+              return $ Just subscription+            Just toKey -> do+              liftIO $ writeIORef (_mergeSubscribedParentWithMove_key parent) $! toKey+              return Nothing+      toDelete <-+        fmap catMaybes+          $ mapM (\(_ :=> v) -> getConstant v)+          $ DMap.toList+          $ DMap.intersectionWithKey moveOrDelete (unPatchDMapWithMove p) oldParents++      return (toDelete, applyAlways p' oldParents)+    getInitialSubscribers :: MergeInitFunc (DMap k) v (DMap k q) x (MergeSubscribedParentWithMove x k)+    getInitialSubscribers = initMergeParents nt parentAt+      where+        -- A moved parent keeps its subscription, so its subscriber reads the+        -- key from a ref that the patch function updates.+        parentAt :: forall a. k a -> EventM x (EventM x (k a), EventSubscription x -> MergeSubscribedParentWithMove x k a)+        parentAt k = do+          keyRef <- liftIO $ newIORef k+          pure (liftIO $ readIORef keyRef, (`MergeSubscribedParentWithMove` keyRef))++type MergeUpdateFunc map v x p s =+  (forall a. EventM x (MapKey map a) -> Subscriber x (v a))+  -> IORef HeightBag+  -> map s+  -> p+  -> EventM x ([EventSubscription x], map s)++type MergeGetSubscription x s = forall a. s a -> EventSubscription x++type MergeInitFunc map v t x s =+  t+  -> (forall a. EventM x (MapKey map a) -> Subscriber x (v a))+  -> IORef HeightBag+  -> EventM x (map v, map s)++data MergeChangeSubscription x+  = MergeChangeNotSubscribed+  | MergeChangeSubscribed !(EventSubscription x)+  | MergeChangeUnsubscribed++{-# INLINE initMergeParents #-}+initMergeParents+  :: forall map q v x s+   . IsMap map+  => (forall a. q a -> Event x (v a))+  -> (forall a. MapKey map a -> EventM x (EventM x (MapKey map a), EventSubscription x -> s a))+  -> MergeInitFunc map v (map q) x s+initMergeParents nt parentAt initialParents subscriber heightBagRef = do+  occurrencesRef <- liftIO $ newIORef mapEmpty+  parents <- forM (mapToList initialParents) $ \(k :=> e) -> do+    (getKey, toParent) <- parentAt k+    SubscribeResult subscription parentOcc <- subscribeMergeParent heightBagRef (nt e) (subscriber getKey)+    liftIO $ for_ parentOcc $ modifyIORef' occurrencesRef . mapInsert k+    pure $ k :=> toParent subscription+  occurrences <- liftIO $ readIORef occurrencesRef+  pure (occurrences, mapFromDistinctAscList parents)++{-# INLINE updateMergeParents #-}+updateMergeParents+  :: forall map q v x+   . IsMap map+  => (forall a. q a -> Event x (v a))+  -> MergeUpdateFunc map v x (map (ComposeMaybe q)) (MergeSubscribedParent x)+updateMergeParents nt subscriber heightBagRef oldParents patch =+  foldM updateParent ([], oldParents) $ mapToList patch+  where+    updateParent (subscriptionsToKill, parents) (k :=> ComposeMaybe maybeEvent) = do+      (maybeOldSubscribed, newParents) <- case maybeEvent of+        Nothing -> pure $ mapDeleteLookup k parents+        Just e -> do+          newParent <- MergeSubscribedParent . subscribeSubscription <$> subscribeMergeParent heightBagRef (nt e) (subscriber $ pure k)+          pure $ mapInsertLookup k newParent parents+      for_ maybeOldSubscribed $+        liftIO . forgetMergeParentHeight heightBagRef . unMergeSubscribedParent+      pure+        ( maybeToList (unMergeSubscribedParent <$> maybeOldSubscribed) <> subscriptionsToKill+        , newParents+        )++subscribeMergeParent :: IORef HeightBag -> Event x a -> Subscriber x a -> EventM x (SubscribeResult x a)+subscribeMergeParent heightBagRef e sub = do+  result <- subscribeAndRead e sub+  liftIO $ modifyIORef' heightBagRef . heightBagAddParent =<< eventSubscriptionHeight (subscribeSubscription result)+  pure result++forgetMergeParentHeight :: IORef HeightBag -> EventSubscription x -> IO ()+forgetMergeParentHeight heightBagRef subscription =+  modifyIORef' heightBagRef . heightBagRemoveParent =<< eventSubscriptionHeight subscription++checkCycle :: HasSpiderTimeline x => EventNode x -> EventM x ()+checkCycle subscribed = do+  height <- liftIO $ readIORef (eventNodeHeightRef subscribed)+  case height of+    ValidHeight -> when debugEnabled $ do+      currentHeight <- getCurrentHeight+      when ((height `compareHeight` currentHeight) /= GT)+        $ error+        $ "checkCycle: merge height " <> show height <> " not above current height " <> show currentHeight+    InvalidHeight -> liftIO $ throwEventLoopException subscribed++{-# INLINE genericMergeCheap #-}+genericMergeCheap+  :: forall map v x p s+   . (HasSpiderTimeline x, IsMap map)+  => MergeGetSubscription x s -> MergeInitFunc map v (PatchTarget p) x s -> MergeUpdateFunc map v x p s -> DynamicS x p -> Event x (map v)+genericMergeCheap getParent getInitialSubscribers updateFunc d = Event $ \sub -> do+  initialParents <- readBehaviorUntracked $ dynamicCurrent d+  accumRef <- liftIO $ newIORef $ error "merge: accumRef not yet initialized"+  heightBagRef <- liftIO $ newIORef heightBagEmpty+  parentsRef :: IORef (map s) <- liftIO $ newIORef $ error "merge: parentsRef not yet initialized"+  changeSubdRef <- liftIO $ newIORef MergeChangeNotSubscribed+  subscribed <-+    mkEventNode+      (error "merge: heightRef not yet initialized")+      (fmap (\(_ :=> parent) -> _eventSubscription_node (getParent parent)) . mapToList <$> readIORef parentsRef)+      (whoCreatedIORef changeSubdRef)+  let heightRef = eventNodeHeightRef subscribed++      scheduleSelf height = scheduleMerge height propagateAtHeight++      -- propagateAtHeight and propagateAccumulated are defined outside+      -- scheduleSelf so that they are allocated once per subscription+      -- instead of on every call.+      propagateAtHeight = do+        height <- liftIO $ readIORef heightRef+        currentHeight <- getCurrentHeight+        case height `compareHeight` currentHeight of+          LT -> error "Somehow a merge's height has been decreased after it was scheduled"+          GT -> scheduleMerge height propagateAtHeight -- The height has been increased by a coincidence event.+          EQ -> propagateAccumulated++      propagateAccumulated = do+        vals <- liftIO $ readIORef accumRef+        liftIO $ writeIORef accumRef $! mapEmpty+        -- TODO: Assert that vals is not empty+        subscriberPropagate sub vals++      invalidateMyHeight = do+        checkNotUnsubscribed "the height of an unsubscribed merge changes"+        invalidateOwnHeight heightRef (subscriberInvalidateHeight sub)++      -- An unsubscribed merge never changes its height.+      checkNotUnsubscribed debugNote =+        when debugFrame $+          readIORef changeSubdRef >>= \case+            MergeChangeUnsubscribed -> error $ "merge: " <> debugNote+            _ -> pure ()++      checkParentCount :: IO ()+      checkParentCount = do+        parents <- readIORef parentsRef+        heights <- readIORef heightBagRef+        when (mapSize parents /= heightBagParentCount heights)+          $ error+          $ "merge: " <> show (mapSize parents) <> " parents, but the height bag has " <> show (heightBagParentCount heights)++      recalculateMyHeight = recalculateOwnHeight heightRef (subscriberRecalculateHeight sub) $ do+        checkNotUnsubscribed "an unsubscribed merge recalculates its height"+        when debugEnabled checkParentCount+        heightBagHeight <$> readIORef heightBagRef++      invalidateMyHeightOnParentChange =+        readIORef changeSubdRef >>= \case+          -- runFrame runs the frame's unsubscriptions before this, so the+          -- merge may already be unsubscribed. Then it keeps its height.+          MergeChangeUnsubscribed -> pure ()+          _ -> do+            own <- readIORef heightRef+            case own of+              ValidHeight -> do+                heights <- readIORef heightBagRef+                case heightBagHeight heights of+                  new@ValidHeight | compareHeight own new == EQ -> pure ()+                  _ -> invalidateMyHeight+              InvalidHeight -> pure ()++      {-# INLINE parentSubscriber #-}+      parentSubscriber :: forall a. EventM x (MapKey map a) -> Subscriber x (v a)+      parentSubscriber getKey =+        Subscriber+          { subscriberPropagate = \a -> do+              checkCycle subscribed+              oldM <- liftIO $ readIORef accumRef+              k <- getKey+              when debugFrame+                $ debugOccurrence "merge: one parent fired twice in one frame"+                $ mapLookup k oldM+              let newM = mapInsert k a oldM+              tracePropagate (Proxy :: Proxy x) $ "  size oldM = " <> show (mapSize oldM) <> "; size newM = " <> show (mapSize newM)+              liftIO $ writeIORef accumRef $! newM+              when (mapNull oldM) $ do+                -- Only schedule the firing once+                height <- liftIO $ readIORef heightRef+                scheduleSelf height+          , subscriberInvalidateHeight = \old -> do+              heights <- readIORef heightBagRef+              let heights' = heightBagInvalidateParent old heights+              writeIORef heightBagRef $! heights'+              own <- readIORef heightRef+              case own of+                ValidHeight ->+                  when+                    (compareHeight (heightBagSuccHeight heights') (heightBagSuccHeight heights) == LT)+                    invalidateMyHeight+                InvalidHeight -> pure ()+          , subscriberRecalculateHeight = \new -> do+              modifyIORef' heightBagRef $ heightBagRecalculateParent new+              own <- readIORef heightRef+              case own of+                ValidHeight -> when (compareHeight own new /= GT) invalidateMyHeight+                InvalidHeight -> pure ()+              recalculateMyHeight+          }++      -- TODO: Be able to run as much of this as possible promptly+      updateParents patch =+        liftIO (readIORef changeSubdRef) >>= \case+          MergeChangeUnsubscribed -> return []+          _ -> do+            oldParents <- liftIO $ readIORef parentsRef+            (subscriptionsToKill, newParents) <- updateFunc parentSubscriber heightBagRef oldParents patch+            liftIO $ writeIORef parentsRef $! newParents+            when debugEnabled $ liftIO checkParentCount+            return subscriptionsToKill++      deferParentUpdate patch =+        defer $ SomeMergeUpdate (updateParents patch) invalidateMyHeightOnParentChange recalculateMyHeight++  (dm, initialParentState) <- getInitialSubscribers initialParents parentSubscriber heightBagRef+  myHeight <- liftIO $ heightBagHeight <$> readIORef heightBagRef+  currentHeight <- getCurrentHeight+  let (occ, accum) =+        if heightSlotPassed currentHeight myHeight -- The merge would have fired already in this frame+          then (if mapNull dm then Nothing else Just dm, mapEmpty)+          else (Nothing, dm)+  unless (mapNull accum) $ scheduleSelf myHeight+  liftIO $ writeIORef accumRef $! accum+  liftIO $ writeIORef heightRef $! myHeight+  liftIO $ writeIORef parentsRef $! initialParentState+  when debugEnabled $ liftIO checkParentCount+  defer $+    SomeMergeInit $+      liftIO (readIORef changeSubdRef) >>= \case+        MergeChangeNotSubscribed -> do+          let changeSubscriber = terminalSubscriber $ \patch ->+                {-# SCC "traverseMergeChange" #-}+                do+                  tracePropagate (Proxy :: Proxy x) "SubscriberMerge/Change"+                  deferParentUpdate patch+          SubscribeResult changeSubscription change <- subscribeAndRead (dynamicUpdated d) changeSubscriber+          for_ change deferParentUpdate+          liftIO $ writeIORef changeSubdRef $ MergeChangeSubscribed changeSubscription+        _ -> pure ()+  let unsubscribeAll = do+        parents <- readIORef parentsRef+        mapFor_ parents $ unsubscribe . getParent+        readIORef changeSubdRef >>= \case+          MergeChangeSubscribed changeSubscription -> unsubscribe changeSubscription+          _ -> pure ()+        writeIORef changeSubdRef MergeChangeUnsubscribed+  pure $ SubscribeResult (EventSubscription unsubscribeAll (toAny (parentsRef, changeSubdRef)) subscribed) occ++{-# NOINLINE [0] mergeInt #-}+{-# SPECIALIZE mergeInt :: DynamicS Global (PatchIntMap (Event Global a)) -> Event Global (IntMap a) #-}+mergeInt :: forall x a. HasSpiderTimeline x => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)+mergeInt d = cacheEventImpl (mergeIntCheapImpl d)++{-# NOINLINE [0] mergeIntCheap #-}+{-# SPECIALIZE mergeIntCheap :: DynamicS Global (PatchIntMap (Event Global a)) -> Event Global (IntMap a) #-}+mergeIntCheap :: forall x a. HasSpiderTimeline x => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)+mergeIntCheap = mergeIntCheapImpl++{-# INLINE mergeIntCheapImpl #-}+mergeIntCheapImpl :: forall x a. HasSpiderTimeline x => DynamicS x (PatchIntMap (Event x a)) -> Event x (IntMap a)+mergeIntCheapImpl = coerceEvent . genericMergeCheap unMergeSubscribedParent getInitialSubscribers updateMe+  where+    coerceEvent :: Event x (IntMapOf a Identity) -> Event x (IntMap a)+    coerceEvent = coerce++    eventOfIdentity :: forall b. Event x b -> Event x (Identity b)+    eventOfIdentity = coerce++    updateMe :: MergeUpdateFunc (IntMapOf a) Identity x (PatchIntMap (Event x a)) (MergeSubscribedParent x)+    updateMe subscriber heightBagRef oldParents (PatchIntMap p) =+      updateMergeParents eventOfIdentity subscriber heightBagRef oldParents (IntMapOf (coerce p) :: IntMapOf a (ComposeMaybe (Event x)))++    -- Not re-using 'initMergeParents' here; inserting each parent into+    -- IntMaps directly allocates less than going through lists of 'DSum'+    -- entries with 'Const2' keys and 'mapFromDistinctAscList'.+    getInitialSubscribers :: MergeInitFunc (IntMapOf a) Identity (IntMap (Event x a)) x (MergeSubscribedParent x)+    getInitialSubscribers initialParents subscriber heightBagRef = do+      occurrencesRef <- liftIO $ newIORef IntMap.empty+      parentsRef <- liftIO $ newIORef IntMap.empty+      forM_ (IntMap.toList initialParents) $ \(k, e) -> do+        SubscribeResult subscription parentOcc <- subscribeMergeParent heightBagRef (eventOfIdentity e) (subscriber $ pure $ Const2 k)+        liftIO $ do+          for_ parentOcc $ \occurrence -> modifyIORef' occurrencesRef $ IntMap.insert k occurrence+          modifyIORef' parentsRef $ IntMap.insert k $ MergeSubscribedParent subscription+      occurrences <- liftIO $ readIORef occurrencesRef+      parents <- liftIO $ readIORef parentsRef+      pure (IntMapOf occurrences, IntMapOf parents)++newtype EventSelector x k = EventSelector {select :: forall a. k a -> Event x a}+newtype EventSelectorG x k v = EventSelectorG {selectG :: forall a. k a -> Event x (v a)}++{-# NOINLINE [1] fanG #-}+fanG :: (HasSpiderTimeline x, GCompare k) => Event x (DMap k v) -> EventSelectorG x k v+fanG e = unsafePerformIO $ do+  self <- newFan+  pure $ EventSelectorG $ \k -> eventFan k e self++{-# NOINLINE [1] fanInt #-}+fanInt :: forall x a. HasSpiderTimeline x => Event x (IntMap a) -> EventSelectorInt x a+fanInt e = unsafePerformIO $ do+  self <- newFan+  pure $ EventSelectorInt $ \k -> coerce $ eventFan (Const2 k) (coerce e :: Event x (IntMapOf a Identity)) self++runHoldInits :: HasSpiderTimeline x => IORef [SomeHoldInit x] -> IORef [SomeDynInit x] -> IORef [SomeMergeInit x] -> EventM x ()+runHoldInits holdInitRef dynInitRef mergeInitRef = do+  holdInits <- liftIO $ readIORef holdInitRef+  dynInits <- liftIO $ readIORef dynInitRef+  mergeInits <- liftIO $ readIORef mergeInitRef+  unless (null holdInits && null dynInits && null mergeInits) $ do+    liftIO $ writeIORef holdInitRef []+    liftIO $ writeIORef dynInitRef []+    liftIO $ writeIORef mergeInitRef []+    mapM_ initHold holdInits+    mapM_ initDyn dynInits+    mapM_ unSomeMergeInit mergeInits+    runHoldInits holdInitRef dynInitRef mergeInitRef++initHold :: forall x. HasSpiderTimeline x => SomeHoldInit x -> EventM x ()+initHold (SomeHoldInit h) = do+  liftIO (readIORef $ holdState h) >>= \case+    HoldLive e invalidators Nothing -> do+      -- Need to evaluate this so that we don't retain the Hold itself+      valueRef <- liftIO $ evaluate $ holdValue h+      let applyPatch patch = do+            old <- {-# SCC "read" #-} liftIO $ readIORef valueRef+            for_ ({-# SCC "apply" #-} apply patch old) $ \new -> do+              withIncreasedDepth (Proxy :: Proxy x) $+                tracePropagate (Proxy :: Proxy x) ("initHold: assigning Hold" <> showNodeId h)+              defer $ {-# SCC "assignment" #-} SomeAssignment valueRef invalidators new+      SubscribeResult subscription occ <- subscribeAndRead e $ terminalSubscriber $ \a ->+        {-# SCC "traverseHold" #-}+        do+          when debugPropagate $ traceM (Proxy :: Proxy x) $ liftIO $ do+            InvalidatorList n _ _ <- readIORef invalidators+            return $ "SubscriberHold" <> showNodeId h <> ": " <> show n+          applyPatch a+      for_ occ applyPatch+      liftIO $ writeIORef (holdState h) $ HoldLive e invalidators $ Just subscription+    _ -> pure ()++initDyn :: HasSpiderTimeline x => SomeDynInit x -> EventM x ()+initDyn (SomeDynInit d) = void $ getDynHold d++newEventEnv :: IO (EventEnv x)+newEventEnv = do+  toAssignRef <- newIORef [] -- This should only actually get used when events are firing+  holdInitRef <- newIORef []+  dynInitRef <- newIORef []+  mergeUpdateRef <- newIORef []+  mergeInitRef <- newIORef []+  heightRef <- newIORef zeroHeight+  toClearRef <- newIORef []+  toClearRootRef <- newIORef []+  coincidenceInfosRef <- newIORef []+  pendingRecalculationsRef <- newIORef []+  delayedRef <- newIORef heightQueueEmpty+  return $ EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef pendingRecalculationsRef delayedRef++clearEventEnv :: EventEnv x -> IO ()+clearEventEnv (EventEnv toAssignRef holdInitRef dynInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef _pendingRecalculationsRef delayedRef) = do+  writeIORef toAssignRef []+  writeIORef holdInitRef []+  writeIORef dynInitRef []+  writeIORef mergeUpdateRef []+  writeIORef mergeInitRef []+  writeIORef heightRef zeroHeight+  when debugFrame $ do+    toClear <- readIORef toClearRef+    toClearRoot <- readIORef toClearRootRef+    unless (null toClear && null toClearRoot) $+      error "clearEventEnv: a clear was scheduled after clearOccurrences"+  writeIORef toClearRef []+  writeIORef toClearRootRef []+  writeIORef coincidenceInfosRef []+  when debugFrame $ do+    delayed <- readIORef delayedRef+    case heightQueueNext delayed of+      Nothing -> pure ()+      Just _ -> error "clearEventEnv: unprocessed scheduled merge"+  writeIORef delayedRef heightQueueEmpty++-- | Run an event action outside of a frame+runFrame :: forall x a. HasSpiderTimeline x => EventM x a -> SpiderHost x a -- TODO: This function also needs to hold the mutex+runFrame a = SpiderHost $ do+  let go = do+        result <- a+        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+        return result+  result <- runEventM go+  clearOccurrences+  toAssign <- readIORef $ eventEnvAssignments env+  toReconnectRef <- newIORef []+  coincidenceInfos <- readIORef $ eventEnvResetCoincidences env+  forM_ toAssign $ \(SomeAssignment vRef iRef v) ->+    {-# SCC "assignment" #-}+    do+      writeIORef vRef v+      traceInvalidate "Invalidating Hold"+      writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef+  mergeUpdates <- readIORef $ eventEnvMergeUpdates env+  writeIORef (eventEnvMergeUpdates env) []+  tracePropagate (Proxy :: Proxy x) "Updating merges"+  mergeSubscriptionsToKill <- runEventM $ do+    subscriptionsToKill <- concat <$> mapM _someMergeUpdate_update mergeUpdates+    -- Subscribing to a new merge parent coming from a patch can cause new+    -- deferred inits being added, evaluate them:+    runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env)+    pure subscriptionsToKill+  tracePropagate (Proxy :: Proxy x) "Updating merges done"+  toReconnect <- readIORef toReconnectRef+  clearEventEnv env+  switchSubscriptionsToKill <- fmap catMaybes . forM toReconnect $ \(SomeSwitchSubscribed subscribed) ->+    {-# SCC "switchSubscribed" #-}+    readIORef (switchSubscribedState subscribed) >>= \case+      SwitchLive behavior readSetRef _ oldSubscription -> do+        writeIORef readSetRef []+        _ <- subscribeSwitchCurrentParent subscribed behavior readSetRef (eventEnvHoldInits env) subscribeReconnect+        return $ Just oldSubscription+      -- Can't happen: unsubscribing finalizes the switch's weak invalidator,+      -- and nothing unsubscribes a switch between the assignments and here.+      SwitchParentUnsubscribed -> error "runFrame: an unsubscribed switch was invalidated"+  liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill+  liftIO $ mapM_ unsubscribe switchSubscriptionsToKill+  let unsubscribeInner raised [] = pure raised+      unsubscribeInner raised (SomeResetCoincidence innerSubscription raisedCoincidence : rest) = do+        unsubscribe innerSubscription+        case raisedCoincidence of+          Nothing -> unsubscribeInner raised rest+          Just subscribed -> unsubscribeInner (SomeRaisedCoincidence subscribed : raised) rest+  raisedCoincidences <- unsubscribeInner [] coincidenceInfos+  forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) ->+    {-# SCC "switchSubscribed" #-}+    readIORef (switchSubscribedState subscribed) >>= \case+      SwitchParentUnsubscribed -> pure ()+      SwitchLive _ _ _ parent -> do+        parentHeight <- eventSubscriptionHeight parent+        myHeight <- readIORef $ switchSubscribedHeight subscribed+        case myHeight of+          InvalidHeight -> pure ()+          ValidHeight -> do+            let heightChanged = case parentHeight of+                  ValidHeight -> compareHeight parentHeight myHeight /= EQ+                  InvalidHeight -> True+            when heightChanged $+              subscriberInvalidateHeight (switchSubscribedSubscriber subscribed) myHeight+  mapM_ _someMergeUpdate_invalidateHeight mergeUpdates+  -- Raised coincidences go back to the height of their outer parent.+  forM_ raisedCoincidences $ \(SomeRaisedCoincidence subscribed) ->+    readIORef (coincidenceSubscribedOuterParent subscribed) >>= \case+      Just _ -> invalidateCoincidenceHeight subscribed+      -- Unsubscribed in this frame: it keeps its height.+      Nothing -> pure ()+  runPendingRecalculations env+  mapM_ _someMergeUpdate_recalculateHeight mergeUpdates+  forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) ->+    readIORef (switchSubscribedState subscribed) >>= \case+      SwitchParentUnsubscribed -> pure ()+      SwitchLive _ _ _ parent ->+        subscriberRecalculateHeight (switchSubscribedSubscriber subscribed) =<< eventSubscriptionHeight parent+  when debugFrame $ do+    leftover <- readIORef $ eventEnvPendingRecalculations env+    unless (null leftover) $+      error "runFrame: pending recalculations at frame end"+  return result+  where+    env = spiderEventEnv @x++    clearOccurrences :: IO ()+    clearOccurrences = do+      toClear <- readIORef $ eventEnvClears env+      forM_ toClear $ \(Some (Clear ref)) -> {-# SCC "clear" #-} writeIORef ref Nothing+      toClearRoot <- readIORef $ eventEnvRootClears env+      forM_ toClearRoot $ \(Some (RootClear ref)) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty+      -- Empty the clear lists, so that the DEBUG_FRAME check can verify that no+      -- clear was scheduled that would have been dropped silently.+      when debugFrame $ do+        writeIORef (eventEnvClears env) []+        writeIORef (eventEnvRootClears env) []++    subscribeReconnect :: forall b. Event x b -> Subscriber x b -> IO (SubscribeResult x b)+    subscribeReconnect e sub =+      {-# SCC "subscribeSwitch" #-}+      do+        pendingRecalculationsBefore <-+          if debugEnabled+            then length <$> readIORef (eventEnvPendingRecalculations env)+            else pure 0+        result <-+          runEventM $+            subscribeAndRead e sub <* runHoldInits (eventEnvHoldInits env) (eventEnvDynInits env) (eventEnvMergeInits env)+        clearOccurrences+        when debugEnabled $ do+          when (isJust $ subscribeOccurrence result) $ error "subscribeReconnect: the new parent has an occurrence, which should be impossible when no event is firing"+          toAssign <- readIORef $ eventEnvAssignments env+          coincidenceInfos <- readIORef $ eventEnvResetCoincidences env+          pendingRecalculationsAfter <- length <$> readIORef (eventEnvPendingRecalculations env)+          unless (null toAssign && null coincidenceInfos && pendingRecalculationsAfter == pendingRecalculationsBefore) $ error "subscribeReconnect: the reconnect subscribe deferred a hold assignment, coincidence reset or height recalculation, which should be impossible when no event is firing"+        clearEventEnv env+        return result++--------------------------------------------------------------------------------+-- Height algo+--------------------------------------------------------------------------------++-- | The first phase of a height change: notify downstream of the height you're+-- leaving. The heightRef reads invalidHeight before notifying and until+-- the recalculation phase.+{-# INLINE invalidateOwnHeight #-}+invalidateOwnHeight :: IORef Height -> (Height -> IO ()) -> IO ()+invalidateOwnHeight heightRef notify = do+  oldHeight <- readIORef heightRef+  case oldHeight of+    InvalidHeight -> pure ()+    ValidHeight -> do+      writeIORef heightRef $! invalidHeight+      notify oldHeight++-- | The second phase of a height change: the heightRef reads the new height+-- during downstream notification of recalculation.+{-# INLINE recalculateOwnHeight #-}+recalculateOwnHeight :: IORef Height -> (Height -> IO ()) -> IO Height -> IO ()+recalculateOwnHeight heightRef notify calculate = do+  oldHeight <- readIORef heightRef+  case oldHeight of+    ValidHeight -> pure ()+    InvalidHeight ->+      calculate >>= \case+        InvalidHeight -> pure ()+        newHeight@ValidHeight -> do+          traceInvalidateHeight $ "recalculateOwnHeight: height: " <> show newHeight+          writeIORef heightRef $! newHeight+          notify newHeight++-- | Requests a height recalculation at the end of the current frame.+--+-- Call this from the node that invalidated its own height. Every invalidation+-- requires exactly one recalculation. Otherwise the height bags of the+-- subscribers stay one entry short and never complete again.+{-# INLINE deferRecalculateHeight #-}+deferRecalculateHeight :: forall x. HasSpiderTimeline x => SomeRecalculateHeight x -> IO ()+deferRecalculateHeight recalculate = modifyIORef' (eventEnvPendingRecalculations (spiderEventEnv @x)) (recalculate :)++runPendingRecalculations :: EventEnv x -> IO ()+runPendingRecalculations env = go+  where+    go =+      readIORef (eventEnvPendingRecalculations env) >>= \case+        [] -> pure ()+        pending -> do+          writeIORef (eventEnvPendingRecalculations env) []+          forM_ pending $ \(SomeRecalculateHeight recalculate) -> recalculate+          go++invalidateCoincidenceHeight :: forall x a. HasSpiderTimeline x => CoincidenceSubscribed x a -> IO ()+invalidateCoincidenceHeight subscribed =+  invalidateOwnHeight (coincidenceSubscribedHeight subscribed) $ \oldHeight -> do+    deferRecalculateHeight @x $ SomeRecalculateHeight $ recalculateCoincidenceHeight subscribed+    invalidateCoincidenceSubscribers subscribed oldHeight++{-# INLINE invalidateCoincidenceSubscribers #-}+invalidateCoincidenceSubscribers :: CoincidenceSubscribed x a -> Height -> IO ()+invalidateCoincidenceSubscribers = subscriberInvalidateHeight . coincidenceSubscribedSubscriber++{-# INLINE recalculateCoincidenceSubscribers #-}+recalculateCoincidenceSubscribers :: CoincidenceSubscribed x a -> Height -> IO ()+recalculateCoincidenceSubscribers = subscriberRecalculateHeight . coincidenceSubscribedSubscriber++recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()+recalculateCoincidenceHeight subscribed =+  recalculateOwnHeight (coincidenceSubscribedHeight subscribed) (recalculateCoincidenceSubscribers subscribed) (calculateCoincidenceHeight subscribed)++calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height+calculateCoincidenceHeight subscribed = do+  outerHeight <-+    readIORef (coincidenceSubscribedOuterParent subscribed) >>= \case+      Just outerSubscription -> eventSubscriptionHeight outerSubscription+      -- Can't happen: runFrame skips unsubscribed coincidences.+      Nothing -> error "coincidence: the height of an unsubscribed coincidence changes"+  innerHeight <- maybe (return zeroHeight) getEventNodeHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)+  pure $ coincidenceHeight outerHeight innerHeight++data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)++invalidate :: IORef [SomeSwitchSubscribed x] -> InvalidatorList x -> IO (InvalidatorList x)+invalidate toReconnectRef (InvalidatorList _ _ wis) = do+  forM_ wis $ \wi -> do+    mi <- deRefWeak wi+    case mi of+      Nothing -> do+        traceInvalidate "invalidate Dead"+        return () -- TODO: Should we clean this up here?+      Just i -> do+        finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict+        case i of+          InvalidatorPull p -> do+            traceInvalidate $ "invalidate: Pull" <> showNodeId p+            mVal <- readIORef $ pullValue p+            forM_ mVal $ \val -> do+              writeIORef (pullValue p) Nothing+              writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)+          InvalidatorSwitch subscribed -> do+            traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed+            modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)+  return emptyInvalidatorList -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them++--------------------------------------------------------------------------------+-- Reflex integration+--------------------------------------------------------------------------------++-- | Designates the default, global Spider timeline+data SpiderTimeline x++type role SpiderTimeline nominal++-- | The default, global Spider environment+type Spider = SpiderTimeline Global++instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (EventM x) where+  {-# SPECIALIZE instance Reflex.Class.MonadSample (SpiderTimeline Global) (EventM Global) #-}+  {-# INLINEABLE sample #-}+  sample (SpiderBehavior b) = readBehaviorUntracked b++instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (EventM x) where+  {-# SPECIALIZE instance Reflex.Class.MonadHold (SpiderTimeline Global) (EventM Global) #-}++  -- hold and headE are INLINE in all four MonadHold instances, for the reason+  -- in the Reflex instance.+  {-# INLINE hold #-}+  hold = holdSpiderEventM+  {-# INLINEABLE holdDyn #-}+  holdDyn = holdDynSpiderEventM+  {-# INLINEABLE holdIncremental #-}+  holdIncremental = holdIncrementalSpiderEventM+  {-# INLINEABLE buildDynamic #-}+  buildDynamic = buildDynamicSpiderEventM+  {-# INLINE headE #-}+  headE (SpiderEvent e) = SpiderEvent <$> Reflex.Spider.Internal.headE e+  {-# INLINEABLE now #-}+  now = nowSpiderEventM++instance Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPullM x) where+  {-# INLINEABLE sample #-}+  sample = coerce . readBehaviorTracked . unSpiderBehavior++instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderPushM x) where+  {-# SPECIALIZE instance Reflex.Class.MonadSample (SpiderTimeline Global) (SpiderPushM Global) #-}+  {-# INLINEABLE sample #-}+  sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b++instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderPushM x) where+  {-# SPECIALIZE instance Reflex.Class.MonadHold (SpiderTimeline Global) (SpiderPushM Global) #-}+  {-# INLINE hold #-}+  hold v0 (SpiderEvent e) = SpiderPushM $ SpiderBehavior <$> holdBehavior v0 e+  {-# INLINEABLE holdDyn #-}+  holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ coerce e+  {-# INLINEABLE holdIncremental #-}+  holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> Reflex.Spider.Internal.hold v0 e+  {-# INLINEABLE buildDynamic #-}+  buildDynamic getV0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicDyn) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce e+  {-# INLINE headE #-}+  headE (SpiderEvent e) = SpiderPushM $ SpiderEvent <$> Reflex.Spider.Internal.headE e+  {-# INLINEABLE now #-}+  now = SpiderPushM nowSpiderEventM++instance HasSpiderTimeline x => Monad (Reflex.Class.Dynamic (SpiderTimeline x)) where+  {-# INLINE (>>=) #-}+  x >>= f = SpiderDynamic $ dynamicDyn $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x+#if !MIN_VERSION_base(4,13,0)+  {-# INLINE fail #-}+  fail _ = error "Dynamic does not support 'fail'"+#endif++{-# INLINEABLE newJoinDyn #-}+newJoinDyn :: HasSpiderTimeline x => DynamicS x (Identity (DynamicS x (Identity a))) -> Reflex.Spider.Internal.Dyn x (Identity a)+newJoinDyn d =+  let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)+      eOuter = Reflex.Spider.Internal.push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d+      eInner = Reflex.Spider.Internal.switch $ dynamicUpdated <$> dynamicCurrent d+      eBoth = Reflex.Spider.Internal.coincidence $ SpiderEvent . dynamicUpdated . runIdentity <$> dynamicUpdated d+      v' = unSpiderEvent $ Reflex.Class.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]+  in Reflex.Spider.Internal.unsafeBuildDynamic readV0 v'++instance HasSpiderTimeline x => Functor (Reflex.Class.Dynamic (SpiderTimeline x)) where+  fmap = mapDynamicSpider+  x <$ d = R.unsafeBuildDynamic (return x) $ x <$ R.updated d++mapDynamicSpider :: HasSpiderTimeline x => (a -> b) -> Reflex.Class.Dynamic (SpiderTimeline x) a -> Reflex.Class.Dynamic (SpiderTimeline x) b+mapDynamicSpider f = SpiderDynamic . newMapDyn f . unSpiderDynamic+{-# INLINE [1] mapDynamicSpider #-}++instance HasSpiderTimeline x => Applicative (Reflex.Class.Dynamic (SpiderTimeline x)) where+  pure = SpiderDynamic . dynamicConst+  liftA2 f a b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith f (unSpiderDynamic a) (unSpiderDynamic b)+  SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ Reflex.Spider.Internal.zipDynWith ($) a b+  a *> b = R.unsafeBuildDynamic (R.sample $ R.current b) $ R.leftmost [R.updated b, R.tag (R.current b) $ R.updated a]+  (<*) = flip (*>) -- There are no effects, so order doesn't matter++{-# INLINE holdSpiderEventM #-}+holdSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Behavior (SpiderTimeline x) a)+holdSpiderEventM v0 e = fmap SpiderBehavior $ holdBehavior v0 $ unSpiderEvent e++holdDynSpiderEventM :: HasSpiderTimeline x => a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e++holdIncrementalSpiderEventM :: (HasSpiderTimeline x, Patch p) => PatchTarget p -> Reflex.Class.Event (SpiderTimeline x) p -> EventM x (Reflex.Class.Incremental (SpiderTimeline x) p)+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e++buildDynamicSpiderEventM :: HasSpiderTimeline x => SpiderPushM x a -> Reflex.Class.Event (SpiderTimeline x) a -> EventM x (Reflex.Class.Dynamic (SpiderTimeline x) a)+buildDynamicSpiderEventM getV0 e = fmap (SpiderDynamic . dynamicDyn) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e++instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHost x) where+  {-# INLINEABLE hold #-}+  hold v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.hold v0 e+  {-# INLINEABLE holdDyn #-}+  holdDyn v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdDyn v0 e+  {-# INLINEABLE holdIncremental #-}+  holdIncremental v0 e = runFrame . runSpiderHostFrame $ Reflex.Class.holdIncremental v0 e+  {-# INLINEABLE buildDynamic #-}+  buildDynamic getV0 e = runFrame . runSpiderHostFrame $ Reflex.Class.buildDynamic getV0 e+  {-# INLINEABLE headE #-}+  headE e = runFrame . runSpiderHostFrame $ Reflex.Class.headE e+  {-# INLINEABLE now #-}+  now = runFrame . runSpiderHostFrame $ Reflex.Class.now++instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where+  {-# SPECIALIZE instance Reflex.Class.MonadSample (SpiderTimeline Global) (SpiderHostFrame Global) #-}+  sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior -- TODO: This can cause problems with laziness, so we should get rid of it if we can++instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where+  {-# SPECIALIZE instance Reflex.Class.MonadHold (SpiderTimeline Global) (SpiderHostFrame Global) #-}+  {-# INLINE hold #-}+  hold v0 e = SpiderHostFrame $ fmap SpiderBehavior $ holdBehavior v0 $ unSpiderEvent e+  {-# INLINEABLE holdDyn #-}+  holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ coerce $ unSpiderEvent e+  {-# INLINEABLE holdIncremental #-}+  holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ Reflex.Spider.Internal.hold v0 $ unSpiderEvent e+  {-# INLINEABLE buildDynamic #-}+  buildDynamic getV0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicDyn) $ Reflex.Spider.Internal.buildDynamic (coerce getV0) $ coerce $ unSpiderEvent e+  {-# INLINE headE #-}+  headE (SpiderEvent e) = SpiderHostFrame $ SpiderEvent <$> Reflex.Spider.Internal.headE e+  {-# INLINEABLE now #-}+  now = SpiderHostFrame Reflex.Class.now++instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (SpiderHost x) where+  {-# INLINEABLE sample #-}+  sample = runFrame . readBehaviorUntracked . unSpiderBehavior++instance HasSpiderTimeline x => Reflex.Class.MonadSample (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where+  {-# SPECIALIZE instance Reflex.Class.MonadSample (SpiderTimeline Global) (Reflex.Spider.Internal.ReadPhase Global) #-}+  {-# INLINEABLE sample #-}+  sample = Reflex.Spider.Internal.ReadPhase . Reflex.Class.sample++instance HasSpiderTimeline x => Reflex.Class.MonadHold (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where+  {-# SPECIALIZE instance Reflex.Class.MonadHold (SpiderTimeline Global) (Reflex.Spider.Internal.ReadPhase Global) #-}+  {-# INLINE hold #-}+  hold v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.hold v0 e+  {-# INLINEABLE holdDyn #-}+  holdDyn v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdDyn v0 e+  {-# INLINEABLE holdIncremental #-}+  holdIncremental v0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.holdIncremental v0 e+  {-# INLINEABLE buildDynamic #-}+  buildDynamic getV0 e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.buildDynamic getV0 e+  {-# INLINE headE #-}+  headE e = Reflex.Spider.Internal.ReadPhase $ Reflex.Class.headE e+  {-# INLINEABLE now #-}+  now = Reflex.Spider.Internal.ReadPhase Reflex.Class.now++instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where+  {-# INLINEABLE subscribeEvent #-}+  subscribeEvent e = SpiderHostFrame $ do+    -- TODO: Unsubscribe eventually (manually and/or with weak ref)+    val <- liftIO $ newIORef Nothing+    subscription <-+      subscribe (unSpiderEvent e) $+        Subscriber+          { subscriberPropagate = setOccurrence "subscribeEvent" val+          , subscriberInvalidateHeight = \_ -> return ()+          , subscriberRecalculateHeight = \_ -> return ()+          }+    return $+      SpiderEventHandle+        { spiderEventHandleSubscription = subscription+        , spiderEventHandleValue = val+        }++instance HasSpiderTimeline x => Reflex.Host.Class.ReflexHost (SpiderTimeline x) where+  {-# SPECIALIZE instance Reflex.Host.Class.ReflexHost (SpiderTimeline Global) #-}+  type EventTrigger (SpiderTimeline x) = RootTrigger x+  type EventHandle (SpiderTimeline x) = SpiderEventHandle x+  type HostFrame (SpiderTimeline x) = SpiderHostFrame x++instance HasSpiderTimeline x => Reflex.Host.Class.MonadReadEvent (SpiderTimeline x) (Reflex.Spider.Internal.ReadPhase x) where+  {-# NOINLINE readEvent #-}+  readEvent h = Reflex.Spider.Internal.ReadPhase $ fmap (fmap return) $ liftIO $ do+    result <- readIORef $ spiderEventHandleValue h+    touch h+    return result++instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where+  newEventWithTrigger = SpiderHost . fmap SpiderEvent . newEventWithTriggerIO+  newFanEventWithTrigger f = SpiderHost $ do+    es <- newFanEventWithTriggerIO f+    return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es++instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where+  newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO+  newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do+    es <- newFanEventWithTriggerIO f+    return $ Reflex.Class.EventSelector $ SpiderEvent . Reflex.Spider.Internal.select es++instance HasSpiderTimeline x => Reflex.Host.Class.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where+  {-# INLINEABLE subscribeEvent #-}+  subscribeEvent = runFrame . runSpiderHostFrame . Reflex.Host.Class.subscribeEvent++instance HasSpiderTimeline x => Reflex.Host.Class.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where+  {-# SPECIALIZE instance Reflex.Host.Class.MonadReflexHost (SpiderTimeline Global) (SpiderHost Global) #-}+  type ReadPhase (SpiderHost x) = Reflex.Spider.Internal.ReadPhase x+  fireEventsAndRead es (Reflex.Spider.Internal.ReadPhase a) = run es a+  runHostFrame = runFrame . runSpiderHostFrame++unsafeNewSpiderTimelineEnv :: forall x. IO (SpiderTimelineEnv x)+unsafeNewSpiderTimelineEnv = do+  lock <- newMVar ()+  env <- newEventEnv+  depthRef <- newTraceDepthRef+  return+    $ STE+    $ SpiderTimelineEnv+      { _spiderTimeline_lock = lock+      , _spiderTimeline_eventEnv = env+      , _spiderTimeline_depth = depthRef+      }++-- | Create a new SpiderTimelineEnv+newSpiderTimeline :: IO (Some SpiderTimelineEnv)+newSpiderTimeline = withSpiderTimeline (pure . Some)++data LocalSpiderTimeline (x :: Type) s++instance+  Reifies s (SpiderTimelineEnv x)+  => HasSpiderTimeline (LocalSpiderTimeline x s)+  where+  spiderTimeline = localSpiderTimeline Proxy $ reflect (Proxy :: Proxy s)++localSpiderTimeline+  :: proxy s+  -> SpiderTimelineEnv x+  -> SpiderTimelineEnv (LocalSpiderTimeline x s)+localSpiderTimeline _ = coerce++-- | Pass a new timeline to the given function.+withSpiderTimeline :: (forall x. HasSpiderTimeline x => SpiderTimelineEnv x -> IO r) -> IO r+withSpiderTimeline k = do+  env <- unsafeNewSpiderTimelineEnv+  reify env $ \s -> k $ localSpiderTimeline s env++newtype SpiderPullM (x :: Type) a = SpiderPullM (BehaviorM x a) deriving (Applicative, Functor, Monad, MonadFix, MonadIO)++newtype SpiderPushM (x :: Type) a = SpiderPushM (EventM x a) deriving (Applicative, Functor, Monad, MonadFix, MonadIO)++instance HasSpiderTimeline x => R.Reflex (SpiderTimeline x) where+  {-# SPECIALIZE instance R.Reflex (SpiderTimeline Global) #-}++  -- The methods that build events are INLINE, because in the SPECIALIZE+  -- dictionary the cached primitives are already specialized and the rewrite+  -- rules don't match them.+  newtype Behavior (SpiderTimeline x) a = SpiderBehavior {unSpiderBehavior :: Behavior x a}+  newtype Event (SpiderTimeline x) a = SpiderEvent {unSpiderEvent :: Event x a}+  newtype Dynamic (SpiderTimeline x) a = SpiderDynamic {unSpiderDynamic :: DynamicS x (Identity a)} -- deriving (Functor, Applicative, Monad)+  newtype Incremental (SpiderTimeline x) p = SpiderIncremental {unSpiderIncremental :: DynamicS x p}+  type PullM (SpiderTimeline x) = SpiderPullM x+  type PushM (SpiderTimeline x) = SpiderPushM x+  {-# INLINEABLE never #-}+  never = SpiderEvent eventNever+  {-# INLINEABLE constant #-}+  constant = SpiderBehavior . behaviorConst+  {-# INLINE push #-}+  push f = SpiderEvent . push (coerce f) . unSpiderEvent+  {-# INLINE pushCheap #-}+  pushCheap f = SpiderEvent . pushCheap (coerce f) . unSpiderEvent+  {-# INLINEABLE pull #-}+  pull = SpiderBehavior . pull . coerce+  {-# INLINE fanG #-}+  fanG e = R.EventSelectorG $ SpiderEvent . selectG (fanG (unSpiderEvent e))+  {-# INLINE mergeG #-}+  mergeG+    :: forall k2 (k :: k2 -> Type) q (v :: k2 -> Type)+     . GCompare k+    => (forall a. q a -> R.Event (SpiderTimeline x) (v a))+    -> DMap k q+    -> R.Event (SpiderTimeline x) (DMap k v)+  mergeG nt = SpiderEvent . mergeG (unSpiderEvent #. nt) . dynamicConst+  {-# INLINE switch #-}+  switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior+  {-# INLINE coincidence #-}+  coincidence = SpiderEvent . coincidence . unSpiderEvent+  {-# INLINEABLE current #-}+  current = SpiderBehavior . dynamicCurrent . unSpiderDynamic+  {-# INLINE updated #-}+  updated = SpiderEvent #. dynamicUpdated .# fmap coerce . unSpiderDynamic+  {-# INLINEABLE unsafeBuildDynamic #-}+  unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ coerce $ unSpiderEvent v'+  {-# INLINEABLE unsafeBuildIncremental #-}+  unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeBuildDynamic (coerce readV0) $ unSpiderEvent dv+  {-# INLINE mergeIncrementalG #-}+  mergeIncrementalG nt = SpiderEvent #. mergeG (coerce #. nt) .# unSpiderIncremental+  {-# INLINE mergeIncrementalWithMoveG #-}+  mergeIncrementalWithMoveG nt = SpiderEvent #. mergeWithMove (coerce #. nt) .# unSpiderIncremental+  {-# INLINEABLE currentIncremental #-}+  currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental+  {-# INLINE updatedIncremental #-}+  updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental+  {-# INLINEABLE incrementalToDynamic #-}+  incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDyn $ unsafeBuildDynamic (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do+    c <- readBehaviorUntracked $ dynamicCurrent i+    return $ Identity <$> apply p c -- TODO: Avoid the redundant 'apply'+  eventCoercion Coercion = Coercion+  behaviorCoercion Coercion = Coercion+  dynamicCoercion Coercion = Coercion+  incrementalCoercion Coercion Coercion = Coercion+  {-# INLINE mergeIntIncremental #-}+  mergeIntIncremental = SpiderEvent . mergeInt . coerce+  {-# INLINE fanInt #-}+  fanInt e = R.EventSelectorInt $ SpiderEvent . selectInt (fanInt (unSpiderEvent e))++data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)++data SpiderEventHandle x a = SpiderEventHandle+  { spiderEventHandleSubscription :: EventSubscription x+  , spiderEventHandleValue :: IORef (Maybe a)+  }++instance MonadRef (EventM x) where+  type Ref (EventM x) = Ref IO+  {-# INLINEABLE newRef #-}+  {-# INLINEABLE readRef #-}+  {-# INLINEABLE writeRef #-}+  newRef = liftIO . newRef+  readRef = liftIO . readRef+  writeRef r a = liftIO $ writeRef r a++instance MonadAtomicRef (EventM x) where+  {-# INLINEABLE atomicModifyRef #-}+  atomicModifyRef r f = liftIO $ atomicModifyRef r f++-- | The monad for actions that manipulate a Spider timeline identified by @x@+newtype SpiderHost (x :: Type) a = SpiderHost {unSpiderHost :: IO a}+  deriving (Applicative, Functor, MonadAsyncException, MonadException, MonadFix, MonadIO)++instance Monad (SpiderHost x) where+  {-# INLINEABLE (>>=) #-}+  SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f+#if !MIN_VERSION_base(4,13,0)+  {-# INLINABLE fail #-}+  fail = MonadFail.fail+#endif++instance MonadFail (SpiderHost x) where+  {-# INLINEABLE fail #-}+  fail s = SpiderHost $ MonadFail.fail s++-- | Run an action affecting the global Spider timeline; this will be guarded by+-- a mutex for that timeline+runSpiderHost :: SpiderHost Global a -> IO a+runSpiderHost (SpiderHost a) = a++-- | Run an action affecting a given Spider timeline; this will be guarded by a+-- mutex for that timeline+runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimelineEnv x -> IO a+runSpiderHostForTimeline (SpiderHost a) _ = a++newtype SpiderHostFrame (x :: Type) a = SpiderHostFrame {runSpiderHostFrame :: EventM x a}+  deriving (Applicative, Functor, MonadAsyncException, MonadCatch, MonadException, MonadFix, MonadIO, MonadMask, MonadThrow)++instance Monad (SpiderHostFrame x) where+  {-# INLINEABLE (>>=) #-}+  SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f+#if !MIN_VERSION_base(4,13,0)+  {-# INLINABLE fail #-}+  fail s = SpiderHostFrame $ fail s+#endif++instance NotReady (SpiderTimeline x) (SpiderHostFrame x) where+  notReadyUntil _ = pure ()+  notReady = pure ()++newEventWithTriggerIO :: forall x a. HasSpiderTimeline x => (RootTrigger x a -> IO (IO ())) -> IO (Event x a)+newEventWithTriggerIO f = do+  es <- newFanEventWithTriggerIO $ \Refl -> f+  return $ select es Refl++newFanEventWithTriggerIO :: (HasSpiderTimeline x, GCompare k) => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)+newFanEventWithTriggerIO f = do+  occRef <- newIORef DMap.empty+  subscribedRef <- newIORef DMap.empty+  node <- mkEventNode zeroHeight (pure []) (return ["root"])+  let !r =+        Root+          { rootOccurrence = occRef+          , rootSubscribed = subscribedRef+          , rootInit = f+          , rootNode = node+          }+  return $ EventSelector $ \k -> eventRoot k r++newtype ReadPhase x a = ReadPhase (EventM x a) deriving (Applicative, Functor, Monad, MonadFix)  instance MonadRef (SpiderHost x) where   type Ref (SpiderHost x) = Ref IO
src/Reflex/Time.hs view
@@ -9,6 +9,7 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-}+ -- | -- Module: --   Reflex.Time@@ -43,13 +44,14 @@  -- | Metadata associated with a timer "tick" data TickInfo-  = TickInfo { _tickInfo_lastUTC :: UTCTime-             -- ^ UTC time immediately after the last tick.-             , _tickInfo_n :: Integer-             -- ^ Number of time periods or ticks since the start of the timer-             , _tickInfo_alreadyElapsed :: NominalDiffTime-             -- ^ Amount of time that has elapsed in the current tick period.-             }+  = TickInfo+  { _tickInfo_lastUTC :: UTCTime+  -- ^ UTC time immediately after the last tick.+  , _tickInfo_n :: Integer+  -- ^ Number of time periods or ticks since the start of the timer+  , _tickInfo_alreadyElapsed :: NominalDiffTime+  -- ^ Amount of time that has elapsed in the current tick period.+  }   deriving (Eq, Ord, Show)  -- | Fires an 'Event' once every time provided interval elapses, approximately.@@ -69,33 +71,34 @@ -- | Fires an 'Event' approximately each time the provided interval elapses. If the system starts running behind, occurrences will be dropped rather than buffered. -- Each occurrence of the resulting event will contain the index of the current interval, with 0 representing the provided initial time. tickLossyFrom-    :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)-    => NominalDiffTime-    -- ^ The length of a tick interval-    -> UTCTime-    -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.-    -> Event t a-    -- ^ Event that starts a tick generation thread.  Usually you want this to-    -- be something like the result of getPostBuild that only fires once.  But-    -- there could be uses for starting multiple timer threads.-    -> m (Event t TickInfo)+  :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)+  => NominalDiffTime+  -- ^ The length of a tick interval+  -> UTCTime+  -- ^ The basis time from which intervals count and with which the initial calculation of elapsed time will be made.+  -> Event t a+  -- ^ Event that starts a tick generation thread.  Usually you want this to+  -- be something like the result of getPostBuild that only fires once.  But+  -- there could be uses for starting multiple timer threads.+  -> m (Event t TickInfo) tickLossyFrom dt t0 e = tickLossyFrom' $ (dt, t0) <$ e  -- | Generalization of tickLossyFrom that takes the delay and initial time as an 'Event'. tickLossyFrom'-    :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)-    => Event t (NominalDiffTime, UTCTime)-    -- ^ Event that starts a tick generation thread.  Usually you want this to-    -- be something like the result of 'getPostBuild' that only fires once.  But-    -- there could be uses for starting multiple timer threads.-    -> m (Event t TickInfo)+  :: (PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), MonadFix m)+  => Event t (NominalDiffTime, UTCTime)+  -- ^ Event that starts a tick generation thread.  Usually you want this to+  -- be something like the result of 'getPostBuild' that only fires once.  But+  -- there could be uses for starting multiple timer threads.+  -> m (Event t TickInfo) tickLossyFrom' e = do   rec result <- performEventAsync $ callAtNextInterval <$> leftmost [e, snd <$> result]   return $ fst <$> result-  where callAtNextInterval pair cb = void $ liftIO $ forkIO $ do-          tick <- uncurry getCurrentTick pair-          Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000-          cb (tick, pair)+  where+    callAtNextInterval pair cb = void $ liftIO $ forkIO $ do+      tick <- uncurry getCurrentTick pair+      Concurrent.delay $ ceiling $ (fst pair - _tickInfo_alreadyElapsed tick) * 1000000+      cb (tick, pair)  -- | Like 'tickLossy', but immediately calculates the first tick and provides a 'Dynamic' that is updated as ticks fire. clockLossy :: (MonadIO m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m), PostBuild t m, MonadHold t m, MonadFix m) => NominalDiffTime -> UTCTime -> m (Dynamic t TickInfo)@@ -138,7 +141,6 @@   -> m (Event t TickInfo) poissonLossyFrom rnd rate = inhomogeneousPoissonFrom rnd (constant rate) rate - -- | Send events with Poisson timing with the given basis and rate --   Each occurrence of the resulting event will contain the index of --   the current interval, with 0 representing the basis time.@@ -164,18 +166,16 @@   -> Event t a   -> m (Event t TickInfo) inhomogeneousPoissonFrom rnd rate maxRate t0 e = do-   -- Create a thread for producing homogeneous poisson events   -- along with random Doubles (usage of Double's explained below)-  ticksWithRateRand <- performEventAsync $-                       fmap callAtNextInterval e+  ticksWithRateRand <-+    performEventAsync $+      fmap callAtNextInterval e    -- Filter homogeneous events according to associated   -- random values and the current rate parameter   return $ attachWithMaybe filterFun rate ticksWithRateRand-   where-     -- Inhomogeneous poisson processes are built from faster     -- homogeneous ones by randomly dropping events from the     -- fast process. For each fast homogeneous event, choose@@ -184,7 +184,7 @@     -- random sample, then keep this event, otherwise drop it     filterFun :: Double -> (TickInfo, Double) -> Maybe TickInfo     filterFun r (tInfo, p)-      | r >= p    = Just tInfo+      | r >= p = Just tInfo       | otherwise = Nothing      callAtNextInterval _ cb = void $ liftIO $ forkIO $ go t0 rnd cb 0@@ -194,16 +194,16 @@        -- Generate random numbers for this poisson interval (u)       -- and sample-retention likelihood (p)-      let (u, nextGen)            = randomR (0,1) lastGen-          (p :: Double, nextGen') = randomR (0,maxRate) nextGen+      let (u, nextGen) = randomR (0, 1) lastGen+          (p :: Double, nextGen') = randomR (0, maxRate) nextGen        -- Inter-event interval is drawn from exponential       -- distribution accourding to u-      let dt             = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime-          nEvents        = lastN + 1+      let dt = realToFrac $ (-1) * log u / maxRate :: NominalDiffTime+          nEvents = lastN + 1           alreadyElapsed = diffUTCTime t tTargetLast-          tTarget        = addUTCTime dt tTargetLast-          thisDelay      = realToFrac $ diffUTCTime tTarget t :: Double+          tTarget = addUTCTime dt tTargetLast+          thisDelay = realToFrac $ diffUTCTime tTarget t :: Double       Concurrent.delay $ ceiling $ thisDelay * 1000000       _ <- cb (TickInfo t nEvents alreadyElapsed, p)       go tTarget nextGen' cb nEvents@@ -235,14 +235,15 @@ batchOccurrences :: (MonadFix m, MonadHold t m, PerformEvent t m, TriggerEvent t m, MonadIO (Performable m)) => NominalDiffTime -> Event t a -> m (Event t (Seq a)) batchOccurrences t newValues = do   let f s x = (Just newState, out)-        where newState = case x of-                This a -> s |> a-                That _ -> mempty-                These a _ -> Seq.singleton a-              out = case x of-                This _ -> if Seq.null s then Just () else Nothing-                That _ -> Nothing-                These _ _ -> Just ()+        where+          newState = case x of+            This a -> s |> a+            That _ -> mempty+            These a _ -> Seq.singleton a+          out = case x of+            This _ -> if Seq.null s then Just () else Nothing+            That _ -> Nothing+            These _ _ -> Just ()   rec (buffer, toDelay) <- mapAccumMaybe f mempty $ align newValues delayed       delayed <- delay t toDelay   return $ tag buffer delayed@@ -255,24 +256,28 @@   let f (immediate, buffer) x = case x of -- (Just newState, out)         This a -- If only the input event fires           | immediate -> -- and we're in immediate mode-            -- Immediate mode turns off, and the buffer is empty.-            -- We fire the output event with the input event value immediately.-            (Just (False, Nothing), Just a)+          -- Immediate mode turns off, and the buffer is empty.+          -- We fire the output event with the input event value immediately.+              (Just (False, Nothing), Just a)           | otherwise -> -- and we're not in immediate mode-            -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.-            -- We don't fire the output event.-            (Just (False, Just a), Nothing)-        That _ -> -- If only the delayed output event fires,+          -- Immediate mode remains off, and we replace the contents of the buffer (if any) with the input value.+          -- We don't fire the output event.+              (Just (False, Just a), Nothing)+        That _ ->+          -- If only the delayed output event fires,           case buffer of-            Nothing -> -- and the buffer is empty:+            Nothing ->+              -- and the buffer is empty:               -- Immediate mode turns back on, and the buffer remains empty.               -- We don't fire.               (Just (True, Nothing), Nothing)-            Just b -> -- and the buffer is full:+            Just b ->+              -- and the buffer is full:               -- Immediate mode remains off, and the buffer is cleared.               -- We fire with the buffered value.               (Just (False, Nothing), Just b)-        These a _ -> -- If both the input and delayed output event fire simultaneously:+        These a _ ->+          -- If both the input and delayed output event fire simultaneously:           -- Immediate mode turns off, and the buffer is empty.           -- We fire with the input event's value, as it is the most recent we have seen at this moment.           (Just (False, Nothing), Just a)@@ -283,13 +288,13 @@ data ThrottleState b   = ThrottleState_Immediate   | ThrottleState_Buffered (ThrottleBuffer b)-  deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data)+  deriving (Data, Eq, Foldable, Functor, Generic, Ord, Show, Traversable)  data ThrottleBuffer b   = ThrottleBuffer_Empty -- Empty conflicts with lens, and hiding it would require turning-                         -- on PatternSynonyms+  -- on PatternSynonyms   | ThrottleBuffer_Full b-  deriving (Eq, Ord, Show, Functor, Foldable, Traversable, Generic, Data)+  deriving (Data, Eq, Foldable, Functor, Generic, Ord, Show, Traversable)  instance Semigroup b => Semigroup (ThrottleBuffer b) where   x <> y = case x of@@ -313,56 +318,77 @@ -- -- NB: The provided lag function must *actually* delay the event. throttleBatchWithLag :: (MonadFix m, MonadHold t m, PerformEvent t m, Semigroup a) => (Event t () -> m (Event t ())) -> Event t a -> m (Event t a)+ -- Invariants:+ -- * Immediate mode must turn off whenever output is produced.+ -- * Output must be produced whenever immediate mode turns from on to off.+ -- * Immediate mode can only go from off to on when the delayed event fires.+ -- * Every input firing must go into either an immediate output firing or the+ --   buffer, but not both.+ -- * An existing full buffer must either stay in the buffer or go to output,+ --   but not both. throttleBatchWithLag lag e = do   let f state x = case x of -- (Just $ newState, out)-        This a -> -- If only the input event fires+        This a ->+          -- If only the input event fires           case state of-            ThrottleState_Immediate -> -- and we're in immediate mode+            ThrottleState_Immediate ->+              -- and we're in immediate mode               -- Immediate mode turns off, and the buffer is empty.               -- We fire the output event with the input event value immediately.-              (Just $ ThrottleState_Buffered $ ThrottleBuffer_Empty, Just a)-            ThrottleState_Buffered b -> -- and we're not in immediate mode+              (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)+            ThrottleState_Buffered b ->+              -- and we're not in immediate mode               -- Immediate mode remains off, and we accumulate the input value.               -- We don't fire the output event.               (Just $ ThrottleState_Buffered $ b <> ThrottleBuffer_Full a, Nothing)-        That _ -> -- If only the delayed output event fires,+        That _ ->+          -- If only the delayed output event fires,           case state of-            ThrottleState_Immediate -> -- and we're in immediate mode+            ThrottleState_Immediate ->+              -- and we're in immediate mode               -- Nothing happens.               (Nothing, Nothing)-            ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:+            ThrottleState_Buffered ThrottleBuffer_Empty ->+              -- and the buffer is empty:               -- Immediate mode turns back on, and the buffer remains empty.               -- We don't fire.               (Just ThrottleState_Immediate, Nothing)-            ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:+            ThrottleState_Buffered (ThrottleBuffer_Full b) ->+              -- and the buffer is full:               -- Immediate mode remains off, and the buffer is cleared.               -- We fire with the buffered value.               (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just b)-        These a _ -> -- If both the input and delayed output event fire simultaneously:+        These a _ ->+          -- If both the input and delayed output event fire simultaneously:           case state of-            ThrottleState_Immediate -> -- and we're in immediate mode+            ThrottleState_Immediate ->+              -- and we're in immediate mode               -- Immediate mode turns off, and the buffer is empty.               -- We fire with the input event's value, as it is the most recent we have seen at this moment.               (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)-            ThrottleState_Buffered ThrottleBuffer_Empty -> -- and the buffer is empty:+            ThrottleState_Buffered ThrottleBuffer_Empty ->+              -- and the buffer is empty:               -- Immediate mode stays off, and the buffer remains empty.               -- We fire with the input event's value.               (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just a)-            ThrottleState_Buffered (ThrottleBuffer_Full b) -> -- and the buffer is full:+            ThrottleState_Buffered (ThrottleBuffer_Full b) ->+              -- and the buffer is full:               -- Immediate mode remains off, and the buffer is cleared.               -- We fire with everything including the buffered value.               (Just $ ThrottleState_Buffered ThrottleBuffer_Empty, Just (b <> a))-  rec (_stateDyn, outE) <- mapAccumMaybeDyn f-        ThrottleState_Immediate -- We start in immediate mode with an empty buffer.-        (align e delayed)+  rec (_stateDyn, outE) <-+        mapAccumMaybeDyn+          f+          ThrottleState_Immediate -- We start in immediate mode with an empty buffer.+          (align e delayed)       delayed <- lag (void outE)   return outE @@ -370,7 +396,7 @@ tickInfo_lastUTC f (TickInfo x1 x2 x3) = (\y -> TickInfo y x2 x3) <$> f x1 {-# INLINE tickInfo_lastUTC #-} -tickInfo_n :: Functor f => (Integer  -> f Integer ) -> TickInfo -> f TickInfo+tickInfo_n :: Functor f => (Integer -> f Integer) -> TickInfo -> f TickInfo tickInfo_n f (TickInfo x1 x2 x3) = (\y -> TickInfo x1 y x3) <$> f x2 {-# INLINE tickInfo_n #-} 
src/Reflex/TriggerEvent/Base.hs view
@@ -1,5 +1,3 @@--- | This module defines 'TriggerEventT', the standard implementation of--- 'TriggerEvent'. {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-}@@ -8,6 +6,8 @@ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} +-- | This module defines 'TriggerEventT', the standard implementation of+-- 'TriggerEvent'. module Reflex.TriggerEvent.Base   ( TriggerEventT (..)   , runTriggerEventT@@ -17,7 +17,7 @@   ) where  import Control.Concurrent-import Control.Monad.Catch (MonadMask, MonadThrow, MonadCatch)+import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow) import Control.Monad.Exception import Control.Monad.Fix import Control.Monad.Primitive@@ -33,8 +33,8 @@ import Data.Monoid ((<>)) #endif -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.Host.Class import Reflex.PerformEvent.Class import Reflex.PostBuild.Class@@ -45,11 +45,11 @@ data TriggerInvocation a = TriggerInvocation a (IO ())  -- | A reference to an 'EventTrigger' suitable for firing with 'TriggerEventT'.-newtype EventTriggerRef t a = EventTriggerRef { unEventTriggerRef :: IORef (Maybe (EventTrigger t a)) }+newtype EventTriggerRef t a = EventTriggerRef {unEventTriggerRef :: IORef (Maybe (EventTrigger t a))}  -- | A basic implementation of 'TriggerEvent'.-newtype TriggerEventT t m a = TriggerEventT { unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a }-  deriving (Functor, Applicative, Monad, MonadFix, MonadIO, MonadException, MonadAsyncException, MonadCatch, MonadThrow, MonadMask)+newtype TriggerEventT t m a = TriggerEventT {unTriggerEventT :: ReaderT (Chan [DSum (EventTriggerRef t) TriggerInvocation]) m a}+  deriving (Applicative, Functor, Monad, MonadAsyncException, MonadCatch, MonadException, MonadFix, MonadIO, MonadMask, MonadThrow)  -- | Run a 'TriggerEventT' action.  The argument should be a 'Chan' into which -- 'TriggerInvocation's can be passed; it is expected that some other thread@@ -59,89 +59,93 @@ runTriggerEventT = runReaderT . unTriggerEventT  instance MonadTrans (TriggerEventT t) where-  {-# INLINABLE lift #-}+  {-# INLINEABLE lift #-}   lift = TriggerEventT . lift  instance PrimMonad m => PrimMonad (TriggerEventT t m) where   type PrimState (TriggerEventT t m) = PrimState m-  {-# INLINABLE primitive #-}+  {-# INLINEABLE primitive #-}   primitive = lift . primitive  instance PerformEvent t m => PerformEvent t (TriggerEventT t m) where   type Performable (TriggerEventT t m) = Performable m-  {-# INLINABLE performEvent_ #-}+  {-# INLINEABLE performEvent_ #-}   performEvent_ e = lift $ performEvent_ e-  {-# INLINABLE performEvent #-}+  {-# INLINEABLE performEvent #-}   performEvent e = lift $ performEvent e  instance PostBuild t m => PostBuild t (TriggerEventT t m) where-  {-# INLINABLE getPostBuild #-}+  {-# INLINEABLE getPostBuild #-}   getPostBuild = lift getPostBuild  instance MonadReflexCreateTrigger t m => MonadReflexCreateTrigger t (TriggerEventT t m) where-  {-# INLINABLE newEventWithTrigger #-}+  {-# INLINEABLE newEventWithTrigger #-}   newEventWithTrigger = lift . newEventWithTrigger-  {-# INLINABLE newFanEventWithTrigger #-}+  {-# INLINEABLE newFanEventWithTrigger #-}   newFanEventWithTrigger f = lift $ newFanEventWithTrigger f  instance (Monad m, MonadRef m, Ref m ~ Ref IO, MonadReflexCreateTrigger t m) => TriggerEvent t (TriggerEventT t m) where-  {-# INLINABLE newTriggerEvent #-}+  {-# INLINEABLE newTriggerEvent #-}   newTriggerEvent = do     (e, t) <- newTriggerEventWithOnComplete     return (e, \a -> t a $ return ())-  {-# INLINABLE newTriggerEventWithOnComplete #-}+  {-# INLINEABLE newTriggerEventWithOnComplete #-}   newTriggerEventWithOnComplete = do     events <- askEvents     (eResult, reResultTrigger) <- lift newEventWithTriggerRef     return . (,) eResult $ \a cb ->       writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]-  {-# INLINABLE newEventWithLazyTriggerWithOnComplete #-}+  {-# INLINEABLE newEventWithLazyTriggerWithOnComplete #-}   newEventWithLazyTriggerWithOnComplete f = do     events <- askEvents-    lift . newEventWithTrigger $ \t ->-      f $ \a cb -> do-        reResultTrigger <- newRef $ Just t+    reResultTrigger <- newRef Nothing+    lift . newEventWithTrigger $ \t -> do+      writeRef reResultTrigger $ Just t+      teardown <- f $ \a cb ->         writeChan events [EventTriggerRef reResultTrigger :=> TriggerInvocation a cb]+      return $ do+        writeRef reResultTrigger Nothing+        teardown  instance MonadRef m => MonadRef (TriggerEventT t m) where   type Ref (TriggerEventT t m) = Ref m-  {-# INLINABLE newRef #-}+  {-# INLINEABLE newRef #-}   newRef = lift . newRef-  {-# INLINABLE readRef #-}+  {-# INLINEABLE readRef #-}   readRef = lift . readRef-  {-# INLINABLE writeRef #-}+  {-# INLINEABLE writeRef #-}   writeRef r = lift . writeRef r  instance MonadAtomicRef m => MonadAtomicRef (TriggerEventT t m) where-  {-# INLINABLE atomicModifyRef #-}+  {-# INLINEABLE atomicModifyRef #-}   atomicModifyRef r = lift . atomicModifyRef r  instance MonadSample t m => MonadSample t (TriggerEventT t m) where-  {-# INLINABLE sample #-}+  {-# INLINEABLE sample #-}   sample = lift . sample  instance MonadHold t m => MonadHold t (TriggerEventT t m) where-  {-# INLINABLE hold #-}+  {-# INLINEABLE hold #-}   hold v0 v' = lift $ hold v0 v'-  {-# INLINABLE holdDyn #-}+  {-# INLINEABLE holdDyn #-}   holdDyn v0 v' = lift $ holdDyn v0 v'-  {-# INLINABLE holdIncremental #-}+  {-# INLINEABLE holdIncremental #-}   holdIncremental v0 v' = lift $ holdIncremental v0 v'-  {-# INLINABLE buildDynamic #-}+  {-# INLINEABLE buildDynamic #-}   buildDynamic a0 = lift . buildDynamic a0-  {-# INLINABLE headE #-}+  {-# INLINEABLE headE #-}   headE = lift . headE-  {-# INLINABLE now #-}+  {-# INLINEABLE now #-}   now = lift now  instance Adjustable t m => Adjustable t (TriggerEventT t m) where-  {-# INLINABLE runWithReplace #-}+  {-# INLINEABLE runWithReplace #-}   runWithReplace (TriggerEventT a0) a' = TriggerEventT $ runWithReplace a0 (coerceEvent a')-  {-# INLINABLE traverseIntMapWithKeyWithAdjust #-}+  {-# INLINEABLE traverseIntMapWithKeyWithAdjust #-}   traverseIntMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseIntMapWithKeyWithAdjust (coerce . f) dm0 dm'-  {-# INLINABLE traverseDMapWithKeyWithAdjust #-}+  {-# INLINEABLE traverseDMapWithKeyWithAdjust #-}   traverseDMapWithKeyWithAdjust f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjust (coerce . f) dm0 dm'-  {-# INLINABLE traverseDMapWithKeyWithAdjustWithMove #-}+  {-# INLINEABLE traverseDMapWithKeyWithAdjustWithMove #-}   traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = TriggerEventT $ traverseDMapWithKeyWithAdjustWithMove (coerce . f) dm0 dm'  -- TODO: Monoid and Semigroup can likely be derived once ReaderT has them.@@ -151,7 +155,6 @@  instance (S.Semigroup a, Applicative m) => S.Semigroup (TriggerEventT t m a) where   (<>) = liftA2 (S.<>)-  -- | Retrieve the current 'Chan'; event trigger invocations pushed into it will -- be fired.
src/Reflex/TriggerEvent/Class.hs view
@@ -1,21 +1,22 @@--- | This module defines 'TriggerEvent', which describes actions that may create--- new 'Event's that can be triggered from 'IO'. {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} +-- | This module defines 'TriggerEvent', which describes actions that may create+-- new 'Event's that can be triggered from 'IO'. module Reflex.TriggerEvent.Class   ( TriggerEvent (..)   ) where -import Reflex.Class- import Control.Monad.Reader import Control.Monad.State import qualified Control.Monad.State.Strict as Strict import Control.Monad.Trans.Maybe (MaybeT) ---TODO: Shouldn't have IO hard-coded+import Reflex.Class++-- TODO: Shouldn't have IO hard-coded+ -- | 'TriggerEvent' represents actions that can create 'Event's that can be -- triggered by 'IO' actions. class Monad m => TriggerEvent t m | m -> t where@@ -23,16 +24,19 @@   -- the resulting 'Event' will fire at some point in the future.  Note that   -- this may not be synchronous.   newTriggerEvent :: m (Event t a, a -> IO ())+   -- | Like 'newTriggerEvent', but the callback itself takes another callback,   -- to be invoked once the requested 'Event' occurrence has finished firing.   -- This allows synchronous operation.-  newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) --TODO: This and newTriggerEvent should be unified somehow+  newTriggerEventWithOnComplete :: m (Event t a, a -> IO () -> IO ()) -- TODO: This and newTriggerEvent should be unified somehow+   -- | Like 'newTriggerEventWithOnComplete', but with setup and teardown.  This   -- relatively complex type signature allows any external listeners to be   -- subscribed lazily and then removed whenever the returned 'Event' is no   -- longer being listened to.  Note that the setup/teardown may happen multiple   -- times, and there is no guarantee that the teardown will be executed-  -- promptly, or even at all, in the case of program termination.+  -- promptly, or even at all, in the case of program termination. The setup+  -- and teardown must not run a frame.   newEventWithLazyTriggerWithOnComplete :: ((a -> IO () -> IO ()) -> IO (IO ())) -> m (Event t a)  instance TriggerEvent t m => TriggerEvent t (ReaderT r m) where
src/Reflex/Widget/Basic.hs view
@@ -7,11 +7,10 @@  import Control.Monad.Fix (MonadFix) import Data.Map (Map)--import Reflex.Class-import Reflex.Adjustable.Class import Data.Patch.MapWithMove +import Reflex.Adjustable.Class+import Reflex.Class  -- | Build sortable content in such a way that re-sorting it can cause minimal -- disruption to an existing context.@@ -29,11 +28,16 @@ -- >   (\k v -> text $ "\n" ++ show k ++ " " ++ v)  -- show each element on a new line -- >   (Map.fromList $ zip [0..] [(3, "a"), (2, "b"), (1, "c")]) -- >   sortEvent-sortableList :: forall t m k v a. (MonadHold t m, MonadFix m, Adjustable t m, Ord k)-             => (k -> v -> m a) -- ^ Function to render the content for each key/value pair-             -> Map k v -- ^ The sortable list with an initial ordering determined by the @Map@ keys in ascending order-             -> Event t (v -> v -> Ordering) -- ^ An event carrying a sort function for the list-             -> m (Map k a)+sortableList+  :: forall t m k v a+   . (MonadHold t m, MonadFix m, Adjustable t m, Ord k)+  => (k -> v -> m a)+  -- ^ Function to render the content for each key/value pair+  -> Map k v+  -- ^ The sortable list with an initial ordering determined by the @Map@ keys in ascending order+  -> Event t (v -> v -> Ordering)+  -- ^ An event carrying a sort function for the list+  -> m (Map k a) sortableList f m0 reSortFunc = do   rec let reSortPatch = attachWith (flip patchThatSortsMapWith) (currentIncremental m) reSortFunc       m <- holdIncremental m0 reSortPatch
src/Reflex/Workflow.hs view
@@ -19,8 +19,8 @@ import Control.Arrow ((***)) import Control.Monad.Fix (MonadFix) -import Reflex.Class import Reflex.Adjustable.Class+import Reflex.Class import Reflex.Network import Reflex.NotReady.Class import Reflex.PostBuild.Class@@ -28,7 +28,7 @@ -- | A widget in a workflow -- -- When the 'Event' returned by a 'Workflow' fires, the current 'Workflow' is replaced by the one inside the firing 'Event'. A series of 'Workflow's must share the same return type.-newtype Workflow t m a = Workflow { unWorkflow :: m (a, Event t (Workflow t m a)) }+newtype Workflow t m a = Workflow {unWorkflow :: m (a, Event t (Workflow t m a))}  -- | Runs a 'Workflow' and returns the 'Dynamic' result of the 'Workflow' (i.e., a 'Dynamic' of the value produced by the current 'Workflow' node, and whose update 'Event' fires whenever one 'Workflow' is replaced by another). workflow :: forall t m a. (Adjustable t m, MonadFix m, MonadHold t m) => Workflow t m a -> m (Dynamic t a)
test/Adjustable.hs view
@@ -1,4 +1,3 @@-{-# LANGUAGE BangPatterns #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-}@@ -6,18 +5,18 @@ module Main where  import Control.Monad.Fix-import Data.Maybe import qualified Data.Map as Map+import Data.Maybe+import Reflex.Patch.MapWithMove  import Reflex import Reflex.EventWriter.Base import Reflex.Network-import Reflex.Patch.MapWithMove import Test.Run  main :: IO () main = do-  let actions =  [ Increment, Update0th, Increment, Swap, Increment, Increment ]+  let actions = [Increment, Update0th, Increment, Swap, Increment, Increment]   os <- runAppB testPatchMapWithMove $ map Just actions   -- If the final counter value in the adjusted widgets corresponds to the number of times it has   -- been incremented, we know that the networks haven't broken.@@ -29,12 +28,12 @@   = Increment   | Swap   | Update0th-  deriving Eq+  deriving (Eq)  -- See https://github.com/reflex-frp/reflex/issues/369 for the bug that this is testing. testPatchMapWithMove   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -44,19 +43,26 @@ testPatchMapWithMove pulse = do   let pulseAction = ffor pulse $ \case         Increment -> Nothing-        Swap -> patchMapWithMove $ Map.fromList-          [ (0, NodeInfo (From_Move 1) (Just 1))-          , (1, NodeInfo (From_Move 0) (Just 0))-          ]-        Update0th -> patchMapWithMove $ Map.fromList-          [ (0, NodeInfo (From_Insert 'z') Nothing) ]+        Swap ->+          patchMapWithMove $+            Map.fromList+              [ (0, NodeInfo (From_Move 1) (Just 1))+              , (1, NodeInfo (From_Move 0) (Just 0))+              ]+        Update0th ->+          patchMapWithMove $+            Map.fromList+              [(0, NodeInfo (From_Insert 'z') Nothing)]   (_, result) <- runBehaviorWriterT $ mdo     counter <- foldDyn (+) 1 $ fmapMaybe (\e -> if isNothing e then Just 1 else Nothing) pulseAction-    _ <- mapMapWithAdjustWithMove-      (\_ _ -> networkHold-        (tellBehavior $ constant [])-        ((\t -> tellBehavior $ constant [t]) <$> updated counter))-      (Map.fromList $ zip [0..] "ab")-      (fmapMaybe id pulseAction)+    _ <-+      mapMapWithAdjustWithMove+        ( \_ _ ->+            networkHold+              (tellBehavior $ constant [])+              ((\t -> tellBehavior $ constant [t]) <$> updated counter)+        )+        (Map.fromList $ zip [0 ..] "ab")+        (fmapMaybe id pulseAction)     return ()   return result
test/DebugCycles.hs view
@@ -2,34 +2,34 @@ {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-}+{-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-}-{-# LANGUAGE PatternSynonyms #-}-{-# LANGUAGE RankNTypes #-}  module Main where -import Data.Foldable-import Control.Lens import Control.Applicative+import Control.Exception+import Control.Lens import Control.Monad import Control.Monad.Fix-import Control.Exception-import System.Timeout-import Data.Maybe (isJust)+import Data.Align+import Data.Foldable import Data.Functor.Misc-import qualified Data.Map as Map-import Data.Map (Map)-import qualified Data.IntMap as IntMap import Data.IntMap (IntMap)+import qualified Data.IntMap as IntMap+import Data.Map (Map)+import qualified Data.Map as Map+import Data.Maybe (isJust) import Data.These-import Data.Align+import System.Timeout+import Test.Hspec+import Witherable (Filterable)+ import Reflex import Reflex.EventWriter.Base-import Test.Run-import Test.Hspec import Reflex.Spider.Internal (EventLoopException)-import Witherable (Filterable)+import Test.Run  #if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0)) import Data.These.Lens@@ -45,9 +45,8 @@ dynLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) dynLoop (e1, e2) = do   -- "heightBagRemove: Height 2 not present in bag HeightBag {_heightBag_size = 2, _heightBag_contents = fromList [(0,1)]}"-  rec-    d <- count e1-    d' <- connectDyn e2 (d, liftA2 (+) d d')+  rec d <- count e1+      d' <- connectDyn e2 (d, liftA2 (+) d d')   return $ updated d'  connectOnCoincidence :: Widget t m => Event t () -> Event t a -> m (Event t a)@@ -57,24 +56,25 @@  coincidenceLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) coincidenceLoop (e1, e2) = do--- "heightBagRemove: Height 1 not present in bag HeightBag {_heightBag_size = 1, _heightBag_contents = fromList [(0,0)]}"--- (simpler version of dynLoop)-  rec-    e' <- connectOnCoincidence e2 (updated d)-    d <- count (align e' e1)+  -- "heightBagRemove: Height 1 not present in bag HeightBag {_heightBag_size = 1, _heightBag_contents = fromList [(0,0)]}"+  -- (simpler version of dynLoop)+  rec e' <- connectOnCoincidence e2 (updated d)+      d <- count (align e' e1)   return $ updated d -addHeight :: Reflex t =>  Event t a -> Event t a-addHeight e = leftmost [e4, e4] where-  e1 = leftmost [e, e]-  e2 = leftmost [e1, e1]-  e3 = leftmost [e2, e2]-  e4 = leftmost [e3, e3]+addHeight :: Reflex t => Event t a -> Event t a+addHeight e = leftmost [e4, e4]+  where+    e1 = leftmost [e, e]+    e2 = leftmost [e1, e1]+    e3 = leftmost [e2, e2]+    e4 = leftmost [e3, e3]  -- Take an existing test and build it inside a buildLoop :: Widget t m => (forall t m. Widget t m => (Event t Int, Event t ()) -> m (Event t Int)) -> (Event t Int, Event t ()) -> m (Event t Int) buildLoop test (e1, e2) = switchHold never buildLoop-  where buildLoop = pushAlways (const $ test (e1, e2)) e2+  where+    buildLoop = pushAlways (const $ test (e1, e2)) e2  connectButtonPromptly :: Widget t m => Event t () -> Event t a -> m (Event t a) connectButtonPromptly click e = do@@ -88,16 +88,15 @@  switchLoop01 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) switchLoop01 (e1, e2) = do-  rec-    e' <- connectButton e2 (updated d)-    d <- count (align e' e1)+  rec e' <- connectButton e2 (updated d)+      d <- count (align e' e1)   return $ updated d  mergeLoop :: forall t m. (Adjustable t m, Widget t m) => (Event t Int, Event t ()) -> m (Event t Int) mergeLoop (e1, e2) = do-  rec-    (_, e) <- runEventWriterT $-      runWithReplace w (leftmost [w <$ e1])+  rec (_, e) <-+        runEventWriterT $+          runWithReplace w (leftmost [w <$ e1])   return (sum <$> e)   where     w = do@@ -106,36 +105,33 @@  switchLoop02 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) switchLoop02 (e1, e2) = do-  rec-    e' <- connectButton e2 (updated d)-    d <- count (leftmost [e', e1])+  rec e' <- connectButton e2 (updated d)+      d <- count (leftmost [e', e1])   return $ updated d  switchLoop03 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) switchLoop03 (e1, e2) = do-  rec-    e' <- connectButton e2 (addHeight $ updated d)-    d <- count (align e' e1)+  rec e' <- connectButton e2 (addHeight $ updated d)+      d <- count (align e' e1)   return $ updated d  staticLoop01 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) staticLoop01 (e1, e2) = do-  rec-    d <- foldDyn (+) (0 :: Int) (1 <$ align e1 (updated d))+  rec d <- foldDyn (+) (0 :: Int) (1 <$ align e1 (updated d))   return $ updated d  staticLoop02 :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) staticLoop02 (e1, e2) = do-  rec-    d <- foldDyn (+) (0 :: Int) (leftmost [e1, updated d])+  rec d <- foldDyn (+) (0 :: Int) (leftmost [e1, updated d])   return $ updated d  buildStaticLoop :: Widget t m => (Event t Int, Event t ()) -> m (Event t Int) buildStaticLoop (e1, e2) = switchHold never buildLoop-  where buildLoop = pushAlways (const $ staticLoop01 (e1, e2)) e2+  where+    buildLoop = pushAlways (const $ staticLoop01 (e1, e2)) e2  splitThese :: Filterable f => f (These a b) -> (f a, f b)-splitThese f = (mapMaybe (preview here) f,  mapMaybe (preview there) f)+splitThese f = (mapMaybe (preview here) f, mapMaybe (preview there) f)  main :: IO () main = hspec $ do@@ -162,10 +158,10 @@       check dynLoop     xit "throws EventLoopException on buildCoincidenceLoop" $ do       check $ buildLoop coincidenceLoop- where-   milliseconds = (*1000)-   occs = [  This 1, This 2, That (), This 3, That (), This 1 ]-   check test = do-     let action = timeout (milliseconds 50) $ do-                    runApp' (test . splitThese) (Just <$> occs)-     action `shouldThrow` (const True :: Selector EventLoopException)+  where+    milliseconds = (* 1000)+    occs = [This 1, This 2, That (), This 3, That (), This 1]+    check test = do+      let action = timeout (milliseconds 50) $ do+            runApp' (test . splitThese) (Just <$> occs)+      action `shouldThrow` (const True :: Selector EventLoopException)
test/EventWriterT.hs view
@@ -1,9 +1,9 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-}+ module Main where  import Control.Lens@@ -11,7 +11,7 @@ import Control.Monad.Fix import qualified Data.Dependent.Map as DMap import Data.Functor.Misc-import qualified Data.Map as M+import qualified Data.Map as Map import Data.These  #if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0))@@ -24,17 +24,12 @@  main :: IO () main = do-  os1@[[Just [10,9,8,7,6,5,4,3,2,1]]] <- runApp' (unwrapApp testOrdering) $-    [ Just ()-    ]+  os1@[[Just [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]] <-+    runApp' (unwrapApp testOrdering) [Just ()]   print os1-  os2@[[Just [1,3,5,7,9]],[Nothing,Nothing],[Just [2,4,6,8,10]],[Just [2,4,6,8,10],Nothing]]-    <- runApp' (unwrapApp testSimultaneous) $ map Just $-         [ This ()-         , That ()-         , This ()-         , These () ()-         ]+  os2@[[Just [1, 3, 5, 7, 9]], [Nothing, Nothing], [Just [2, 4, 6, 8, 10]], [Just [2, 4, 6, 8, 10], Nothing]] <-+    runApp' (unwrapApp testSimultaneous) $+      map Just [This (), That (), This (), These () ()]   print os2   os3@[[Nothing, Just [2]]] <- runApp' (unwrapApp testMoribundTellEvent) [Just ()]   print os3@@ -44,7 +39,7 @@   print os5   os6 <- runApp' (unwrapApp delayedPulse) [Just ()]   print os6-  let ![[Nothing, Nothing]] = os6+  [[Nothing, Nothing]] <- pure os6   return ()  unwrapApp :: (Reflex t, Monad m) => (a -> EventWriterT t [Int] m ()) -> a -> m (Event t [Int])@@ -53,19 +48,19 @@   return e  testOrdering :: (Reflex t, Monad m) => Event t () -> EventWriterT t [Int] m ()-testOrdering pulse = forM_ [10,9..1] $ \i -> tellEvent ([i] <$ pulse)+testOrdering pulse = forM_ [10, 9 .. 1] $ \i -> tellEvent ([i] <$ pulse)  testSimultaneous :: (Reflex t, Adjustable t m, MonadHold t m) => Event t (These () ()) -> EventWriterT t [Int] m () testSimultaneous pulse = do   let e0 = fmapMaybe (^? here) pulse       e1 = fmapMaybe (^? there) pulse-  forM_ [1,3..9] $ \i -> runWithReplace (tellEvent ([i] <$ e0)) $ ffor e1 $ \_ -> tellEvent ([i+1] <$ e0)+  forM_ [1, 3 .. 9] $ \i -> runWithReplace (tellEvent ([i] <$ e0)) $ ffor e1 $ \_ -> tellEvent ([i + 1] <$ e0)  -- | Test that a widget telling and event which fires at the same time it has been replaced -- doesn't count along with the new widget. testMoribundTellEvent   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -81,7 +76,7 @@ -- | The equivalent of 'testMoribundTellEvent' for 'traverseDMapWithKeyWithAdjust'. testMoribundTellEventDMap   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -94,15 +89,15 @@       (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-         traverseDMapWithKeyWithAdjust           (\(Const2 ()) (Identity v) -> Identity . const v <$> tellIntOnReplace v)-          (mapToDMap $ M.singleton () 1)-          ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)+          (mapToDMap $ Map.singleton () 1)+          (PatchDMap (DMap.map (ComposeMaybe . Just) $ mapToDMap $ Map.singleton () 2) <$ pulse)   return ()  -- | Ensures that elements which are _not_ removed can still fire 'tellEvent's -- during the same frame as other elements are updated. testLiveTellEventDMap   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -115,13 +110,13 @@       (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-         traverseDMapWithKeyWithAdjust           (\(Const2 k) (Identity ()) -> Identity <$> tellIntOnReplace k)-          (mapToDMap $ M.singleton 1 ())-          ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)+          (mapToDMap $ Map.singleton 1 ())+          (PatchDMap (DMap.map (ComposeMaybe . Just) $ mapToDMap $ Map.singleton 2 ()) <$ pulse)   return ()  delayedPulse   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -129,6 +124,6 @@   => Event t ()   -> EventWriterT t [Int] m () delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do-    -- This has the effect of delaying pulse' from pulse-    (_, pulse') <- runWithReplace (pure ()) $ pure [1] <$ pulse-    tellEvent pulse'+  -- This has the effect of delaying pulse' from pulse+  (_, pulse') <- runWithReplace (pure ()) $ pure [1] <$ pulse+  tellEvent pulse'
test/GC.hs view
@@ -1,41 +1,68 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-}+{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-}+ module Main where  import Control.Monad import Control.Monad.IO.Class import Control.Monad.Ref import Data.Align+import Data.Coerce import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap import Data.Dependent.Sum import Data.Functor.Identity+import Data.Functor.Misc import Data.GADT.Compare import Data.IORef+import Data.Maybe (isNothing)+import Data.Patch import Data.Semigroup import Data.These-import Data.Type.Equality ((:~:)(Refl))--import Data.Functor.Misc-import Data.Patch+import Data.Type.Equality ((:~:) (Refl))+import System.Exit+import System.Mem +import qualified Reflex.Class as R import qualified Reflex.Host.Class as Host import qualified Reflex.Spider.Internal as S -import System.Exit-import System.Mem-import Data.Coerce- main :: IO () main = do   ref <- newIORef Nothing   hostPerf ref   readIORef ref >>= maybe exitFailure (putStrLn . ("Result " <>) . show)+  headEAtMostOnce <- checkHeadEAtMostOnce+  if headEAtMostOnce+    then putStrLn "headE at-most-once holds under GC"+    else do+      putStrLn "headE fired for a subscriber that subscribed after its first occurrence"+      exitFailure +{- HLINT ignore checkHeadEAtMostOnce "Functor law" -}+checkHeadEAtMostOnce :: IO Bool+checkHeadEAtMostOnce = S.runSpiderHost $ do+  (inputEvent, inputTriggerRef) <- Host.newEventWithTriggerRef+  -- fmap goes through push/cacheEvent, whose subscribers live in a weak bag;+  -- a plain root event may retain its subscribers strongly and mask the bug.+  headOfInput <- Host.runHostFrame $ R.headE (fmap id (inputEvent :: R.Event S.Spider String))+  liftIO performMajorGC+  Just trigger <- liftIO $ readIORef inputTriggerRef+  Host.fireEvents [trigger :=> Identity "first"]+  liftIO performMajorGC+  lateHandle <- Host.subscribeEvent headOfInput+  lateOccurrence <-+    Host.fireEventsAndRead [trigger :=> Identity "second"] $+      Host.readEvent lateHandle >>= \case+        Nothing -> return Nothing+        Just getValue -> Just <$> getValue+  return $ isNothing lateOccurrence+ hostPerf :: IORef (Maybe Int) -> IO () hostPerf ref = S.runSpiderHost $ do   ---- body@@ -46,26 +73,39 @@       eadd = S.unSpiderEvent eadd'   liftIO $ putStrLn "#creating event graph"   eventToPerform <- Host.runHostFrame $ do-    (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity))-      <- S.SpiderHostFrame-       $ fmap ( S.mergeG coerce-              . S.dynamicHold)-       $ S.hold DMap.empty-       -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained-       $ (\e -> S.Event $ \sub -> do-            (s, o) <- S.subscribeAndRead e $ sub-               { S.subscriberPropagate = S.subscriberPropagate sub-               }-            return (s, o))-       $ runIdentity . runIdentity <$> S.selectG-          (S.fanG $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)-          (WrapArg Request)-    return $ alignWith (mergeThese (<>))-      (flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do-        liftIO $ putStrLn "#eadd fired"-        return $ PatchDMap $ DMap.singleton (Const2 (1 :: Int)) $ ComposeMaybe $ Just-               $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) $ eadd)-      (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)+    (reqMap :: S.Event S.Global (DMap (Const2 Int (DMap Tell (S.SpiderHostFrame S.Global))) Identity)) <-+      S.SpiderHostFrame+        $ fmap+          ( S.mergeG coerce+              . S.dynamicHold+          )+        $ S.hold DMap.empty+        -- Construct a new heap object for the subscriber, invalidating any weak references to the subscriber if they are not retained+        $ ( \e -> S.Event $ \sub -> do+              S.SubscribeResult s o <-+                S.subscribeAndRead e $+                  sub+                    { S.subscriberPropagate = S.subscriberPropagate sub+                    }+              return (S.SubscribeResult s o)+          )+        $ runIdentity . runIdentity+          <$> S.selectG+            (S.fanG $ S.pushCheap (return . Just . mapKeyValuePairsMonotonic (\(t :=> e) -> WrapArg t :=> Identity e)) response)+            (WrapArg Request)+    return $+      alignWith+        (mergeThese (<>))+        ( flip S.pushCheap eadd $ \_ -> return $ Just $ DMap.singleton Request $ do+            liftIO $ putStrLn "#eadd fired"+            return+              $ PatchDMap+              $ DMap.singleton (Const2 (1 :: Int))+              $ ComposeMaybe+              $ Just+              $ S.pushCheap (return . Just . DMap.singleton Action . (\_ -> liftIO (writeIORef ref (Just 1)))) eadd+        )+        (flip S.pushCheap reqMap $ \m -> return $ Just $ mconcat $ (\(Const2 _ :=> Identity reqs) -> reqs) <$> DMap.toList m)   ---- epilogue   eventToPerformHandle <- Host.subscribeEvent (S.SpiderEvent eventToPerform)   liftIO $ putStrLn "#performing GC" >> performMajorGC
test/QueryT.hs view
@@ -11,7 +11,6 @@ import Control.Lens import Control.Monad.Fix import Data.Align-import qualified Data.AppendMap as AMap import Data.Functor.Misc import Data.Map (Map) import qualified Data.Map as Map@@ -20,16 +19,19 @@ import Data.Semigroup.Commutative import Data.These +import qualified Data.AppendMap as AMap+ #if defined(MIN_VERSION_these_lens) || (MIN_VERSION_these(0,8,0) && !MIN_VERSION_these(0,9,0)) import Data.These.Lens #endif -import Reflex import Data.Patch.MapWithMove++import Reflex import Test.Run  newtype MyQuery = MyQuery SelectedCount-  deriving (Show, Read, Eq, Ord, Monoid, Semigroup, Commutative, Group)+  deriving (Commutative, Eq, Group, Monoid, Ord, Read, Semigroup, Show)  instance Query MyQuery where   type QueryResult MyQuery = ()@@ -37,10 +39,10 @@  instance (Ord k, Query a, Eq (QueryResult a), Align (MonoidalMap k)) => Query (Selector k a) where   type QueryResult (Selector k a) = Selector k (QueryResult a)-  crop q r = undefined+  crop (Selector q) (Selector r) = Selector $ AMap.intersectionWith (flip crop) r q -newtype Selector k a = Selector { unSelector :: MonoidalMap k a }-  deriving (Show, Read, Eq, Ord, Functor)+newtype Selector k a = Selector {unSelector :: MonoidalMap k a}+  deriving (Eq, Functor, Ord, Read, Show)  #if !(MIN_VERSION_monoidal_containers(0,4,1)) deriving instance Ord k => Align (MonoidalMap k)@@ -67,39 +69,49 @@  main :: IO () main = do-  [0, 1, 1, 0] <- fmap (map fst . concat) $-    runApp (testQueryT testRunWithReplace) () $ map (Just . That) $-      [ That (), This (), That () ]-  [0, 1, 1, 0] <- fmap (map fst . concat) $-    runApp (testQueryT testSequenceDMapWithAdjust) () $ map (Just . That) $-      [ That (), This (), That () ]-  [0, 1, 1, 0] <- fmap (map fst . concat) $-    runApp (testQueryT testSequenceDMapWithAdjustWithMove) () $ map (Just . That) $-      [ That (), This (), That () ]+  [0, 1, 1, 0] <-+    fmap (map fst . concat)+      $ runApp (testQueryT testRunWithReplace) ()+      $ map (Just . That) [That (), This (), That ()]+  [0, 1, 1, 0] <-+    fmap (map fst . concat)+      $ runApp (testQueryT testSequenceDMapWithAdjust) ()+      $ map (Just . That) [That (), This (), That ()]+  [0, 1, 1, 0] <-+    fmap (map fst . concat)+      $ runApp (testQueryT testSequenceDMapWithAdjustWithMove) ()+      $ map (Just . That) [That (), This (), That ()]   return () -testQueryT :: (Reflex t, MonadFix m)-           => (Event t () -> Event t () -> QueryT t (Selector Int MyQuery) m ())-           -> AppIn t () (These () ())-           -> m (AppOut t Int Int)+testQueryT+  :: (Reflex t, MonadFix m)+  => (Event t () -> Event t () -> QueryT t (Selector Int MyQuery) m ())+  -> AppIn t () (These () ())+  -> m (AppOut t Int Int) testQueryT w (AppIn _ pulse) = do   let replace = fmapMaybe (^? here) pulse       increment = fmapMaybe (^? there) pulse   (_, q) <- runQueryT (w replace increment) $ pure mempty-  let qDyn = head . AMap.keys . unSelector <$> incrementalToDynamic q-  return $ AppOut-    { _appOut_behavior = current qDyn-    , _appOut_event = updated qDyn-    }+  let qDyn =+        ffor (incrementalToDynamic q) $ \(Selector s) -> case AMap.keys s of+          k : _ -> k+          [] -> error "testQueryT"+  return $+    AppOut+      { _appOut_behavior = current qDyn+      , _appOut_event = updated qDyn+      } -testRunWithReplace :: ( Reflex t-                      , Adjustable t m-                      , MonadHold t m-                      , MonadFix m-                      , MonadQuery t (Selector Int MyQuery) m)-                   => Event t ()-                   -> Event t ()-                   -> m ()+testRunWithReplace+  :: ( Reflex t+     , Adjustable t m+     , MonadHold t m+     , MonadFix m+     , MonadQuery t (Selector Int MyQuery) m+     )+  => Event t ()+  -> Event t ()+  -> m () testRunWithReplace replace increment = do   let w = do         n <- count increment@@ -107,28 +119,32 @@   _ <- runWithReplace w $ w <$ replace   return () -testSequenceDMapWithAdjust :: ( Reflex t-                              , Adjustable t m-                              , MonadHold t m-                              , MonadFix m-                              , MonadQuery t (Selector Int MyQuery) m)-                           => Event t ()-                           -> Event t ()-                           -> m ()+testSequenceDMapWithAdjust+  :: ( Reflex t+     , Adjustable t m+     , MonadHold t m+     , MonadFix m+     , MonadQuery t (Selector Int MyQuery) m+     )+  => Event t ()+  -> Event t ()+  -> m () testSequenceDMapWithAdjust replace increment = do   _ <- listHoldWithKey (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do     n <- count increment     queryDyn $ zipDynWith (\x y -> Selector (AMap.singleton (x :: Int) y)) n $ pure $ MyQuery $ SelectedCount 1   return () -testSequenceDMapWithAdjustWithMove :: ( Reflex t-                                      , Adjustable t m-                                      , MonadHold t m-                                      , MonadFix m-                                      , MonadQuery t (Selector Int MyQuery) m)-                                   => Event t ()-                                   -> Event t ()-                                   -> m ()+testSequenceDMapWithAdjustWithMove+  :: ( Reflex t+     , Adjustable t m+     , MonadHold t m+     , MonadFix m+     , MonadQuery t (Selector Int MyQuery) m+     )+  => Event t ()+  -> Event t ()+  -> m () testSequenceDMapWithAdjustWithMove replace increment = do   _ <- listHoldWithKeyWithMove (Map.singleton () ()) (Map.singleton () (Just ()) <$ replace) $ \_ _ -> do     n <- count increment@@ -140,4 +156,5 @@ listHoldWithKeyWithMove m0 m' f = do   (n0, n') <- mapMapWithAdjustWithMove f m0 $ ffor m' $ PatchMapWithMove . Map.map (\v -> NodeInfo (maybe From_Delete From_Insert v) Nothing)   incrementalToDynamic <$> holdIncremental n0 n'+ -- -}
test/Reflex/Bench/Focused.hs view
@@ -7,112 +7,110 @@ {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-}-{-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE TypeApplications #-}  module Reflex.Bench.Focused where -import Reflex-import Reflex.TestPlan- import Control.Applicative+import Control.DeepSeq import Control.Monad import Control.Monad.Fix import Control.Monad.Identity-import Data.Traversable (for, traverse)-+import Control.Monad.Trans.Class (lift) import qualified Data.Dependent.Map as DMap-import Data.Map (Map)-import qualified Data.Map as Map-import Data.Maybe- import Data.Functor.Misc-+import qualified Data.IntMap as IntMap import Data.List import Data.List.Split-import Data.Tuple-+import Data.Map (Map)+import qualified Data.Map as Map+import Data.Maybe import Data.Monoid+import Data.Traversable (for, traverse)+import Data.Tuple import Data.Word--import Control.DeepSeq- import Prelude hiding (concat, sum) +import Reflex+import Reflex.TestPlan  mergeTree :: Num a => (Monoid (f [a]), Functor f) => Int -> [f a] -> f a-mergeTree n es | length es <= n =  sum' es-               | otherwise = mergeTree n subTrees+mergeTree n es+  | length es <= n = sum' es+  | otherwise = mergeTree n subTrees   where-    merges   = chunksOf n es+    merges = chunksOf n es     subTrees = map sum' merges-    sum'     = fmap sum . mconcat . fmap (fmap (:[]) )+    sum' = fmap sum . mconcat . fmap (fmap (: []))  mergeListDyn :: Reflex t => [Dynamic t a] -> Dynamic t [a] mergeListDyn = mconcat . fmap (fmap pure)  mergeTreeDyn :: (Num a, Reflex t) => Int -> [Dynamic t a] -> Dynamic t a-mergeTreeDyn n dyns | length dyns <= n = sumDyns dyns-                    | otherwise = mergeTreeDyn n $ fmap sumDyns merges+mergeTreeDyn n dyns+  | length dyns <= n = sumDyns dyns+  | otherwise = mergeTreeDyn n $ fmap sumDyns merges   where     merges = chunksOf n dyns     sumDyns = fmap sum . mergeListDyn -- -- N events all firing for N frames continuous :: TestPlan t m => Word -> Word -> m [Event t Word]-continuous n frames = for [1..n] $ \i -> plan $ (, i) <$> [1..frames]+continuous n frames = for [1 .. n] $ \i -> plan $ (,i) <$> [1 .. frames]  -- Fire N events once every P frames for total N frames (interspersed evenly) occasional :: TestPlan t m => Word -> Word -> Word -> m [Event t Word]-occasional n period frames = traverse plan $ zipWith occs [1..] phases+occasional n period frames = traverse plan $ zipWith occs [1 ..] phases   where-    phases       = take (fromIntegral n) $ concat (repeat [1..period])-    occs i phase = (, i) <$> [1, phase+1..frames]--+    phases = take (fromIntegral n) $ cycle [1 .. period]+    occs i phase = (,i) <$> [1, phase + 1 .. frames]  -- Event which never fires (but isn't 'never') never' :: TestPlan t m => m (Event t Word) never' = plan [] - -- Event which fires once on first frame event :: TestPlan t m => m (Event t Word) event = plan [(1, 0)]  -- Event which fires constantly over N frames events :: TestPlan t m => Word -> m (Event t Word)-events n  = plan $ (\i -> (i, i)) <$> [1..n]-+events n = plan $ (\i -> (i, i)) <$> [1 .. n]  -- N events all originating from one event fmapFan :: Reflex t => Word -> Event t Word -> [Event t Word]-fmapFan n e = (\i -> (+i) <$> e) <$> [1..n]-+fmapFan n e = (\i -> (+ i) <$> e) <$> [1 .. n]  -- Make a fan using the value in the event converting it to a singleton Map -- use a fan of size n (key is the value mod n) fanMerge :: Reflex t => Word -> Event t Word -> Event t Word-fanMerge n e =  leftmost $ s <$> [0..n - 1] where-  s k = select f (Const2 k)-  f = fan (toMap <$> e)-  toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k)+fanMerge n e = leftmost $ s <$> [0 .. n - 1]+  where+    s k = select f (Const2 k)+    f = fan (toMap <$> e)+    toMap k = DMap.singleton (Const2 $ k `mod` n) (Identity k) +fanIntMerge :: Reflex t => Word -> Event t Word -> Event t Word+fanIntMerge n e = leftmost $ s <$> [0 .. n - 1]+  where+    s k = selectInt f (fromIntegral k)+    f = fanInt (toIntMap <$> e)+    toIntMap k = IntMap.singleton (fromIntegral $ k `mod` n) k+ -- Dumb version of the above using simple fmapMaybe to filter fmapFanMerge :: Reflex t => Word -> Event t Word -> Event t Word-fmapFanMerge n e =  leftmost $ s <$> [0..n - 1] where-  s k = flip fmapMaybe e $ \j -> if k == j `mod` n-    then Just k-    else Nothing--+fmapFanMerge n e = leftmost $ s <$> [0 .. n - 1]+  where+    s k = flip fmapMaybe e $ \j ->+      if k == j `mod` n+        then Just k+        else Nothing  -- Create an Event with a Map which is dense to size N denseMap :: TestPlan t m => Word -> m (Event t (Map Word Word))-denseMap n = plan [(1, m)] where-  m = Map.fromList $ zip [1..n] [1..n]+denseMap n = plan [(1, m)]+  where+    m = Map.fromList $ zip [1 .. n] [1 .. n]  iter :: (a -> a) -> Word -> a -> a iter _ 0 a = a@@ -122,12 +120,13 @@ iterM _ 0 a = return a iterM f n a = iterM f (n - 1) =<< f a -fmapChain :: (Functor f) => Word -> f Word -> f Word-fmapChain = iter (fmap (+1))+fmapChain :: Functor f => Word -> f Word -> f Word+fmapChain = iter (fmap (+ 1))  mapDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)-mapDynChain = iterM (return . fmap (+1))+mapDynChain = iterM (return . fmap (+ 1)) +{- HLINT ignore joinDynChain "Use =<<" -} joinDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word) joinDynChain = iterM (\d -> return $ join $ fmap (const d) d) @@ -135,47 +134,67 @@ holdDynChain = iterM (\d -> sample (current d) >>= flip holdDyn (updated d))  buildDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word)-buildDynChain = iterM (\d -> do-    let b = fmap (+1) (current d)-        e = fmap (*2) (updated d)-    buildDynamic (sample b) e)-+buildDynChain =+  iterM+    ( \d -> do+        let b = fmap (+ 1) (current d)+            e = fmap (* 2) (updated d)+        buildDynamic (sample b) e+    )  combineDynChain :: (Reflex t, MonadHold t m) => Word -> Dynamic t Word -> m (Dynamic t Word) combineDynChain = iterM (\d -> return $ zipDynWith (+) d d)  pingPong :: (Reflex t, MonadHold t m, MonadFix m) => Event t a -> Event t a -> m (Event t a) pingPong e1 e2 = do-  rec-    d <- foldDyn (const swap) (e1, e2) e-    let e = switch (fst <$> current d)+  rec d <- foldDyn (const swap) (e1, e2) e+      let e = switch (fst <$> current d)   return e  switchFactors :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word) switchFactors 0 e = return e switchFactors i e = do-    b <- hold ((+1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)-    switchFactors (i - 1) (switch b)-+  b <- hold ((+ 1) <$> e) (e <$ ffilter ((== 0) . (i `mod`)) e)+  switchFactors (i - 1) (switch b)  switchChain :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)-switchChain  = iterM (\e -> pingPong e ((+1) <$> e))-+switchChain = iterM (\e -> pingPong e ((+ 1) <$> e))  switchChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)-switchChain2 = iterM (\e -> pingPong e ((+1) <$> leftmost [e, e]))+switchChain2 = iterM (\e -> pingPong e ((+ 1) <$> leftmost [e, e]))  switchPromptlyChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word) switchPromptlyChain = iterM $ \e ->-    switchPromptlyDyn <$> holdDyn e (e <$ e)+  switchPromptlyDyn <$> holdDyn e (e <$ e) +-- Like switchPromptlyChain, but each level alternates between two distinct+-- events instead of re-assigning the one it already holds: the two chains+-- bracket implementations that reuse the current subscription when the+-- switched-to event is unchanged (switchPromptlyChain rewards such reuse+-- maximally; this chain never allows it).+switchPromptlyChain2 :: (Reflex t, MonadHold t m, MonadFix m) => Word -> Event t Word -> m (Event t Word)+switchPromptlyChain2 = iterM $ \e -> do+  d <- foldDyn (const swap) (e, (+ 1) <$> e) e+  return $ switchPromptlyDyn (fst <$> d)  coinChain :: Reflex t => Word -> Event t Word -> Event t Word coinChain = iter $ \e -> coincidence (e <$ e) +headEChain :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)+headEChain = iterM headE++headEFan :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)+headEFan n e = mergeTree 8 <$> traverse headE (fmapFan n e)++headEShared :: (Reflex t, MonadHold t m) => Word -> Event t Word -> m (Event t Word)+headEShared n e = mergeTree 8 . fmapFan n <$> headE e+ fanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word fanMergeChain width = iter $ fanMerge width +fanIntMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word+fanIntMergeChain width = iter $ fanIntMerge width+ fmapFanMergeChain :: Reflex t => Word -> Word -> Event t Word -> Event t Word fmapFanMergeChain width = iter $ fmapFanMerge width @@ -183,52 +202,49 @@ data UpdatedMap t k a = UpdatedMap (Map k a) (Event t (Map k (Maybe a)))  -- This will hopefully become a primitive (faster!)-switchMergeEvents ::  (MonadFix m, MonadHold t m, Reflex t, Ord k) =>  UpdatedMap t k (Event t a)  -> m (Event t (Map k a))-switchMergeEvents mapChanges = switch . fmap mergeMap  <$> holdMap mapChanges+switchMergeEvents :: (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Event t a) -> m (Event t (Map k a))+switchMergeEvents mapChanges = switch . fmap mergeMap <$> holdMap mapChanges  -- switchMergeMaybe :: (MonadFix m, MonadHold t m, Reflex t, Ord k) =>  UpdatedMap t k (Event t a)  -> m (Event t (Map k a)) -- switchMergeMaybe (UpdatedMap initial changes) = switchMergeMap initial (fmap (fromMaybe never) <$> changes) -switchMergeBehaviors  :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) =>  UpdatedMap t k (Behavior t a)  -> m (Behavior t (Map k a))+switchMergeBehaviors :: forall a t m k. (MonadFix m, MonadHold t m, Reflex t, Ord k) => UpdatedMap t k (Behavior t a) -> m (Behavior t (Map k a)) switchMergeBehaviors mapChanges = pull . joinMap <$> holdMap mapChanges-  where joinMap m = traverse sample =<< sample m+  where+    joinMap m = traverse sample =<< sample m  -- | Turn an UpdatedMap into a Dynamic by applying the differences to the initial value holdMapDyn :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Dynamic t (Map k a)) holdMapDyn (UpdatedMap initial changes) = foldDyn (flip (Map.foldrWithKey modify)) initial changes-   where     modify k Nothing items = Map.delete k items     modify k (Just item) items = Map.insert k item items - -- | Hold an UpdatedMap as a behavior by applying differences to the initial value holdMap :: (Reflex t, MonadHold t m, MonadFix m, Ord k) => UpdatedMap t k a -> m (Behavior t (Map k a)) holdMap = (current <$>) . holdMapDyn - increasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a) increasingMerge xs = do-  e   <- planList (zipWith Map.singleton  [1..] (Just <$> xs) ++ [reset])+  e <- planList (zipWith Map.singleton [1 ..] (Just <$> xs) <> [reset])   return (UpdatedMap Map.empty e)-    where-      reset = Map.fromList $ zip [1..] (const Nothing <$> xs)+  where+    reset = Map.fromList $ zip [1 ..] (Nothing <$ xs) -decreasingMerge ::  (TestPlan t m) => [a] -> m (UpdatedMap t Int a)+decreasingMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a) decreasingMerge xs = do-  e <- planList (zipWith Map.singleton  [1..] (const Nothing <$> xs) ++ [reset])+  e <- planList (zipWith Map.singleton [1 ..] (Nothing <$ xs) <> [reset])   return (UpdatedMap initial e)-    where-      initial = Map.fromList $ zip [1..] xs-      reset = Just <$> initial+  where+    initial = Map.fromList $ zip [1 ..] xs+    reset = Just <$> initial -modifyMerge :: (TestPlan t m) =>  [a] -> m (UpdatedMap t Int a)+modifyMerge :: TestPlan t m => [a] -> m (UpdatedMap t Int a) modifyMerge xs = do-  e <- planList $ zipWith Map.singleton  [1..] (Just <$> xs)+  e <- planList $ zipWith Map.singleton [1 ..] (Just <$> xs)   return (UpdatedMap initial e)-    where-      initial = Map.fromList $ zip [1..] xs-+  where+    initial = Map.fromList $ zip [1 ..] xs  countMany :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Behavior t Int] countMany = traverse (fmap current . count)@@ -236,33 +252,43 @@ countManyDyn :: (Reflex t, MonadHold t m, MonadFix m) => [Event t a] -> m [Dynamic t Int] countManyDyn = traverse count - -- Given a function which creates a sub-network (from a single event) -- Create a plan which uses a switch to substitute it switches :: TestPlan t m => Word -> (forall n. (MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> m (Event t a) switches numFrames f = do   es <- events numFrames   switch <$> hold never (makeEvents es)--    where-      makeEvents es =  pushAlways (\n -> f (fmap (+n) es)) es--+  where+    makeEvents es = pushAlways (\n -> f (fmap (+ n) es)) es  -- Two sets of benchmarks, one which we're interested in testing subscribe time (as well as time to fire frames) -- the other, which we're only interested in time for running frames subscribing :: Word -> Word -> [(String, TestCase)] subscribing n frames =-  [ testSub "fmapFanMerge"        $ return . mergeList . fmapFan n-  , testSub "fanMerge"            $ return . fanMerge n-  , testSub "fmapFan/mergeTree"   $ return . mergeTree 8 . fmapFan n-  , testSub "fmapChain"           $ return . fmapChain n-  , testSub "switchChain"         $ switchChain n+  [ testSub "fmapFanMerge" $ return . mergeList . fmapFan n+  , testSub "fanMerge" $ return . fanMerge n+  , testSub "fanIntMerge" $ return . fanIntMerge n+  , testSub "fmapFan/mergeTree" $ return . mergeTree 8 . fmapFan n+  , testSub "fmapChain" $ return . fmapChain n+  , testSub "switchChain" $ switchChain n   , testSub "switchPromptlyChain" $ switchPromptlyChain n-  , testSub "switchFactors"       $ switchFactors n-  , testSub "coincidenceChain"    $ return . coinChain n+  , testSub "switchPromptlyChain2" $ switchPromptlyChain2 n+  , testSub "switchFactors" $ switchFactors n+  , testSub "coincidenceChain" $ return . coinChain n   ]+  where+    testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)+    testSub name test = testE name (switches frames test) +-- Set of benchmarks to compare headE implementations. The networks are+-- rebuilt (and their input fires, spending every headE) on each frame, so+-- creation, frame-end init, subscription and spend/teardown are all measured.+headEs :: Word -> Word -> [(String, TestCase)]+headEs n frames =+  [ testSub "headEChain" $ headEChain n+  , testSub "headEFan" $ headEFan n+  , testSub "headEShared" $ headEShared n+  ]   where     testSub :: (Eq a, Show a, NFData a) => String -> (forall t n. (Reflex t, MonadHold t n, MonadFix n) => Event t Word -> n (Event t a)) -> (String, TestCase)     testSub name test = testE name (switches frames test)@@ -271,111 +297,127 @@ -- a pattern which occurs frequently in reflex-dom collections merging :: Word -> [(String, TestCase)] merging n =-  [ testE "static events"        $ mergeList <$> sparse-  , testE "increasing events"    $ switchMergeEvents =<< increasingMerge =<< sparse-  , testE "decreasing events"    $ switchMergeEvents =<< decreasingMerge =<< sparse-  , testE "modify events"        $ switchMergeEvents =<< modifyMerge =<< sparse--  , testB "static behaviors"     $ pull . traverse sample <$> counters+  [ testE "static events" $ mergeList <$> sparse+  , testE "increasing events" $ switchMergeEvents =<< increasingMerge =<< sparse+  , testE "decreasing events" $ switchMergeEvents =<< decreasingMerge =<< sparse+  , testE "modify events" $ switchMergeEvents =<< modifyMerge =<< sparse+  , testB "static behaviors" $ pull . traverse sample <$> counters   , testB "increasing behaviors" $ switchMergeBehaviors =<< increasingMerge =<< counters   , testB "decreasing behaviors" $ switchMergeBehaviors =<< decreasingMerge =<< counters-  , testB "modify behaviors"     $ switchMergeBehaviors =<< modifyMerge =<< counters--+  , testB "modify behaviors" $ switchMergeBehaviors =<< modifyMerge =<< counters   -- , testE "increasing events/switchMerge"    $ switchMergeMaybe =<< increasingMerge =<< sparse   -- , testE "decreasing events/switchMerge"    $ switchMergeMaybe =<< decreasingMerge =<< sparse   -- , testE "modify events/switchMerge"        $ switchMergeMaybe =<< modifyMerge =<< sparse   ]-   where     sparse :: TestPlan t m => m [Event t Word]-    sparse = fmap (fmap (+1)) <$> occasional n 8 n+    sparse = fmap (fmap (+ 1)) <$> occasional n 8 n      counters :: TestPlan t m => m [Behavior t Int]     counters = countMany =<< sparse +-- | Merges of n events whose parents change in every frame. The patch of+-- frame i removes the parent of each key k with odd (k + i) and adds a parent+-- for each key k with even (k + i), so every frame changes every key.+mergePatches :: Word -> [(String, TestCase)]+mergePatches n =+  [ testE "mergeMapIncremental" $ do+      e <- events 10+      parents <- holdIncremental Map.empty $ mapPatch e <$> e+      return $ fmapCheap sum $ mergeMapIncremental parents+  , testE "mergeIntIncremental" $ do+      e <- events 10+      parents <- holdIncremental IntMap.empty $ intMapPatch e <$> e+      return $ fmapCheap sum $ mergeIntIncremental parents+  ]+  where+    keyParent :: Reflex t => Event t Word -> Word -> Word -> Maybe (Event t Word)+    keyParent e i k = if even (k + i) then Just ((+ k) <$> e) else Nothing+    mapPatch :: Reflex t => Event t Word -> Word -> PatchMap Word (Event t Word)+    mapPatch e i = PatchMap $ Map.fromList [(k, keyParent e i k) | k <- [0 .. n - 1]]+    intMapPatch :: Reflex t => Event t Word -> Word -> PatchIntMap (Event t Word)+    intMapPatch e i = PatchIntMap $ IntMap.fromList [(fromIntegral k, keyParent e i k) | k <- [0 .. n - 1]] +eventWriters :: Word -> [(String, TestCase)]+eventWriters n =+  [ testE "firing" $ fmapCheap sum <$> (tellMany =<< events 10)+  , testE "subscribing" $ switches 10 (fmap (fmapCheap sum) . tellMany)+  ]+  where+    tellMany :: (Reflex t, Monad m) => Event t Word -> m (Event t [Word])+    tellMany e = fmap snd $ runEventWriterT $ forM_ [1 .. n] $ \i -> tellEvent $ fmapCheap ((: []) . (+ i)) e  fans :: Word -> [(String, TestCase)] fans n =-  [  testE "fanMapChain"               $ fanMergeChain n 10 <$> e-  ,  testE "fmapFanMapChain"           $ fmapFanMergeChain n 10 <$> e--  , testE "fanMerge " $ fanMerge n <$> events n--  , testE "fmapFanMerge " $ fmapFanMerge n <$> events n-  , testE "triggerMerge" $ leftmost <$> for [1..n] (\i -> plan [(i, i)])-+  [ testE "fanMapChain" $ fanMergeChain n 10 <$> e+  , testE "fanIntMapChain" $ fanIntMergeChain n 10 <$> e+  , testE "fmapFanMapChain" $ fmapFanMergeChain n 10 <$> e+  , testE "fanMerge" $ fanMerge n <$> events n+  , testE "fanIntMerge" $ fanIntMerge n <$> events n+  , testE "fmapFanMerge" $ fmapFanMerge n <$> events n+  , testE "triggerMerge" $ leftmost <$> for [1 .. n] (\i -> plan [(i, i)])   ]   where-     e :: TestPlan t m => m (Event t Word)     e = events 100 --- dynamics :: Word -> [(String, TestCase)] dynamics n =-  [ testE "mapDynChain"         $ fmap updated $ mapDynChain n =<< d-  , testE "joinDynChain"        $ fmap updated $ joinDynChain n =<< d-  , testE "holdDynChain"        $ fmap updated $ holdDynChain n =<< d-  , testE "buildDynChain"        $ fmap updated $ buildDynChain n =<< d-  , testE "combineDynChain"     $ fmap updated $ combineDynChain n =<< d-  , testE "dense mergeTree"     $ fmap (updated . mergeTreeDyn 8) dense-  , testE "sparse mergeTree"    $ fmap (updated . mergeTreeDyn 8) sparse-  , testE "mergeDyn"            $ fmap (updated . fmap sum . mergeListDyn) sparse-  ] where-+  [ testE "mapDynChain" $ fmap updated $ mapDynChain n =<< d+  , testE "joinDynChain" $ fmap updated $ joinDynChain n =<< d+  , testE "holdDynChain" $ fmap updated $ holdDynChain n =<< d+  , testE "buildDynChain" $ fmap updated $ buildDynChain n =<< d+  , testE "combineDynChain" $ fmap updated $ combineDynChain n =<< d+  , testE "dense mergeTree" $ fmap (updated . mergeTreeDyn 8) dense+  , testE "sparse mergeTree" $ fmap (updated . mergeTreeDyn 8) sparse+  , testE "mergeDyn" $ fmap (updated . fmap sum . mergeListDyn) sparse+  ]+  where     d :: TestPlan t m => m (Dynamic t Word)     d = count =<< events 10      sparse, dense :: TestPlan t m => m [Dynamic t Int]     sparse = countManyDyn =<< occasional n 8 16-    dense  = countManyDyn =<< continuous n 2-+    dense = countManyDyn =<< continuous n 2  firing :: Word -> [(String, TestCase)] firing n =-  [ testE "fmapChain"           $ fmapChain n <$> e-  , testE "switchChain2"        $ switchChain2 n =<< e+  [ testE "fmapChain" $ fmapChain n <$> e+  , testE "switchChain2" $ switchChain2 n =<< e   , testE "switchPromptlyChain" $ switchPromptlyChain n =<< e-  , testE "switchFactors"       $  switchFactors n =<< e-  , testE "coincidenceChain"    $ coinChain n <$> e--  , testE "dense mergeTree"      $ mergeTree 8 <$> dense-  , testE "sparse mergeTree"  $ mergeTree 8 <$> sparse--  -- Triggers test failure in Spider-  --, testE "runFrame"               $ events n+  , testE "switchPromptlyChain2" $ switchPromptlyChain2 n =<< e+  , testE "switchFactors" $ switchFactors n =<< e+  , testE "coincidenceChain" $ coinChain n <$> e+  , testE "dense mergeTree" $ mergeTree 8 <$> dense+  , testE "sparse mergeTree" $ mergeTree 8 <$> sparse+  , -- Triggers test failure in Spider+    -- , testE "runFrame"               $ events n -  , testB "sum counters" $ do+    testB "sum counters" $ do       counts <- counters       return $ pull $ sum <$> traverse sample counts--  , testB "pullChain"                 $ fmapChain n . current <$> (count =<< events 4)-  , testB "pullChain2"                $ do-    es <- events 4-    e' <- plan [(0, ())]+  , testB "pullChain" $ fmapChain n . current <$> (count =<< events 4)+  , testB "pullChain2" $ do+      es <- events 4+      e' <- plan [(0, ())] -    b <- hold (constant 0) $-      pushAlways (const $ fmapChain n <$> hold 0 es) e'+      b <-+        hold (constant 0) $+          pushAlways (const $ fmapChain n <$> hold 0 es) e' -    return (join b)+      return (join b)   , testB "counters/pullTree" $ mergeTree 8 <$> counters-   ]-    where-      e :: TestPlan t m => m (Event t Word)-      e = events 10--      dense, sparse :: TestPlan t m => m [Event t Word]-      dense = continuous n 2-      sparse = occasional n 8 16+  where+    e :: TestPlan t m => m (Event t Word)+    e = events 10 -      counters :: TestPlan t m => m [Behavior t Int]-      counters = countMany =<< sparse+    dense, sparse :: TestPlan t m => m [Event t Word]+    dense = continuous n 2+    sparse = occasional n 8 16 +    counters :: TestPlan t m => m [Behavior t Int]+    counters = countMany =<< sparse  -- Stress-test sampling a single behavior through a large, shared set of pulls, -- exercising the invalidator-list pruning path.@@ -383,6 +425,6 @@ sharedInvalidators width =   [ testB "sumPulls" $ do       b <- current <$> (count @_ @_ @Int =<< events 10)-      let ps = [ (+ fromIntegral i) <$> b | i <- [1 .. width] ]+      let ps = [(+ fromIntegral i) <$> b | i <- [1 .. width]]       return $ pull $ sum <$> traverse sample ps   ]
test/Reflex/Plan/Pure.hs view
@@ -8,35 +8,33 @@  module Reflex.Plan.Pure where -import Reflex-import Reflex.Pure-import Reflex.TestPlan- import Control.Applicative import Control.Monad.Fix import Control.Monad.State+import Data.Bifunctor import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.IntSet (IntSet) import qualified Data.IntSet as IntSet--import Data.Bifunctor import Data.Maybe import Data.Monoid import Prelude +import Reflex+import Reflex.Pure+import Reflex.TestPlan  mapToPureEvent :: IntMap a -> Event (Pure Int) a mapToPureEvent m = Event $ flip IntMap.lookup m  type TimeM = (->) Int-newtype PurePlan a = PurePlan { unPlan :: StateT IntSet TimeM a } deriving (Functor, Applicative, Monad, MonadFix)+newtype PurePlan a = PurePlan {unPlan :: StateT IntSet TimeM a} deriving (Applicative, Functor, Monad, MonadFix)  liftPlan :: TimeM a -> PurePlan a liftPlan = PurePlan . lift  instance MonadHold (Pure Int) PurePlan where-  hold initial  = liftPlan . hold initial+  hold initial = liftPlan . hold initial   holdDyn initial = liftPlan . holdDyn initial   holdIncremental initial = liftPlan . holdIncremental initial   buildDynamic getInitial = liftPlan . buildDynamic getInitial@@ -46,28 +44,23 @@ instance MonadSample (Pure Int) PurePlan where   sample = liftPlan . sample - instance TestPlan (Pure Int) PurePlan where   plan occs = do     PurePlan . modify $ IntSet.union (IntMap.keysSet m)     return $ mapToPureEvent m-      where m = IntMap.fromList (first fromIntegral <$> occs)+    where+      m = IntMap.fromList (first fromIntegral <$> occs)  runPure :: PurePlan a -> (a, IntSet)-runPure (PurePlan p) = runStateT p mempty $ 0+runPure (PurePlan p) = runStateT p mempty 0  relevantTimes :: IntSet -> IntSet-relevantTimes occs = IntSet.fromList [0..l + 1]-  where l = fromMaybe 0 (fst <$> IntSet.maxView occs)+relevantTimes occs = IntSet.fromList [0 .. l + 1]+  where+    l = maybe 0 fst (IntSet.maxView occs)  testBehavior :: (Behavior (Pure Int) a, IntSet) -> IntMap a testBehavior (b, occs) = IntMap.fromSet (sample b) (relevantTimes occs)  testEvent :: (Event (Pure Int) a, IntSet) -> IntMap (Maybe a) testEvent (Event readEvent, occs) = IntMap.fromSet readEvent (relevantTimes occs)------
test/Reflex/Plan/Reflex.hs view
@@ -8,58 +8,51 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE UndecidableInstances #-}+ module Reflex.Plan.Reflex-  ( TestPlan(..)+  ( TestPlan (..)   , runPlan   , Plan (..)   , Schedule   , Firing (..)   , MonadIORef--   , readSchedule   , readSchedule_   , testSchedule   , readEvent'   , makeDense-   , runTestE   , runTestB-   ) where -import Reflex.Class-import Reflex.Host.Class-import Reflex.TestPlan- import Control.Applicative+import Control.DeepSeq+import Control.Exception import Control.Monad import Control.Monad.Fix import Control.Monad.Identity-import Control.Monad.State.Strict- import Control.Monad.Ref+import Control.Monad.State.Strict import Data.Dependent.Sum (DSum (..))+import Data.IORef+import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Maybe import Data.Monoid import Data.Traversable (sequenceA, traverse)--import Control.DeepSeq-import Control.Exception-import Data.IntMap.Strict (IntMap)-import Data.IORef import System.Mem- -- Note: this import must come last to silence warnings from AMP import Prelude +import Reflex.Class+import Reflex.Host.Class+import Reflex.TestPlan+ type MonadIORef m = (MonadIO m, MonadRef m, Ref m ~ Ref IO)  data Firing t where   Firing :: IORef (Maybe (EventTrigger t a)) -> a -> Firing t - type Schedule t = IntMap [Firing t]  -- Implementation of a TestPlan in terms of ReflexHost@@ -73,32 +66,27 @@ deriving instance ReflexHost t => MonadHold t (Plan t) deriving instance ReflexHost t => MonadFix (Plan t) - instance (ReflexHost t, MonadRef (HostFrame t), Ref (HostFrame t) ~ Ref IO) => TestPlan t (Plan t) where   plan occurrences = Plan $ do     (e, ref) <- newEventWithTriggerRef     modify (IntMap.unionWith mappend (firings ref))     return e-     where       firings ref = IntMap.fromList (makeFiring ref <$> occurrences)       makeFiring ref (t, a) = (fromIntegral t, [Firing ref a]) --firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum  (EventTrigger t) Identity))+firingTrigger :: (MonadReflexHost t m, MonadIORef m) => Firing t -> m (Maybe (DSum (EventTrigger t) Identity)) firingTrigger (Firing ref a) = fmap (:=> Identity a) <$> readRef ref -runPlan :: (MonadReflexHost t m) => Plan t a -> m (a, Schedule t)+runPlan :: MonadReflexHost t m => Plan t a -> m (a, Schedule t) runPlan (Plan p) = runHostFrame $ runStateT p mempty - makeDense :: Schedule t -> Schedule t makeDense s = fromMaybe (emptyRange 0) $ do   (end, _) <- fst <$> IntMap.maxViewWithKey s   return $ IntMap.union s (emptyRange end)-    where-      emptyRange end = IntMap.fromList (zip [0..end + 1] (repeat []))-+  where+    emptyRange end = IntMap.fromList [(i, []) | i <- [0 .. end + 1]]  -- For the purposes of testing, we add in a zero frame and extend one frame (to observe changes to behaviors -- after the last event)@@ -113,14 +101,13 @@ readSchedule_ schedule readResult = mapM_ (uncurry $ triggerFrame readResult) $ IntMap.toList schedule  triggerFrame :: (MonadReflexHost t m, MonadIORef m, NFData a) => ReadPhase m a -> Int -> [Firing t] -> m a-triggerFrame readResult _ occs =  do-    triggers <- catMaybes <$> traverse firingTrigger occs-    liftIO . evaluate . force =<< fireEventsAndRead triggers readResult+triggerFrame readResult _ occs = do+  triggers <- catMaybes <$> traverse firingTrigger occs+  liftIO . evaluate . force =<< fireEventsAndRead triggers readResult  readEvent' :: MonadReadEvent t m => EventHandle t a -> m (Maybe a) readEvent' = readEvent >=> sequenceA - -- Convenience functions for running tests producing Events/Behaviors runTestB :: (MonadReflexHost t m, MonadIORef m, NFData a) => Plan t (Behavior t a) -> m (IntMap a) runTestB p = do@@ -132,5 +119,3 @@   (e, s) <- runPlan p   h <- subscribeEvent e   testSchedule s (readEvent' h)--
test/Reflex/Test.hs view
@@ -1,66 +1,94 @@-{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-}-{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE RankNTypes #-}  module Reflex.Test-  ( testAgreement-  , compareResult+  ( toTestTree+  , dumpExpected+  , warnMissingExpected   , runTests-   , module Reflex.TestPlan-   ) where -import Reflex.Spider--import Reflex.TestPlan+import qualified Data.IntMap as IntMap+import Data.Maybe+import System.IO (hPutStr, stderr)+import Test.Tasty+import Test.Tasty.ExpectedFailure (expectFailBecause)+import Test.Tasty.HUnit+import Prelude  import Reflex.Plan.Pure import Reflex.Plan.Reflex--import Control.Monad-import Data.Monoid--import Data.IntMap (IntMap)----import Data.Foldable-import System.Exit--import Prelude---testAgreement :: TestCase -> IO Bool-testAgreement (TestE p) = do-  spider <- runSpiderHost $ runTestE p-  let results = [("spider", spider)]--  compareResult results (testEvent $ runPure p)--testAgreement (TestB p) = do-  spider <- runSpiderHost $ runTestB p-  let results = [("spider", spider)]+import Reflex.Spider+import Reflex.TestPlan -  compareResult results (testBehavior $ runPure p)+toTestTree :: (String, TestCase) -> TestTree+toTestTree (name, tc) = testGroup name (implementationLeaves tc) +implementationLeaves :: TestCase -> [TestTree]+implementationLeaves (TestE meta p) =+  [ leaf reference "pure" (return (firings pure'))+  , leaf reference "spider" (firings <$> runSpiderHost (runTestE p))+  ]+  where+    firings = IntMap.mapMaybe id+    pure' = testEvent (runPure p)+    reference = firings (fromMaybe pure' (expectedOutput meta))+    leaf = implementationLeaf (expectedFailures meta)+implementationLeaves (TestB meta p) =+  [ leaf reference "pure" (return pure')+  , leaf reference "spider" (runSpiderHost (runTestB p))+  ]+  where+    pure' = testBehavior (runPure p)+    reference = fromMaybe pure' (expectedOutput meta)+    leaf = implementationLeaf (expectedFailures meta) -compareResult :: (Show a, Eq a) => [(String, IntMap a)] -> IntMap a -> IO Bool-compareResult results expected = fmap and $ forM results $ \(name, r) -> do+implementationLeaf :: (Eq a, Show a) => [String] -> a -> String -> IO a -> TestTree+implementationLeaf failures reference name getResult =+  markExpectedFailure $ testCase name $ do+    result <- getResult+    result @?= reference+  where+    markExpectedFailure+      | name `elem` failures =+          expectFailBecause (name <> " is expected to diverge from the reference")+      | otherwise = id -  when (r /= expected) $ do-    putStrLn ("Got: " ++ show (name, r))-    putStrLn ("Expected: " ++ show expected)-  return (r == expected)+-- | Print a paste-ready 'testE''/'testB'' declaration using Pure as a reference.+dumpExpected :: (String, TestCase) -> IO ()+dumpExpected (name, TestE _ p) =+  putStrLn $+    "  , testE' "+      <> show name+      <> " "+      <> show (IntMap.toList (IntMap.mapMaybe id (testEvent (runPure p))))+dumpExpected (name, TestB _ p) =+  putStrLn $+    "  , testB' "+      <> show name+      <> " "+      <> show (IntMap.toList (testBehavior (runPure p))) +warnMissingExpected :: [(String, TestCase)] -> IO ()+warnMissingExpected tests = case length (filter (missingExpected . snd) tests) of+  0 -> return ()+  n ->+    hPutStr stderr $+      unlines+        [ ""+        , "WARNING: " <> show n <> " test case(s) pin no expected output and are only"+        , "checked for agreement against the Pure implementation. To pin a fixed"+        , "expected output, generate the testE'/testB' declarations with"+        , ""+        , "    cabal run semantics -- --dump-expected [name-prefix]"+        , ""+        , "and paste the relevant lines into the test list."+        , ""+        ]+  where+    missingExpected (TestE meta _) = isNothing (expectedOutput meta)+    missingExpected (TestB meta _) = isNothing (expectedOutput meta)  runTests :: [(String, TestCase)] -> IO ()-runTests testCases = do-   results <- forM testCases $ \(name, test) -> do-     putStrLn $ "Test: " <> name-     testAgreement test-   exitWith $ if and results-              then ExitSuccess-              else ExitFailure 1-+runTests = defaultMain . testGroup "semantics" . map toTestTree
test/Reflex/Test/CrossImpl.hs view
@@ -4,40 +4,38 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-}-{-# LANGUAGE MultiParamTypeClasses #-}-{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-}--import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_)--import Control.Monad.Ref-import Reflex.Class-import Reflex.Dynamic-import Reflex.Host.Class-import qualified Reflex.Pure as P-import qualified Reflex.Spider.Internal as S-import qualified Reflex.Profiled as Prof+{-# LANGUAGE NoMonomorphismRestriction #-}  import Control.Arrow (second, (&&&)) import Control.Monad import Control.Monad.Fix import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence, sequence_)+import Control.Monad.Ref import Control.Monad.State.Strict hiding (forM, forM_, mapM, mapM_, sequence, sequence_) import Data.Dependent.Sum (DSum (..)) import Data.Foldable import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map-import qualified Data.Set as Set import Data.Monoid+import qualified Data.Set as Set import Data.Traversable import System.Exit import System.Mem+import Prelude hiding (and, foldl, mapM, mapM_, sequence, sequence_) +import Reflex.Class+import Reflex.Dynamic+import Reflex.Host.Class+import qualified Reflex.Profiled as Prof+import qualified Reflex.Pure as P+import qualified Reflex.Spider.Internal as S+ mapToPureBehavior :: Map Int a -> Behavior PureReflexDomain a mapToPureBehavior m = P.Behavior $ \t -> case Map.lookupLE t m of   Nothing -> error $ "mapToPureBehavior: no value for time " <> show t@@ -48,7 +46,7 @@  relevantTestingTimes :: (Map Int a, Map Int b) -> [Int] relevantTestingTimes (b, e) = case Set.minView &&& Set.maxView $ Map.keysSet b `Set.union` Map.keysSet e of-  (Just (t0, _), Just (t1, _)) -> [t0..t1+1] -- We need to go to b+1 to see the result of the final event+  (Just (t0, _), Just (t1, _)) -> [t0 .. t1 + 1] -- We need to go to b+1 to see the result of the final event   _ -> [] -- Doesn't actually make much sense  type PureReflexDomain = P.Pure Int@@ -83,11 +81,11 @@   (rb, rbTrigger) <- newEventWithTriggerRef   b <- runHostFrame $ hold (error "testTimeline: No value for input behavior yet") rb   (b', e') <- runHostFrame $ builder (b, re)-  e'Handle <- subscribeEvent e' --TODO: This should be unnecessary+  e'Handle <- subscribeEvent e' -- TODO: This should be unnecessary   let times = relevantTestingTimes (bMap, eMap)   liftIO performGC   outputs <- forM times $ \t -> do-    forM_ (Map.lookup t bMap) $ \val -> mapM_ (\ rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger+    forM_ (Map.lookup t bMap) $ \val -> mapM_ (\rbt -> fireEvents [rbt :=> Identity val]) =<< readRef rbTrigger     bOutput <- sample b'     eOutput <- fmap join $ forM (Map.lookup t eMap) $ \val -> do       mret <- readRef reTrigger@@ -100,7 +98,7 @@   return (Map.fromList $ map (second fst) outputs, Map.mapMaybe id $ Map.fromList $ map (second snd) outputs)  tracePerf :: Show a => a -> b -> b-tracePerf = flip const+tracePerf _ x = x  testAgreement :: (Eq c, Eq d, Show c, Show d) => (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) -> (Map Int a, Map Int b) -> IO Bool testAgreement builder inputs = do@@ -112,144 +110,146 @@   tracePerf "---------" $ return ()   let resultsAgree = identityResult == spiderResult && identityResult == profiledResult   if resultsAgree-    then do --putStrLn "Success:"-            --print identityResult-            return ()-    else do putStrLn "Failure:"-            putStrLn $ "Pure result: " <> show identityResult-            putStrLn $ "Spider result:   " <> show spiderResult-            putStrLn $ "Profiled result:   " <> show profiledResult+    then do+      -- putStrLn "Success:"+      -- print identityResult+      return ()+    else do+      putStrLn "Failure:"+      putStrLn $ "Pure result: " <> show identityResult+      putStrLn $ "Spider result:   " <> show spiderResult+      putStrLn $ "Profiled result:   " <> show profiledResult   return resultsAgree  type TestCaseConstraint t m = (Reflex t, MonadSample t m, MonadHold t m, MonadFix m, MonadFix (PushM t))  data TestCase = forall a b c d. (Eq c, Eq d, Show c, Show d) => TestCase (Map Int a, Map Int b) (forall m t. TestCaseConstraint t m => (Behavior t a, Event t b) -> m (Behavior t c, Event t d)) +{- HLINT ignore testCases "Use =<<" -} testCases :: [(String, TestCase)] testCases =   [ (,) "hold" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do-       b' <- hold "123" e-       return (b', e)+      b' <- hold "123" e+      return (b', e)   , (,) "count" $ TestCase (Map.singleton 0 (), Map.fromList [(1, ()), (2, ()), (3, ())]) $ \(_, e) -> do-       e' <- updated <$> count e-       b' <- hold (0 :: Int) e'-       return (b', e')+      e' <- updated <$> count e+      b' <- hold (0 :: Int) e'+      return (b', e')   , (,) "headE-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       e' <- headE $ leftmost [e, e]-       return (b, e')+      e' <- headE $ leftmost [e, e]+      return (b, e')   , (,) "switch-1" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = fmap (const e) e-       b' <- hold never e'-       let e'' = switch b'-       return (b, e'')+      let e' = fmap (const e) e+      b' <- hold never e'+      let e'' = switch b'+      return (b, e'')   , (,) "switch-2" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ const $ do-             let eab = splitRecombineEvent e-             switch <$> hold eab never-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ const $ do+            let eab = splitRecombineEvent e+            switch <$> hold eab never+          e'' = coincidence e'+      return (b, e'')   , (,) "switch-3" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ const $ do-             let eab = splitRecombineEvent e-             switch <$> hold eab (fmap (const e) e)-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ const $ do+            let eab = splitRecombineEvent e+            switch <$> hold eab (fmap (const e) e)+          e'' = coincidence e'+      return (b, e'')   , (,) "switch-4" $ TestCase (Map.singleton 0 "asdf", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = leftmost [e, e]-       e'' <- switch <$> hold e' (fmap (const e) e)-       return (b, e'')+      let e' = leftmost [e, e]+      e'' <- switch <$> hold e' (fmap (const e) e)+      return (b, e'')   , (,) "switchHoldPromptly-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = fmap (const e) e-       e'' <- switchHoldPromptly never e'-       return (b, e'')+      let e' = fmap (const e) e+      e'' <- switchHoldPromptly never e'+      return (b, e'')   , (,) "switchHoldPromptly-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = fmap (const e) e-       e'' <- switchHoldPromptly never $ leftmost [e', e']-       return (b, e'')+      let e' = fmap (const e) e+      e'' <- switchHoldPromptly never $ leftmost [e', e']+      return (b, e'')   , (,) "switchHoldPromptly-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = leftmost [e, e]-       e'' <- switchHoldPromptly never (fmap (const e) e')-       return (b, e'')+      let e' = leftmost [e, e]+      e'' <- switchHoldPromptly never (fmap (const e) e')+      return (b, e'')   , (,) "switchHoldPromptly-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do-       let e' = leftmost [e, e]-       e'' <- switchHoldPromptly never (fmap (const e') e)-       return (b, e'')+      let e' = leftmost [e, e]+      e'' <- switchHoldPromptly never (fmap (const e') e)+      return (b, e'')   , (,) "switch-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = leftmost [e, e]-       e'' <- switch <$> hold never (fmap (const e') e)-       return (b, e'')+      let e' = leftmost [e, e]+      e'' <- switch <$> hold never (fmap (const e') e)+      return (b, e'')   , (,) "switchHoldPromptly-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip push e $ \_ -> do-             Just <$> headE e-       e'' <- switchHoldPromptly never e'-       return (b, e'')+      let e' = flip push e $ \_ -> do+            Just <$> headE e+      e'' <- switchHoldPromptly never e'+      return (b, e'')   , (,) "switchHoldPromptly-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ \_ -> do-             switchHoldPromptly e never-       e'' <- switchHoldPromptly never e'-       return (b, e'')+      let e' = flip pushAlways e $ \_ -> do+            switchHoldPromptly e never+      e'' <- switchHoldPromptly never e'+      return (b, e'')   , (,) "coincidence-1" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ \_ -> return e-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ \_ -> return e+          e'' = coincidence e'+      return (b, e'')   , (,) "coincidence-2" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ \_ -> return $ leftmost [e, e]+          e'' = coincidence e'+      return (b, e'')   , (,) "coincidence-3" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ \_ -> return $ coincidence $ fmap (const e) e+          e'' = coincidence e'+      return (b, e'')   , (,) "coincidence-4" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do-       let e' = flip pushAlways e $ \_ -> headE e-           e'' = coincidence e'-       return (b, e'')+      let e' = flip pushAlways e $ \_ -> headE e+          e'' = coincidence e'+      return (b, e'')   , (,) "coincidence-5" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do-       let eChild = flip pushAlways e $ const $ do-             let eNewValues = leftmost [e, e]-             return $ coincidence $ fmap (const eNewValues) eNewValues-           e' = coincidence eChild-       return (b, e')+      let eChild = flip pushAlways e $ const $ do+            let eNewValues = leftmost [e, e]+            return $ coincidence $ fmap (const eNewValues) eNewValues+          e' = coincidence eChild+      return (b, e')   , (,) "coincidence-6" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer")]) $ \(b, e) -> do-       let eChild = flip pushAlways e $ const $ do-             let e' = coincidence $ fmap (const e) e-             return $ leftmost [e', e']-           e'' = coincidence eChild-       return (b, e'')+      let eChild = flip pushAlways e $ const $ do+            let e' = coincidence $ fmap (const e) e+            return $ leftmost [e', e']+          e'' = coincidence eChild+      return (b, e'')   , (,) "coincidence-7" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj"), (3, "asdf")]) $ \(b, e) -> do-       let e' = leftmost [e, e]-           eCoincidences = coincidence $ fmap (const e') e-       return (b, eCoincidences)+      let e' = leftmost [e, e]+          eCoincidences = coincidence $ fmap (const e') e+      return (b, eCoincidences)   , (,) "holdWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       eo <- headE e-       bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo-       let b' = pull $ sample =<< sample bb-       return (b', e)+      eo <- headE e+      bb <- hold b $ pushAlways (const $ hold "asdf" eo) eo+      let b' = pull $ sample =<< sample bb+      return (b', e)   , (,) "foldDynWhileFiring" $ TestCase (Map.singleton 0 "zxc", Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(_, e) -> do-       d <- foldDyn (:) [] $-         pushAlways (\a -> foldDyn (:) [a] e) e-       let b = current (join (fmap distributeListOverDynPure d))-       return (b, e)+      d <-+        foldDyn (:) [] $+          pushAlways (\a -> foldDyn (:) [a] e) e+      let b = current (join (fmap distributeListOverDynPure d))+      return (b, e)   , (,) "joinDyn" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, "qwer"), (2, "lkj")]) $ \(b, e) -> do-       bb <- hold "b" e-       bd <- hold never . fmap (const e) =<< headE e-       eOuter <- pushAlways sample . fmap (const bb) <$> headE e-       let eInner = switch bd-           e' = leftmost [eOuter, eInner]-       return (b, e')+      bb <- hold "b" e+      bd <- hold never . fmap (const e) =<< headE e+      eOuter <- pushAlways sample . fmap (const bb) <$> headE e+      let eInner = switch bd+          e' = leftmost [eOuter, eInner]+      return (b, e')   , (,) "holdUniqDyn-laziness" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList (zip [1 :: Int ..] [1 :: Int, 2, 2, 3, 3, 3, 4, 4, 4, 4])) $ \(_, e :: Event t Int) -> do       rec result <- holdUniqDyn d           d <- holdDyn (0 :: Int) e       return (current result, updated result) ---  {--  , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do-       x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e-       let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)-       return (b, e')-  -}+      {-+      , (,) "mergeIncrementalWithMove" $ TestCase (Map.singleton 0 (0 :: Int), Map.fromList [(1, PatchDMapWithMove.moveDMapKey LeftTag RightTag), (2, mempty)]) $ \(b, e :: Event t (PatchDMapWithMove (EitherTag () ()) (Const2 () ()))) -> do+           x <- holdIncremental (DMap.singleton LeftTag $ void e) $ PatchDMapWithMove.mapPatchDMapWithMove (\(Const2 _) -> void e) <$> e+           let e' = mergeIncrementalWithMove x :: Event t (DMap (EitherTag () ()) Identity)+           return (b, e')+      -}   ]  splitRecombineEvent :: Reflex t => Event t a -> Event t String@@ -258,12 +258,12 @@       eb = "b" <$ e   in leftmost [ea, eb] - main :: IO () main = do   results <- forM testCases $ \(name, TestCase inputs builder) -> do     putStrLn $ "Test: " <> name     testAgreement builder inputs-  exitWith $ if and results-             then ExitSuccess-             else ExitFailure 1+  exitWith $+    if and results+      then ExitSuccess+      else ExitFailure 1
test/Reflex/Test/Micro.hs view
@@ -3,269 +3,278 @@ {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-}-{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecursiveDo #-}+{-# LANGUAGE ScopedTypeVariables #-}  module Reflex.Test.Micro (testCases) where -import Reflex-import Reflex.TestPlan- import Control.Applicative import Control.Monad import Control.Monad.Fix import Data.Char import Data.Foldable import Data.Functor.Misc-import qualified Data.Map as Map import qualified Data.IntMap as IntMap+import Data.List.NonEmpty (NonEmpty (..))+import qualified Data.Map as Map import Data.Monoid-import Reflex.Patch.MapWithMove (moveMapKey, insertMapKey, deleteMapKey)-+import Reflex.Patch.MapWithMove (deleteMapKey, insertMapKey, moveMapKey) import Prelude +import Reflex+import Reflex.TestPlan+ pushDyn :: (Reflex t, MonadHold t m) => (a -> PushM t b) -> Dynamic t a -> m (Dynamic t b) pushDyn f d = buildDynamic (sample (current d) >>= f) (pushAlways f (updated d))  foldedDyn :: (Reflex t, MonadHold t m) => (a -> a -> a) -> Dynamic t a -> m (Dynamic t a) foldedDyn f d = fmap join $ flip buildDynamic never $ do- a <- sample (current d)- foldDyn f a (updated d)+  a <- sample (current d)+  foldDyn f a (updated d)  scannedDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> m (Dynamic t [a]) scannedDyn = fmap (fmap reverse) . foldedDyn (<>) . fmap pure +{- HLINT ignore scanInnerDyns "Use =<<" -} scanInnerDyns :: (Reflex t, MonadHold t m) => Dynamic t (Dynamic t a) -> m (Dynamic t [a]) scanInnerDyns d = do   scans <- scannedDyn d   return (join (fmap distributeListOverDynPure scans)) ---{-# ANN testCases "HLint: ignore Functor law" #-}+{- HLINT ignore testCases "Functor law" -}+{- HLINT ignore testCases "Use =<<" -} testCases :: [(String, TestCase)] testCases =-  [ testB "hold"  $ hold "0" =<< events1--  , testB "count" $ do+  [ testB' "hold" [(0, "0"), (1, "0"), (2, "a"), (3, "b"), (4, "b"), (5, "b"), (6, "c"), (7, "c"), (8, "d"), (9, "e")] $ hold "0" =<< events1+  , testB' "count" [(0, 0), (1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (6, 3), (7, 4), (8, 5)] $ do       b <- current <$> (count =<< events2)-      return $ (+ (0::Int)) <$> b--  , testB "pull-1"  $ do+      return $ (+ (0 :: Int)) <$> b+  , testB' "pull-1" [(0, "0"), (1, "0"), (2, "a"), (3, "b"), (4, "b"), (5, "b"), (6, "c"), (7, "c"), (8, "d"), (9, "e")] $ do       b <- hold "0" =<< events1       return (pull $ sample $ pull $ sample b)--  , testB "pull-2" $ do+  , testB' "pull-2" [(0, "11"), (1, "11"), (2, "aa"), (3, "bb"), (4, "bb"), (5, "bb"), (6, "cc"), (7, "cc"), (8, "dd"), (9, "ee")] $ do       b1 <- behavior1       return (pull $ liftA2 (<>) (sample b1) (sample b1))--  , testB "pull-3" $ do-      b1 <- behavior1-      b2 <- behavior2-      return (pull $ liftA2 (<>) (sample b1) (sample b2))--  , testB "pull-4" $ do+  , testB' "pull-3" [(0, "12"), (1, "12"), (2, "ae"), (3, "be"), (4, "bd"), (5, "bc"), (6, "cc"), (7, "cb"), (8, "da"), (9, "ea")] $+      liftA2 (\b1 b2 -> pull $ liftA2 (<>) (sample b1) (sample b2)) behavior1 behavior2+  , testB' "pull-4" [(0, ""), (1, "z"), (2, "a"), (3, "b"), (4, "c")] $ do       es <- planList ["a", "b", "c"]       e <- plan [(0, ())]-      b <- hold (constant "") $-        pushAlways (const $ hold "z" es) e+      b <-+        hold (constant "") $+          pushAlways (const $ hold "z" es) e       return (join b)--  , testE "id" $ do+  , testE' "id" [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")] $ do       events2--  , testE "fmap-id" $ do-      e <- events2-      return $ fmap id e--  , testE "tag-1" $ do+  , testE' "fmap-id" [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")] $+      fmap id <$> events2+  , testE' "tag-1" [(1, "1"), (3, "b"), (4, "b"), (6, "c"), (7, "c")] $ do       b1 <- behavior1-      e <- events2-      return (tag b1 e)--  , testE "tag-2" $ do+      tag b1 <$> events2+  , testE' "tag-2" [(1, "1"), (3, "B"), (4, "B"), (6, "C"), (7, "C")] $ do       b1 <- behavior1-      e <- events2-      return (tag (map toUpper <$>  b1) e)--  , testE "attach-1" $ do+      tag (map toUpper <$> b1) <$> events2+  , testE' "attach-1" [(1, "1e"), (3, "Bd"), (4, "Bc"), (6, "Cb"), (7, "Ca")] $ do       b1 <- behavior1-      e <- events2-      return (attachWith (++) (map toUpper <$> b1) e)--  , testE "leftmost" $ liftA2 leftmost2 events1 events2--  , testE "appendEvents-1" $ liftA2 mappend events1 events2--  , testE "appendEvents-2" $ liftA2 mappend events3 events2--  , testE "merge-1" $ do+      attachWith (++) (map toUpper <$> b1) <$> events2+  , testE' "leftmost" [(1, "a"), (2, "b"), (3, "d"), (4, "c"), (5, "c"), (6, "b"), (7, "d"), (8, "e")] $ liftA2 leftmost2 events1 events2+  , testE' "appendEvents-1" [(1, "ae"), (2, "b"), (3, "d"), (4, "c"), (5, "c"), (6, "b"), (7, "da"), (8, "e")] $ liftA2 mappend events1 events2+  , testE' "appendEvents-2" [(1, "aee"), (2, "b"), (3, "dd"), (4, "cc"), (5, "c"), (6, "bb"), (7, "daa"), (8, "e")] $ liftA2 mappend events3 events2+  , testE' "merge-1" [(1, "x"), (2, "x"), (5, "x"), (7, "x"), (8, "x")] $ do       e <- events1       return $ leftmost ["x" <$ e, "y" <$ e]--  , testE "merge-2" $ do+  , testE' "merge-2" [(1, Map.fromList [(1, "y"), (2, "z")]), (2, Map.fromList [(1, "y"), (2, "z")]), (5, Map.fromList [(1, "y"), (2, "z")]), (7, Map.fromList [(1, "y"), (2, "z")]), (8, Map.fromList [(1, "y"), (2, "z")])] $ do       e <- events1-      let m = mergeMap $ Map.fromList [(1::Int, "y" <$ e), (2, "z" <$ e)]+      let m = mergeMap $ Map.fromList [(1 :: Int, "y" <$ e), (2, "z" <$ e)]       let ee = flip pushAlways e $ const $ return m       return $ coincidence ee--  , testE "headE-1" $ do+  , testE' "headE-1" [(1, "a")] $ do       e <- events1       headE $ leftmost [e, e]--  , testE "headE-2" $ do+  , testE' "headE-2" [(2, "b")] $ do       e <- events1       b <- hold never (e <$ e)       headE $ switch b--  , testE "switch-1" $ do+  , testE' "headE-rec" [(1, "a")] $ do       e <- events1+      rec !eHeadOfLater <- headE eLater+          eLater <- headE e+      return eHeadOfLater+  , -- Tests for a bug caught during headE development where the argument event's+    -- heightRef was incorrectly reused as headE's heightRef.+    testE' "headE-height-after-head" [(1, ())] $ do+      unsubscribeHead <- plan [(1, ())]+      dropFromMerge <- plan [(2, ())]+      let taller = void (mergeList [unsubscribeHead, unsubscribeHead])+      parent <- hold unsubscribeHead (taller <$ unsubscribeHead)+      let switched = switch parent+      headOfSwitched <- headE switched+      mergeParents <-+        holdIncremental+          (IntMap.singleton (0 :: Int) headOfSwitched)+          (PatchIntMap (IntMap.singleton 0 Nothing) <$ dropFromMerge)+      -- 'switched' stays subscribed here, so it goes on subscribing (and so+      -- changing its height) after the headE has stopped listening to it:+      pure $ leftmost [void (mergeIntIncremental mergeParents), switched]+  , testE' "nested-incremental-merge-added-by-patch" [(3, IntMap.singleton 0 7)] $ do+      addInner <- plan [(1, ())]+      addLeaf <- plan [(2, ())]+      leaf <- plan [(3, 7 :: Int)]+      inner <- holdIncremental IntMap.empty (PatchIntMap (IntMap.singleton 0 (Just leaf)) <$ addLeaf)+      let innerSummed = sum <$> mergeIntIncremental inner+      outer <- holdIncremental IntMap.empty (PatchIntMap (IntMap.singleton 0 (Just innerSummed)) <$ addInner)+      pure $ mergeIntIncremental outer+  , testE' "switch-1" [(2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do+      e <- events1       b <- hold never (e <$ e)       return $ switch b--  , testE "switch-2" $ do+  , testE' "switch-2" [(1, "x"), (2, "x"), (5, "x"), (7, "x"), (8, "x")] $ do       e <- events1       return $ coincidence $ flip pushAlways e $ const $ do-            switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)--  , testE "switch-3" $ do+        switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) (e <$ e)+  , testE' "switch-3" [(1, "x"), (2, "x"), (5, "x"), (7, "x"), (8, "x")] $ do       e <- events1       return $ coincidence $ flip pushAlways e $ const $ do-          switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never--  , testE "switch-4" $ do+        switch <$> hold (leftmost ["x" <$ e, "y" <$ e, "z" <$ e]) never+  , testE' "switch-4" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       switch <$> hold (deep e) (e <$ e)--  , testE "switch-5" $ do+  , testE' "switch-5" [(1, "x"), (2, "x"), (5, "x"), (7, "x"), (8, "x")] $ do       e <- events1-      return $ coincidence $ flip pushAlways e $ const $-        return $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]--  , testE "switch-6" $ do+      return+        $ coincidence+        $ flip pushAlways e+        $ const+        $ return+        $ leftmost ["x" <$ e, "y" <$ e, "z" <$ e]+  , testE' "switch-6" [(1, "x"), (2, "x"), (5, "x"), (7, "x"), (8, "x")] $ do       e <- events1       return $ coincidence $ flip pushAlways e $ const $ do-            switch <$> hold ("x" <$ e) (e <$ e)--  , testE "switchHoldPromptly-1" $ do+        switch <$> hold ("x" <$ e) (e <$ e)+  , testE' "switchHoldPromptly-1" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       let e' = e <$ e       switchHoldPromptly never $ e <$ e'--  , testE "switchHoldPromptly-2" $ do+  , testE' "switchHoldPromptly-2" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       switchHoldPromptly never $ deep (e <$ e)--  , testE "switchHoldPromptly-3" $ do+  , testE' "switchHoldPromptly-3" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      switchHoldPromptly never $ (e <$ deep e)--  , testE "switchHoldPromptly-4" $ do+      switchHoldPromptly never (e <$ deep e)+  , testE' "switchHoldPromptly-4" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      switchHoldPromptly never $ (deep e <$ e)--  , testE "switch-5" $ do+      switchHoldPromptly never (deep e <$ e)+  , testE' "switch-7" [(2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       switch <$> hold never (deep e <$ e)--  , testE "switchHoldPromptly-5" $ do-    e <- events1-    switchHoldPromptly never $ flip push e $-      const (Just <$> headE e)--  , testE "switchHoldPromptly-6" $ do+  , testE' "switchHoldPromptly-5" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      switchHoldPromptly never $ flip pushAlways e $-        const (switchHoldPromptly e never)--  , testE "coincidence-1" $ do+      switchHoldPromptly never+        $ flip push e+        $ const (Just <$> headE e)+  , testE' "switchHoldPromptly-6" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      return $ coincidence $ flip pushAlways e $-        const $ return e--  , testE "coincidence-2" $ do+      switchHoldPromptly never+        $ flip pushAlways e+        $ const (switchHoldPromptly e never)+  , testE' "coincidence-1" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      return $ coincidence $ flip pushAlways e $-        const $ return (deep e)--  , testE "coincidence-3" $ do+      return+        $ coincidence+        $ flip pushAlways e+        $ const+        $ return e+  , testE' "coincidence-2" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      return $ coincidence $ flip pushAlways e $-        const $ return (coincidence (e <$ e))--  , testE "coincidence-4" $ do+      return+        $ coincidence+        $ flip pushAlways e+        $ const+        $ return (deep e)+  , testE' "coincidence-3" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1-      return $ coincidence $ flip pushAlways e $-        const (headE e)--  , testE "coincidence-5" $ do+      return+        $ coincidence+        $ flip pushAlways e+        $ const+        $ return (coincidence (e <$ e))+  , testE' "coincidence-4" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1+      return+        $ coincidence+        $ flip pushAlways e+        $ const (headE e)+  , testE' "coincidence-5" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do+      e <- events1       return $ coincidence $ flip pushAlways e $ const $ do         let e' = deep e         return (coincidence (e' <$ e'))--  , testE "coincidence-6" $ do+  , testE' "coincidence-6" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       return $ coincidence $ flip pushAlways e $ const $ do         let e' = coincidence (e <$ e)         return $ deep e'--  , testE "coincidence-7" $ do+  , testE' "coincidence-7" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       return $ coincidence (deep e <$ e)--  , testE "coincidence-incremental-height" $ do+  , testE' "coincidence-incremental-height" [(1, ()), (2, ()), (3, ()), (4, ()), (5, ()), (6, ())] $ do       tick <- ticks-      e2 <- mergeMapIncremental-              <$> holdIncremental mempty ((mempty :: PatchMap Int (Event t ())) <$ tick)-      pure (leftmost [ void $ coincidence (e2 <$ leftmost [tick, tick])-                     , tick])--  , testE "coincidence-int-incremental-height" $ do+      e2 <-+        mergeMapIncremental+          <$> holdIncremental mempty ((mempty :: PatchMap Int (Event t ())) <$ tick)+      pure+        ( leftmost+            [ void $ coincidence (e2 <$ leftmost [tick, tick])+            , tick+            ]+        )+  , testE' "coincidence-int-incremental-height" [(1, ()), (2, ()), (3, ()), (4, ()), (5, ()), (6, ())] $ do       tick <- ticks-      h <- mergeIntIncremental-             <$> holdIncremental-                   (IntMap.singleton 1 (void tick))-                   (PatchIntMap (IntMap.singleton 1 (Just (void tick))) <$ tick)-      pure (leftmost [ void $ coincidence (void h <$ leftmost [tick, tick])-                     , tick])--  , testE "coincidence-switch-reconnect-height" $ do+      h <-+        mergeIntIncremental+          <$> holdIncremental+            (IntMap.singleton 1 (void tick))+            (PatchIntMap (IntMap.singleton 1 (Just (void tick))) <$ tick)+      pure+        ( leftmost+            [ void $ coincidence (void h <$ leftmost [tick, tick])+            , tick+            ]+        )+  , testE' "coincidence-switch-reconnect-height" [(1, ()), (2, ()), (3, ()), (4, ()), (5, ()), (6, ())] $ do       tick <- ticks       flag <- foldDyn (\_ b -> not b) False tick       let hi = leftmost [tick, tick]       pure (leftmost [void (coincidence (switch (current $ (\b -> if b then hi else tick) <$> flag) <$ hi)), tick])--  , testE "mergeWithMove-height" $ do+  , testE' "mergeWithMove-height" [(1, Map.fromList [(0, ())]), (2, Map.fromList [(0, ()), (1, ())]), (3, Map.fromList [(1, ())]), (4, Map.fromList [(0, ()), (1, ())]), (5, Map.fromList [(0, ()), (2, ())]), (6, Map.fromList [(0, ())])] $ do       tick <- ticks       let lo = tick           hi = leftmost [tick, tick]-      patches <- plan-        [ (1, insertMapKey 1 hi)-        , (2, deleteMapKey 0)-        , (3, insertMapKey 0 lo)-        , (4, moveMapKey 1 2)-        , (5, deleteMapKey 2) ]+      patches <-+        plan+          [ (1, insertMapKey 1 hi)+          , (2, deleteMapKey 0)+          , (3, insertMapKey 0 lo)+          , (4, moveMapKey 1 2)+          , (5, deleteMapKey 2)+          ]       mergeMapIncrementalWithMove         <$> holdIncremental (Map.singleton (0 :: Int) lo) patches--  , testB "holdWhileFiring" $ do+  , testB' "holdWhileFiring" [(0, "x"), (1, "x"), (2, "a"), (3, "a"), (4, "a"), (5, "a"), (6, "a"), (7, "a"), (8, "a"), (9, "a")] $ do       e <- events1       eo <- headE e       bb <- hold (constant "x") $ pushAlways (const $ hold "a" eo) eo       return $ pull $ sample =<< sample bb---  , testB "foldDynWhileFiring"  $ do-    e <- events1-    d <- foldDyn (:) [] $-      pushAlways (\a -> foldDyn (:) [a] e) e--    return $ current (join (fmap distributeListOverDynPure d))+  , testB' "foldDynWhileFiring" [(0, []), (1, []), (2, [["a", "a"]]), (3, [["b", "b"], ["b", "a", "a"]]), (4, [["b", "b"], ["b", "a", "a"]]), (5, [["b", "b"], ["b", "a", "a"]]), (6, [["c", "c"], ["c", "b", "b"], ["c", "b", "a", "a"]]), (7, [["c", "c"], ["c", "b", "b"], ["c", "b", "a", "a"]]), (8, [["d", "d"], ["d", "c", "c"], ["d", "c", "b", "b"], ["d", "c", "b", "a", "a"]]), (9, [["e", "e"], ["e", "d", "d"], ["e", "d", "c", "c"], ["e", "d", "c", "b", "b"], ["e", "d", "c", "b", "a", "a"]])] $ do+      e <- events1+      d <-+        foldDyn (:) [] $+          pushAlways (\a -> foldDyn (:) [a] e) e -  , testE "joinDyn" $ do+      return $ current (join (fmap distributeListOverDynPure d))+  , testE' "joinDyn" [(1, "b"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e <- events1       bb <- hold "b" e       bd <- hold never . fmap (const e) =<< headE e@@ -273,38 +282,38 @@       eOuter <- pushAlways sample . fmap (const bb) <$> headE e       let eInner = switch bd       return $ leftmost [eOuter, eInner]--  , testB "foldDyn"  $ do+  , testE' "joinDyn-inner-occurrence" [(3, 1)] $ do+      updateOld <- plan [(3, 100 :: Int)]+      swap <- plan [(3, ())]+      innerOld <- holdDyn 0 updateOld+      innerNew <- holdDyn 1 never+      outer <- holdDyn innerOld (innerNew <$ swap)+      pure $ updated (join outer)+  , testB' "foldDyn" [(0, "0"), (1, "0"), (2, "a0"), (3, "ba0"), (4, "ba0"), (5, "ba0"), (6, "cba0"), (7, "cba0"), (8, "dcba0"), (9, "edcba0")] $ do       d <- foldDyn (++) "0" =<< events1       return (current d)--  , testB "mapDyn"  $ do+  , testB' "mapDyn" [(0, "0"), (1, "0"), (2, "A0"), (3, "BA0"), (4, "BA0"), (5, "BA0"), (6, "CBA0"), (7, "CBA0"), (8, "DCBA0"), (9, "EDCBA0")] $ do       d <- foldDyn (++) "0" =<< events1       return $ current $ fmap (map toUpper) d--  , testB "combineDyn"  $ do+  , testB' "combineDyn" [(0, "00"), (1, "00"), (2, "a0E0"), (3, "ba0E0"), (4, "ba0DE0"), (5, "ba0CDE0"), (6, "cba0CDE0"), (7, "cba0BCDE0"), (8, "dcba0ABCDE0"), (9, "edcba0ABCDE0")] $ do       d1 <- foldDyn (++) "0" =<< events1       d2 <- fmap (fmap (map toUpper)) $ foldDyn (++) "0" =<< events2        return $ current $ zipDynWith (<>) d1 d2--  , testB "buildDynamicStrictness"  $ do-      rec-        d'' <- pushDyn return d'-        d' <- pushDyn return d-        d <- holdDyn "0" =<< events1+  , testB' "buildDynamicStrictness" [(0, "0"), (1, "0"), (2, "a"), (3, "b"), (4, "b"), (5, "b"), (6, "c"), (7, "c"), (8, "d"), (9, "e")] $ do+      rec d'' <- pushDyn return d'+          d' <- pushDyn return d+          d <- holdDyn "0" =<< events1        _ <- sample (current d'')       return (current d'')--  , testB "factorDyn"  $ do+  , testB' "factorDyn" [(0, "a"), (1, "a"), (2, "e"), (3, "e"), (4, "d"), (5, "c"), (6, "c"), (7, "b"), (8, "a")] $ do       d <- holdDyn (Left "a") =<< eithers        eithers' <- eitherDyn d       let unFactor = either id id       return $ current (join (fmap unFactor eithers'))--  , testB "pushDynDeep"  $ do+  , testB' "pushDynDeep" [(0, [["d1d2d1"]]), (1, [["d1d2d1"]]), (2, [["d1d2a", "d1ea"], ["ad2a", "aea"]]), (3, [["d1d2b", "d1eb"], ["ad2b", "aeb"], ["beb"]]), (4, [["d1d2b", "d1eb", "d1db"], ["ad2b", "aeb", "adb"], ["beb", "bdb"]]), (5, [["d1d2b", "d1eb", "d1db", "d1cb"], ["ad2b", "aeb", "adb", "acb"], ["beb", "bdb", "bcb"]]), (6, [["d1d2c", "d1ec", "d1dc", "d1cc"], ["ad2c", "aec", "adc", "acc"], ["bec", "bdc", "bcc"], ["ccc"]]), (7, [["d1d2c", "d1ec", "d1dc", "d1cc", "d1bc"], ["ad2c", "aec", "adc", "acc", "abc"], ["bec", "bdc", "bcc", "bbc"], ["ccc", "cbc"]]), (8, [["d1d2d", "d1ed", "d1dd", "d1cd", "d1bd", "d1ad"], ["ad2d", "aed", "add", "acd", "abd", "aad"], ["bed", "bdd", "bcd", "bbd", "bad"], ["ccd", "cbd", "cad"], ["dbd", "dad"]]), (9, [["d1d2e", "d1ee", "d1de", "d1ce", "d1be", "d1ae"], ["ad2e", "aee", "ade", "ace", "abe", "aae"], ["bee", "bde", "bce", "bbe", "bae"], ["cce", "cbe", "cae"], ["dbe", "dae"], ["eae"]])] $ do       _ <- events1       _ <- events2 @@ -318,58 +327,147 @@        d' <- pushDyn scanInnerDyns d >>= scanInnerDyns       return $ current d'--  , testE "fan-1" $ do+  , testE' "fan-1" [(1, 'a' :| ""), (2, 'b' :| ""), (5, 'c' :| ""), (7, 'd' :| ""), (8, 'e' :| "")] $ do       e <- fmap toMap <$> events1       let es = select (fanMap e) . Const2 <$> values        return (mergeList es)--  , testE "fan-2" $ do+  , testE' "fan-2" [(1, 'a' :| "e"), (2, 'b' :| ""), (3, 'd' :| ""), (4, 'c' :| ""), (5, 'c' :| ""), (6, 'b' :| ""), (7, 'a' :| "d"), (8, 'e' :| "")] $ do       e <- fmap toMap <$> events3       let es = select (fanMap e) . Const2 <$> values        return (mergeList es)--  , testE "fan-3" $ do+  , testE' "fan-3" [(4, 'c'), (5, 'c')] $ do       f <- fanMap . fmap toMap <$> events3-      return $  select f (Const2 'c')--  , testE "fan-4" $ do+      return $ select f (Const2 'c')+  , testE' "fan-4" [(1, 'A')] $ do       e <- fmap toMap <$> events1       return $ toUpper <$> select (fanMap e) (Const2 'a')--  , testE "fan-5" $ do+  , testE' "fan-5" [(4, 'C')] $ do       e <- fmap toMap <$> events2       return $ toUpper <$> select (fanMap e) (Const2 'c')--  , testE "fan-6" $ do+  , testE' "fan-6" [(2, "bb"), (8, "ee")] $ do       f <- fanMap . fmap toMap <$> events1-      return $ toList <$> mergeList [ select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e') ]--  , testE "difference" $ do+      return $ toList <$> mergeList [select f (Const2 'b'), select f (Const2 'b'), select f (Const2 'e'), select f (Const2 'e')]+  , testE' "difference" [(2, "b"), (5, "c"), (8, "e")] $ do       e1 <- events1       e2 <- events2-      return $ e1 `difference ` e2--  , testE "lazy-hold" $ do+      return $ e1 `difference` e2+  , testE' "lazy-hold" [] $ do       let lazyHold :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())           lazyHold = do             rec !b <- hold never e                 let e = never <$ switch b             return $ void e       lazyHold-  , testE "now-1" $ do+  , testE' "now-1" [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")] $ do       e1 <- events1       switchHoldPromptly never . pushAlways (\a -> fmap (a <$) now) $ e1-  , testE "now-2" $ do+  , testE' "now-2" [(1, ())] $ do       e1 <- events1       let e = pushAlways (\a -> if a == "a" then now else return never) e1-      x <- accumDyn (<>) never e +      x <- accumDyn (<>) never e       return . coincidence $ updated x-  ] where--    events1, events2, events3 ::  TestPlan t m => m (Event t String)+  , xfail ["spider"] $ testE "now-4" $ do+      now+  , testE "now-5" $+      coincidence . pushAlways (const now) <$> events1+  , testE "now-6" $ do+      e1 <- events1+      n <- now+      pure $ coincidence $ pushAlways (const (pure n)) e1+  , xfail ["spider"] $ testE "now-7" $ do+      e1 <- plan [(0, "a"), (1, "b"), (3, "c")]+      n <- now+      pure $ coincidence $ pushAlways (const (pure n)) e1+  , testE' "dynamic-bind-lazy-function" [(3, "a")] $ do+      e <- plan [(1, "a")]+      eLater <- plan [(3, ())]+      dReady <- holdDyn False (True <$ e)+      dPayload <- holdDyn "payload" e+      let dJoined =+            dReady >>= \ready ->+              if ready then dPayload else error "dynamic-bind: function applied to unobserved value"+      return $ tag (current dJoined) eLater+  , testE' "dynamic-bind-forced-at-build" [(3, "a")] $ do+      e <- plan [(1, "a")]+      eLater <- plan [(3, ())]+      dReady <- holdDyn False (True <$ e)+      dPayload <- holdDyn "payload" e+      let dJoined =+            dReady >>= \ready ->+              if ready then dPayload else error "dynamic-bind: function applied to unobserved value"+      dJoined `seq` return (tag (current dJoined) eLater)+  , -- An fmap'd Dynamic that is forced but never sampled or subscribed must not+    -- sample the Dynamic it maps over.+    testB' "dynamic-fmap-dead" [(0, "ok"), (1, "ok"), (2, "x")] $ do+      e <- plan [(1, "x")]+      let divergingBehavior :: forall t. Reflex t => Event t () -> Behavior t String+          divergingBehavior _timelinePin = fix $ \bLoop -> fmap ('!' :) bLoop+      let dDead = fmap (map toUpper) (unsafeDynamic (divergingBehavior (void e)) never)+      dDead `seq` hold "ok" e+  , -- A joined Dynamic that is forced but never sampled or subscribed must not+    -- sample its outer or inner Dynamics.+    testB' "dynamic-join-dead" [(0, "ok"), (1, "ok"), (2, "x")] $ do+      e <- plan [(1, "x")]+      -- A dynamic that refers to itself through 'join': a bottom placeholder+      -- that must stay inert while unobserved. The event argument only pins the+      -- timeline type.+      let selfReferentialDynamic :: forall t. Reflex t => Event t () -> Dynamic t String+          selfReferentialDynamic _timelinePin = fix $ \dLoop -> join (pure dLoop)+      selfReferentialDynamic (void e) `seq` hold "ok" e+  , -- unsafeBuildDynamic's initial-value computation runs no earlier than the+    -- first observation of the Dynamic.+    testE' "unsafeBuildDynamic-seed-timing" [(3, "b")] $ do+      e <- plan [(1, "a"), (2, "b")]+      eLater <- plan [(3, ())]+      b <- hold "0" e+      let d = unsafeBuildDynamic (sample b) never+      d `seq` return (tag (current d) eLater)+  , -- buildDynamic's initial-value computation runs during the frame that+    -- builds it.+    testE' "buildDynamic-seed-timing" [(3, "0")] $ do+      e <- plan [(1, "a"), (2, "b")]+      eLater <- plan [(3, ())]+      b <- hold "0" e+      d <- buildDynamic (sample b) never+      return (tag (current d) eLater)+  , -- buildDynamic inside a recursive knot, whose initial-value computation+    -- scrutinizes a value sampled from a Dynamic bound later in the same knot.+    testB' "buildDynamic-rec-scrutinize" [(0, 5), (1, 5)] $ do+      rec dScrutinized <-+            buildDynamic+              ( do+                  seed <- sample (current dLater)+                  if seed > (0 :: Int) then return seed else return 0+              )+              never+          dLater <- holdDyn 5 never+      return (current dScrutinized)+  , -- The lazy-hold knot with an fmap between the hold and the switch.+    testE' "lazy-hold-fmap" [(1, ()), (2, ())] $ do+      let lazyHoldFmap :: forall t m. (Reflex t, MonadHold t m, MonadFix m) => m (Event t ())+          lazyHoldFmap = do+            rec !b <- hold never e+                let e = never <$ switch (fmap id b)+            return $ void e+      e0 <- plan [(1, ()), (2, ())]+      tickle <- lazyHoldFmap+      return $ leftmost [tickle, e0]+  , testE' "switch-fmap-behavior" [(1, "hia"), (2, "lob"), (3, "hic"), (4, "lod")] $ do+      e1 <- plan [(1, "a"), (2, "b"), (3, "c"), (4, "d")]+      rec bFlag <- hold True (not <$> tag bFlag e1)+      let bE = (\f -> if f then ("hi" ++) <$> e1 else ("lo" ++) <$> e1) <$> bFlag+      return (switch bE)+  , testE' "coincidence-pull-switch-height" [(1, ()), (2, ()), (3, ()), (4, ())] $ do+      tick <- plan [(1, ()), (2, ()), (3, ()), (4, ())]+      rec bFlag <- hold False (not <$> tag bFlag tick)+      let hi = leftmost [tick, tick]+          bE = (\f -> if f then hi else tick) <$> bFlag+      return $ leftmost [void (coincidence (switch bE <$ hi)), tick]+  ]+  where+    events1, events2, events3 :: TestPlan t m => m (Event t String)     events1 = plan [(1, "a"), (2, "b"), (5, "c"), (7, "d"), (8, "e")]     events2 = plan [(1, "e"), (3, "d"), (4, "c"), (6, "b"), (7, "a")]     events3 = liftA2 mappend events1 events2@@ -379,16 +477,15 @@     ticks :: TestPlan t m => m (Event t ())     ticks = plan [(1, ()), (2, ()), (3, ()), (4, ()), (5, ()), (6, ())] -    eithers ::  TestPlan t m => m (Event t (Either String String))+    eithers :: TestPlan t m => m (Event t (Either String String))     eithers = plan [(1, Left "e"), (3, Left "d"), (4, Right "c"), (6, Right "b"), (7, Left "a")] -     values = "abcde"     toMap str = Map.fromList $ map (\c -> (c, c)) str      behavior1, behavior2 :: forall t m. TestPlan t m => m (Behavior t String)-    behavior1 =  hold "1" =<< events1-    behavior2 =  hold "2" =<< events2+    behavior1 = hold "1" =<< events1+    behavior2 = hold "2" =<< events2      deep e = leftmost [e, e]     leftmost2 e1 e2 = leftmost [e1, e2]
test/Reflex/TestPlan.hs view
@@ -6,47 +6,80 @@ {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-}-module Reflex.TestPlan-  ( TestPlan(..) +module Reflex.TestPlan+  ( TestPlan (..)   , TestCase (..)-  , testE, testB-  , TestE, TestB-+  , TestMeta (..)+  , emptyMeta+  , testE+  , testB+  , testE'+  , testB'+  , xfail+  , TestE+  , TestB   , planList-   ) where  import Control.DeepSeq import Control.Monad.Fix+import Data.IntMap (IntMap)+import qualified Data.IntMap as IntMap import Data.Word-import Reflex.Class-- import Prelude +import Reflex.Class+ class (Reflex t, MonadHold t m, MonadFix m) => TestPlan t m where   -- | Specify a plan of an input Event firing   -- Occurrences must be in the future (i.e. Time > 0)   -- Initial specification is-   plan :: [(Word, a)] -> m (Event t a) - planList :: TestPlan t m => [a] -> m (Event t a)-planList xs = plan $ zip [1..] xs+planList xs = plan $ zip [1 ..] xs  type TestE a = forall t m. TestPlan t m => m (Event t a) type TestB a = forall t m. TestPlan t m => m (Behavior t a) -data TestCase  where-  TestE  :: (Show a, Eq a, NFData a) => TestE a -> TestCase-  TestB  :: (Show a, Eq a, NFData a) => TestB a -> TestCase+data TestMeta v = TestMeta+  { expectedOutput :: Maybe (IntMap v)+  -- ^ When 'Nothing', the Pure implementation is used as the reference.+  , expectedFailures :: [String]+  -- ^ Names of implementations expected to diverge from the reference output.+  } +emptyMeta :: TestMeta v+emptyMeta = TestMeta Nothing []++data TestCase where+  TestE :: (Show a, Eq a, NFData a) => TestMeta (Maybe a) -> TestE a -> TestCase+  TestB :: (Show a, Eq a, NFData a) => TestMeta a -> TestB a -> TestCase+ -- Helpers to declare test cases testE :: (Eq a, Show a, NFData a) => String -> TestE a -> (String, TestCase)-testE name test = (name, TestE test)+testE name test = (name, TestE emptyMeta test)  testB :: (Eq a, Show a, NFData a) => String -> TestB a -> (String, TestCase)-testB name test = (name, TestB test)+testB name test = (name, TestB emptyMeta test) +-- | Declare an Event test case with a pinned expected output, given as the+-- frames at which the Event fires paired with the value fired at each.+testE' :: (Eq a, Show a, NFData a) => String -> [(Int, a)] -> TestE a -> (String, TestCase)+testE' name occurrences test =+  (name, TestE emptyMeta {expectedOutput = Just (Just <$> IntMap.fromList occurrences)} test)++-- | Declare a Behavior test case with a pinned expected output, given as the+-- value sampled at every frame from 0 to the last relevant frame.+testB' :: (Eq a, Show a, NFData a) => String -> [(Int, a)] -> TestB a -> (String, TestCase)+testB' name values test =+  (name, TestB emptyMeta {expectedOutput = Just (IntMap.fromList values)} test)++-- | Mark the named implementations as expected to diverge from the reference+-- output for this test case.+xfail :: [String] -> (String, TestCase) -> (String, TestCase)+xfail implementations (name, TestE meta test) =+  (name, TestE meta {expectedFailures = implementations} test)+xfail implementations (name, TestB meta test) =+  (name, TestB meta {expectedFailures = implementations} test)
test/RequesterT.hs view
@@ -1,6 +1,6 @@+{-# LANGUAGE BangPatterns #-} {-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-}-{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-}@@ -11,6 +11,7 @@ {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-}+ module Main where  import Control.Lens hiding (has)@@ -25,7 +26,7 @@ import Data.Functor.Misc import Data.List (words) import Data.Map (Map)-import qualified Data.Map as M+import qualified Data.Map as Map #if !MIN_VERSION_these(4,11,0) import Data.Semigroup ((<>)) #endif@@ -58,16 +59,12 @@  main :: IO () main = do-  os1 <- runApp' (unwrapApp testOrdering) $-    [ Just ()-    ]+  os1 <-+    runApp' (unwrapApp testOrdering) [Just ()]   print os1-  os2 <- runApp' (unwrapApp testSimultaneous) $ map Just $-    [ This ()-    , That ()-    , This ()-    , These () ()-    ]+  os2 <-+    runApp' (unwrapApp testSimultaneous) $+      map Just [This (), That (), This (), These () ()]   print os2   os3 <- runApp' (unwrapApp testMoribundRequest) [Just ()]   print os3@@ -77,58 +74,63 @@   print os5   os6 <- runApp' (unwrapApp delayedPulse) [Just ()]   print os6-  os7 <- runApp' testMatchRequestsWithResponses [ Just $ TestRequest_Increment 1 ]+  os7 <- runApp' testMatchRequestsWithResponses [Just $ TestRequest_Increment 1]   print os7-  os8 <- runApp' testMatchRequestsWithResponses [ Just $ TestRequest_Reverse "yoyo" ]+  os8 <- runApp' testMatchRequestsWithResponses [Just $ TestRequest_Reverse "yoyo"]   print os8-  let ![[Just [1,2,3,4,5,6,7,8,9,10]]] = os1 -- The order is reversed here: see the documentation for 'runRequesterT'-  let ![[Just [9,7,5,3,1]],[Nothing,Nothing],[Just [10,8,6,4,2]],[Just [10,8,6,4,2],Nothing]] = os2-  let ![[Nothing, Just [2]]] = os3-  let ![[Nothing, Just [2]]] = os4-  let ![[Nothing, Just [1, 2]]] = os5-  -- let ![[Nothing, Nothing]] = os6 -- TODO re-enable this test after issue #233 has been resolved-  let !(Just [(1,"2")]) = M.toList <$> head (head os7)-  let !(Just [(1,"oyoy")]) = M.toList <$> head (head os8)+  [[Just [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]] <- pure os1 -- The order is reversed here: see the documentation for 'runRequesterT'+  [[Just [9, 7, 5, 3, 1]], [Nothing, Nothing], [Just [10, 8, 6, 4, 2]], [Just [10, 8, 6, 4, 2], Nothing]] <- pure os2+  [[Nothing, Just [2]]] <- pure os3+  [[Nothing, Just [2]]] <- pure os4+  [[Nothing, Just [1, 2]]] <- pure os5+  -- [[Nothing, Nothing]] <- pure os6 -- TODO re-enable this test after issue #233 has been resolved+  (Just [(1, "2")] : _) : _ <- pure $ fmap (fmap Map.toList) <$> os7+  (Just [(1, "oyoy")] : _) : _ <- pure $ fmap (fmap Map.toList) <$> os8    return ()  unwrapRequest :: DSum tag RequestInt -> Int unwrapRequest (_ :=> RequestInt i) = i -unwrapApp :: ( Reflex t, Monad m )-          => (a -> RequesterT t RequestInt Identity m ())-          -> a-          -> m (Event t [Int])+unwrapApp+  :: (Reflex t, Monad m)+  => (a -> RequesterT t RequestInt Identity m ())+  -> a+  -> m (Event t [Int]) unwrapApp x appIn = do   ((), e) <- runRequesterT (x appIn) never   return $ fmap (map unwrapRequest . requesterDataToList) e -testOrdering :: ( Response m ~ Identity-                , Request m ~ RequestInt-                , Requester t m-                , Adjustable t m)-             => Event t ()-             -> m ()-testOrdering pulse = forM_ [10,9..1] $ \i ->+testOrdering+  :: ( Response m ~ Identity+     , Request m ~ RequestInt+     , Requester t m+     , Adjustable t m+     )+  => Event t ()+  -> m ()+testOrdering pulse = forM_ [10, 9 .. 1] $ \i ->   requestingIdentity (RequestInt i <$ pulse) -testSimultaneous :: ( Response m ~ Identity-                    , Request m ~ RequestInt-                    , Requester t m-                    , Adjustable t m)-                 => Event t (These () ())-                 -> m ()+testSimultaneous+  :: ( Response m ~ Identity+     , Request m ~ RequestInt+     , Requester t m+     , Adjustable t m+     )+  => Event t (These () ())+  -> m () testSimultaneous pulse = do   let tellE = fmapMaybe (^? here) pulse       switchE = fmapMaybe (^? there) pulse-  forM_ [1,3..9] $ \i -> runWithReplace (requestingIdentity (RequestInt i <$ tellE)) $ ffor switchE $ \_ ->-    requestingIdentity (RequestInt (i+1) <$ tellE)+  forM_ [1, 3 .. 9] $ \i -> runWithReplace (requestingIdentity (RequestInt i <$ tellE)) $ ffor switchE $ \_ ->+    requestingIdentity (RequestInt (i + 1) <$ tellE)  -- | Test that a widget requesting and event which fires at the same time it has been replaced -- doesn't count along with the new widget. testMoribundRequest   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -146,7 +148,7 @@ -- | The equivalent of 'testMoribundRequest' for 'traverseDMapWithKeyWithAdjust'. testMoribundRequestDMap   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -162,15 +164,15 @@       (_, rwrFinished :: Event t (PatchDMap (Const2 () Int) Identity)) <-         traverseDMapWithKeyWithAdjust           (\(Const2 ()) (Identity v) -> Identity . const v <$> requestIntOnReplace v)-          (mapToDMap $ M.singleton () 1)-          ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton () 2) <$ pulse)+          (mapToDMap $ Map.singleton () 1)+          (PatchDMap (DMap.map (ComposeMaybe . Just) $ mapToDMap $ Map.singleton () 2) <$ pulse)   return ()  -- | Ensures that elements which are _not_ removed can still fire requests -- during the same frame as other elements are updated. testLiveRequestDMap   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -186,13 +188,13 @@       (_, rwrFinished :: Event t (PatchDMap (Const2 Int ()) Identity)) <-         traverseDMapWithKeyWithAdjust           (\(Const2 k) (Identity ()) -> Identity <$> requestIntOnReplace k)-          (mapToDMap $ M.singleton 1 ())-          ((PatchDMap $ DMap.map (ComposeMaybe . Just) $ mapToDMap $ M.singleton 2 ()) <$ pulse)+          (mapToDMap $ Map.singleton 1 ())+          (PatchDMap (DMap.map (ComposeMaybe . Just) $ mapToDMap $ Map.singleton 2 ()) <$ pulse)   return ()  delayedPulse   :: forall t m-  .  ( Reflex t+   . ( Reflex t      , Adjustable t m      , MonadHold t m      , MonadFix m@@ -204,9 +206,9 @@   => Event t ()   -> m () delayedPulse pulse = void $ flip runWithReplace (pure () <$ pulse) $ do-    -- This has the effect of delaying pulse' from pulse-    (_, pulse') <- runWithReplace (pure ()) $ pure (RequestInt 1) <$ pulse-    requestingIdentity pulse'+  -- This has the effect of delaying pulse' from pulse+  (_, pulse') <- runWithReplace (pure ()) $ pure (RequestInt 1) <$ pulse+  requestingIdentity pulse'  testMatchRequestsWithResponses   :: forall m t req a@@ -221,12 +223,16 @@   => Event t (req a) -> m (Event t (Map Int String)) testMatchRequestsWithResponses pulse = mdo   (_, requests) <- runRequesterT (requesting pulse) responses-  let rawResponses = M.map (\v ->-        case words v of-          ["reverse", str] -> reverse str-          ["increment", i] -> show $ succ $ (read i :: Int)-        ) <$> rawRequestMap-  (rawRequestMap, responses) <- matchResponsesWithRequests reqEncoder requests (head . M.toList <$> rawResponses)+  let rawResponses =+        Map.map+          ( \v ->+              case words v of+                ["reverse", str] -> reverse str+                ["increment", i] | Just n <- readMaybe i -> show (succ (n :: Int))+                _ -> error $ "testMatchRequestsWithResponses: unexpected request " <> show v+          )+          <$> rawRequestMap+  (rawRequestMap, responses) <- matchResponsesWithRequests reqEncoder requests (fmapMaybe Map.lookupMin rawResponses)   pure rawResponses   where     reqEncoder :: forall a. req a -> (String, String -> Maybe a)
test/Test/Run.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-}+ module Test.Run where  import Control.Monad@@ -21,19 +22,23 @@   , _appOut_event :: Event t e   } -runApp :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)-       => (AppIn t bIn eIn -> PerformEventT t m (AppOut t bOut eOut))-       -> bIn-       -> [Maybe (These bIn eIn)]-       -> IO [[(bOut, Maybe eOut)]]+runApp+  :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)+  => (AppIn t bIn eIn -> PerformEventT t m (AppOut t bOut eOut))+  -> bIn+  -> [Maybe (These bIn eIn)]+  -> IO [[(bOut, Maybe eOut)]] runApp app b0 input = runSpiderHost $ do   (appInHoldE, pulseHoldTriggerRef) <- newEventWithTriggerRef   (appInE, pulseEventTriggerRef) <- newEventWithTriggerRef   appInB <- hold b0 appInHoldE-  (out, FireCommand fire) <- hostPerformEventT $ app $ AppIn-    { _appIn_event = appInE-    , _appIn_behavior = appInB-    }+  (out, FireCommand fire) <-+    hostPerformEventT+      $ app+      $ AppIn+        { _appIn_event = appInE+        , _appIn_behavior = appInB+        }   hnd <- subscribeEvent (_appOut_event out)   mpulseB <- readRef pulseHoldTriggerRef   mpulseE <- readRef pulseEventTriggerRef@@ -43,32 +48,34 @@         return (b, frames)   forM input $ \case     Nothing ->-      fire [] $ readPhase+      fire [] readPhase     Just i -> case i of       This b' -> case mpulseB of         Nothing -> error "tried to fire in-behavior but ref was empty"-        Just pulseB -> fire [ pulseB :=> Identity b' ] $ readPhase+        Just pulseB -> fire [pulseB :=> Identity b'] readPhase       That e' -> case mpulseE of         Nothing -> error "tried to fire in-event but ref was empty"-        Just pulseE -> fire [ pulseE :=> Identity e' ] $ readPhase+        Just pulseE -> fire [pulseE :=> Identity e'] readPhase       These b' e' -> case mpulseB of         Nothing -> error "tried to fire in-behavior but ref was empty"         Just pulseB -> case mpulseE of           Nothing -> error "tried to fire in-event but ref was empty"-          Just pulseE -> fire [ pulseB :=> Identity b', pulseE :=> Identity e' ] $ readPhase+          Just pulseE -> fire [pulseB :=> Identity b', pulseE :=> Identity e'] readPhase -runApp' :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)-        => (Event t eIn -> PerformEventT t m (Event t eOut))-        -> [Maybe eIn]-        -> IO [[Maybe eOut]]+runApp'+  :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)+  => (Event t eIn -> PerformEventT t m (Event t eOut))+  -> [Maybe eIn]+  -> IO [[Maybe eOut]] runApp' app input = do   let app' = fmap (AppOut (pure ())) . app   map (map snd) <$> runApp (app' . _appIn_event) () (map (fmap That) input) -runAppB :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)-        => (Event t eIn -> PerformEventT t m (Behavior t bOut))-        -> [Maybe eIn]-        -> IO [[bOut]]+runAppB+  :: (t ~ SpiderTimeline Global, m ~ SpiderHost Global)+  => (Event t eIn -> PerformEventT t m (Behavior t bOut))+  -> [Maybe eIn]+  -> IO [[bOut]] runAppB app input = do-  let app' = fmap (flip AppOut never) . app+  let app' = fmap (`AppOut` never) . app   map (map fst) <$> runApp (app' . _appIn_event) () (map (fmap That) input)
test/behaviorLeak.hs view
@@ -5,6 +5,7 @@ -- | Test whether Applicative combination of Behaviors leaks memory when one of -- the Behaviors' source events never occurs. -- (https://github.com/reflex-frp/reflex/issues/490)+module Main where  import Control.Monad import Control.Monad.IO.Class@@ -12,14 +13,14 @@ import Control.Monad.Ref import Data.Dependent.Sum import Data.Functor.Identity-import Data.Maybe (fromJust) import GHC.Stats-import Reflex-import Reflex.Host.Class import System.Exit import System.Mem (performMajorGC) import Text.Printf +import Reflex+import Reflex.Host.Class+ warmupTicks :: Int warmupTicks = 200000 windowTicks :: Int@@ -47,7 +48,7 @@   runSpiderHost $ do     (tickE, tickTriggerRef) <- newEventWithTriggerRef     b <- runHostFrame $ testCase tickE-    trigger <- fromJust <$> readRef tickTriggerRef+    Just trigger <- readRef tickTriggerRef     let fireOnce = void $ fireEventsAndRead [trigger :=> Identity ()] $ do           v <- sample b           v `seq` pure ()@@ -74,6 +75,9 @@           printf "Failed: Behavior Applicative space leak\n"           printf "    first-window avg live bytes:  %d\n" firstWindowAvg           printf "    second-window avg live bytes: %d\n" secondWindowAvg-          printf "    growth over %d intervening ticks: %d bytes (allowed %d)\n"-            ticksBetweenWindows growth allowedGrowthBytes+          printf+            "    growth over %d intervening ticks: %d bytes (allowed %d)\n"+            ticksBetweenWindows+            growth+            allowedGrowthBytes           exitFailure
+ test/collectedSubscriber.hs view
@@ -0,0 +1,229 @@+{-# LANGUAGE LambdaCase #-}++-- | Regression tests for space leaks & useless propagation. When the only+-- subscriber of an event is garbage collected instead of unsubscribed, the+-- event must still unsubscribe from its parent; otherwise the subscriptions up+-- to the root stay alive for as long as the application keeps a reference to+-- the event.+module Main where++import Control.Concurrent (newEmptyMVar, putMVar, tryTakeMVar, yield)+import Control.Exception (evaluate)+import Control.Monad (void)+import Control.Monad.IO.Class (liftIO)+import Data.Dependent.Sum (DSum ((:=>)))+import Data.Functor.Identity (Identity (..))+import Data.Functor.Misc (Const2 (..))+import Data.IORef (IORef, mkWeakIORef, modifyIORef', newIORef, readIORef, writeIORef)+import qualified Data.IntMap as IntMap+import qualified Data.Map as Map+import Data.Maybe (isNothing)+import System.Mem (performMajorGC)+import System.Mem.Weak (Weak, deRefWeak, mkWeakPtr)+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit++import Reflex+import Reflex.Host.Class+import qualified Reflex.Spider.Internal as S++type T = SpiderTimeline Global++collectTheOnlySubscriberThen+  :: (Event T Int -> (Event T Int, keep))+  -> (keep -> SpiderHost Global ())+  -> Assertion+collectTheOnlySubscriberThen build steps = do+  setupCount <- newIORef (0 :: Int)+  (finalCount, keep) <- runSpiderHost $ do+    root <- newEventWithTrigger $ \_ -> do+      modifyIORef' setupCount succ+      pure $ modifyIORef' setupCount pred+    case build root of+      (e, keep) -> do+        -- After this frame nothing references the 'hold'.+        runHostFrame $ void $ hold 0 e+        liftIO $ assertEqual "setupCount before the garbage collection" 1 =<< readIORef setupCount+        liftIO collectAndSettle+        steps keep+        finalCount <- liftIO $ readIORef setupCount+        pure (finalCount, keep)+  _ <- evaluate keep+  assertEqual "setupCount at the end" 0 finalCount++collectTheOnlySubscriber :: (Event T Int -> (Event T Int, keep)) -> Assertion+collectTheOnlySubscriber build = collectTheOnlySubscriberThen build (\_ -> pure ())++collectAndSettle :: IO ()+collectAndSettle = do+  done <- newEmptyMVar+  sentinel <- newIORef ()+  weakSentinel <- mkWeakPtr sentinel (Just (putMVar done ()))+  writeIORef sentinel ()+  performMajorGC+  let spin :: Int -> IO ()+      spin retries =+        tryTakeMVar done >>= \case+          Just () -> pure ()+          Nothing+            | retries <= 0 -> putStrLn "  warning: sentinel finalizer did not run"+            | otherwise -> yield >> performMajorGC >> spin (retries - 1)+  spin 1000+  _ <- evaluate weakSentinel+  pure ()++main :: IO ()+main =+  defaultMain $+    testGroup+      "collectedSubscriber"+      [ unsubscribeAfterCollection+      , unsubscribedSwitchReleasesBehavior+      , unsubscribedSwitchIsNotInvalidated+      , mergeUnsubscribedAfterItsPatchChangedItsHeight+      , coincidenceUnsubscribedAfterItRaisedItsHeight+      ]++unsubscribeAfterCollection :: TestTree+unsubscribeAfterCollection =+  testGroup+    "events unsubscribe from parent after GC of last subscriber"+    [ testCase "cacheEvent" $+        collectTheOnlySubscriber $ \root ->+          let cached = S.SpiderEvent $ S.cacheEvent $ S.unSpiderEvent root+          in (cached, cached)+    , testCase "merge" $+        collectTheOnlySubscriber $ \root ->+          let merged = leftmost [root]+          in (merged, merged)+    , -- For fan/fanInt we want unsubscribing from the parent even if the event selector is retained:+      testCase "fan" $+        collectTheOnlySubscriber $ \root ->+          let selector = fanMap $ fmapCheap (Map.singleton (0 :: Int)) root+          in (select selector (Const2 0), selector)+    , testCase "fanInt" $+        collectTheOnlySubscriber $ \root ->+          let selector = fanInt $ fmapCheap (IntMap.singleton 0) root+          in (selectInt selector 0, selector)+    , testCase "root" $+        collectTheOnlySubscriber $+          \root -> (root, root)+    , testCase "switch" $+        collectTheOnlySubscriber $ \root ->+          let switched = switch (constant root)+          in (switched, switched)+    , testCase "coincidence" $+        collectTheOnlySubscriber $ \root ->+          let inner = coincidence (fmapCheap (const root) root)+          in (inner, inner)+    ]++subscribeSwitchOverPull :: Behavior T Int -> Event T Int -> S.SpiderHostFrame Global (S.EventSubscription Global, Weak (IORef ()))+subscribeSwitchOverPull held inner = S.SpiderHostFrame $ do+  captured <- liftIO $ newIORef ()+  weakCaptured <- liftIO $ mkWeakIORef captured (pure ())+  let behavior = S.pull $ do+        _ <- S.readBehaviorTracked $ S.unSpiderBehavior held+        liftIO $ readIORef captured+        pure $ S.unSpiderEvent inner+      ignore =+        S.Subscriber+          { S.subscriberPropagate = \_ -> pure ()+          , S.subscriberInvalidateHeight = \_ -> pure ()+          , S.subscriberRecalculateHeight = \_ -> pure ()+          }+  S.SubscribeResult subscription _ <- S.subscribeAndRead (S.switchUncached behavior) ignore+  pure (subscription, weakCaptured)++unsubscribedSwitchReleasesBehavior :: TestTree+unsubscribedSwitchReleasesBehavior =+  testCase "an unsubscribed switch does not retain what its behavior captured or read" $ do+    (subscription, weakCaptured) <- runSpiderHost $ do+      (updates, _) <- newEventWithTriggerRef+      runHostFrame $ do+        held <- hold 0 updates+        subscribeSwitchOverPull held updates+    S.unsubscribe subscription+    collectAndSettle+    capturedIsCollected <- isNothing <$> deRefWeak weakCaptured+    _ <- evaluate subscription+    assertBool "the value that the behavior captured is collected" capturedIsCollected++-- | 'S.runFrame' errors if this reconnects the unsubscribed switch.+unsubscribedSwitchIsNotInvalidated :: TestTree+unsubscribedSwitchIsNotInvalidated =+  testCase "an update of a hold that an unsubscribed switch read does not invalidate the switch" $+    runSpiderHost $ do+      (updates, updatesTriggerRef) <- newEventWithTriggerRef+      (subscription, _) <- runHostFrame $ do+        held <- hold 0 updates+        subscribeSwitchOverPull held updates+      liftIO $ S.unsubscribe subscription+      fireEventRef updatesTriggerRef 1+      _ <- liftIO $ evaluate subscription+      pure ()++-- | A merge's patch changes its height in the frame in which its only+-- subscriber drops it. The merge must then keep its height, because that+-- subscriber belongs to a released cacheEvent record (checked under+-- DEBUG_FRAME).+mergeUnsubscribedAfterItsPatchChangedItsHeight :: TestTree+mergeUnsubscribedAfterItsPatchChangedItsHeight =+  testGroup+    "a merge whose patch changes its height in the frame in which its subscriber drops it"+    [ testCase (patchName <> ", " <> dropName) $ do+        occurrence <- runSpiderHost $ do+          (input, inputTriggerRef) <- newEventWithTriggerRef+          handle <- runHostFrame $ do+            members <- holdIncremental (IntMap.singleton 0 input) (patchOnInput input <$ input)+            subscribeEvent =<< dropOnInput input (sum <$> mergeIntIncremental members)+          fireEventRefAndRead inputTriggerRef 1 handle+        occurrence @?= Just 1+    | (patchName, patchOnInput) <-+        [ ("the patch removes the only member", \_ -> PatchIntMap (IntMap.singleton 0 Nothing))+        , -- A merge of the input is higher than the input.+          ("the patch adds a higher member", \input -> PatchIntMap (IntMap.singleton 1 (Just (leftmost [input]))))+        ]+          :: [(String, Event T Int -> PatchIntMap (Event T Int))]+    , (dropName, dropOnInput) <-+        [ ("a switch leaves the merge", \input merged -> switchHold merged (never <$ input))+        ,+          ( "a patch removes the merge from a merge"+          , \input merged -> do+              collection <- holdIncremental (IntMap.singleton 0 merged) (PatchIntMap (IntMap.singleton 0 Nothing) <$ input)+              pure $ sum <$> mergeIntIncremental collection+          )+        , -- The coincidence unsubscribes from its inner event at the end of the+          -- frame.+          ("the merge is the inner event of a coincidence", \input merged -> pure $ coincidence $ merged <$ input)+        ]+          :: [(String, Event T Int -> Event T Int -> HostFrame T (Event T Int))]+    ]++-- | A coincidence that raised its height and was dropped in the same frame+-- must not reset its height (checked under DEBUG_FRAME).+coincidenceUnsubscribedAfterItRaisedItsHeight :: TestTree+coincidenceUnsubscribedAfterItRaisedItsHeight =+  testGroup+    "a coincidence that raised its height, and whose subscriber unsubscribes in the same frame"+    [ testCase name $ do+        occurrence <- runSpiderHost $ do+          (input, inputTriggerRef) <- newEventWithTriggerRef+          handle <- runHostFrame $ do+            -- A merge of the input is higher than the input.+            let raised = coincidence $ leftmost [input] <$ input+            subscribeEvent =<< dropAtFirstOccurrence input raised+          fireEventRefAndRead inputTriggerRef 1 handle+        occurrence @?= Just 1+    | (name, dropAtFirstOccurrence) <-+        [ ("a headE of a merge unsubscribes in the propagation", \_ e -> headE $ leftmost [e])+        ,+          ( "a patch removes the coincidence from a merge"+          , \input e -> do+              members <- holdIncremental (IntMap.singleton 0 e) (PatchIntMap (IntMap.singleton 0 Nothing) <$ input)+              pure $ sum <$> mergeIntIncremental members+          )+        , ("the coincidence is the inner event of a coincidence", \input e -> pure $ coincidence $ e <$ input)+        ]+          :: [(String, Event T Int -> Event T Int -> HostFrame T (Event T Int))]+    ]
− test/hlint.hs
@@ -1,39 +0,0 @@-module Main where--import Control.Monad-import Language.Haskell.HLint (hlint)-import System.Directory-import System.Exit (exitFailure, exitSuccess)-import System.FilePath-import System.FilePath.Find--main :: IO ()-main = do-  pwd <- getCurrentDirectory-  let runHlint f = hlint $ f:-        [ "--ignore=Redundant do"-        , "--ignore=Use camelCase"-        , "--ignore=Redundant $"-        , "--ignore=Use &&"-        , "--ignore=Use &&&"-        , "--ignore=Use const"-        , "--ignore=Use >=>"-        , "--ignore=Use ."-        , "--ignore=Use unless"-        , "--ignore=Reduce duplication"-        , "--ignore=Replace case with maybe"-        , "--cpp-define=DEBUG"-        , "--ignore=Use tuple-section"-        ]-      recurseInto = and <$> sequence-        [ fileType ==? Directory-        , fileName /=? ".git"-        ]-      matchFile = and <$> sequence-        [ extension ==? ".hs"-        ]-  files <- find recurseInto matchFile (pwd </> "src") --TODO: Someday fix all hints in tests, etc.-  ideas <- fmap concat $ forM files $ \f -> do-    putStr $ "linting file " ++ drop (length pwd + 1) f ++ "... "-    runHlint f-  if null ideas then exitSuccess else exitFailure
+ test/newFanEventWithTrigger.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE GADTs #-}++-- | Regression test: 'fireEventsAndRead' fires all of its triggers in one+-- frame. This must also hold when two of the triggers are keys of one root+-- created by 'newFanEventWithTrigger'.+module Main where++import Control.Monad.IO.Class (liftIO)+import Data.Dependent.Sum (DSum ((:=>)))+import Data.Functor.Identity (Identity (..))+import Data.Functor.Misc (Const2 (..))+import Data.IORef (modifyIORef', newIORef, readIORef)+import qualified Data.Map as Map+import Test.Tasty+import Test.Tasty.HUnit++import Reflex+import Reflex.Host.Class++{- HLINT ignore main "Avoid restricted function" -}+main :: IO ()+main =+  defaultMain $+    testGroup+      "newFanEventWithTrigger"+      [ testCase "two keys fired in one frame both occur" $ do+          occurrences <- runSpiderHost $ do+            triggersRef <- liftIO $ newIORef (Map.empty :: Map.Map Int (EventTrigger Spider Int))+            selector <- newFanEventWithTrigger $ \(Const2 key) trigger -> do+              modifyIORef' triggersRef $ Map.insert key trigger+              pure $ modifyIORef' triggersRef $ Map.delete key+            (handle1, handle2) <-+              runHostFrame $+                (,)+                  <$> subscribeEvent (select selector (Const2 1 :: Const2 Int Int Int))+                  <*> subscribeEvent (select selector (Const2 2 :: Const2 Int Int Int))+            triggers <- liftIO $ readIORef triggersRef+            let readHandle handle = readEvent handle >>= sequence+            fireEventsAndRead [triggers Map.! 1 :=> Identity 10, triggers Map.! 2 :=> Identity 20] $+              (,) <$> readHandle handle1 <*> readHandle handle2+          occurrences @?= (Just 10, Just 20)+      ]
test/rootCleanup.hs view
@@ -1,10 +1,11 @@ import Control.Concurrent import Control.Monad import Data.IORef-import Reflex-import Reflex.Host.Class import System.Exit import System.Mem++import Reflex+import Reflex.Host.Class  main :: IO () main = do
+ test/runHostFrame.hs view
@@ -0,0 +1,33 @@+-- | 'runHostFrame' contains some optimizations which broke Spider when Reflex+-- gained `now`.+module Main where++import qualified Data.IntMap as IntMap+import Test.Tasty+import Test.Tasty.ExpectedFailure (expectFailBecause)+import Test.Tasty.HUnit++import Reflex+import Reflex.Host.Class++main :: IO ()+main =+  defaultMain $+    testGroup+      "runHostFrame"+      [ testCase "hold on now" $ do+          value <- runSpiderHost $ do+            b <- runHostFrame $ do+              buildTime <- now+              hold "initial" ("fired" <$ buildTime)+            runHostFrame $ sample b+          value @?= "fired"+      , expectFailBecause "runHostFrame never drains the delayed-merge queue, so the merge's occurrence is lost" $+          testCase "hold on mergeInt of now" $ do+            value <- runSpiderHost $ do+              b <- runHostFrame $ do+                buildTime <- now+                hold "initial" ("fired" <$ mergeInt (IntMap.singleton 0 buildTime))+              runHostFrame $ sample b+            value @?= "fired"+      ]
test/semantics.hs view
@@ -7,41 +7,36 @@  module Main (main) where -import Reflex.Test- import Data.Bifunctor-import Data.Functor import Data.List-import qualified Reflex.Bench.Focused as Focused-import qualified Reflex.Test.Micro as Micro- import System.Environment-import System.Exit- import Prelude +import qualified Reflex.Bench.Focused as Focused+import Reflex.Test+import qualified Reflex.Test.Micro as Micro+ matchPrefixes :: [String] -> (String -> Bool)-matchPrefixes []   = const True+matchPrefixes [] = const True matchPrefixes args = \name -> any (`isPrefixOf` name) args - main :: IO () main = do   args <- getArgs    case args of-    ["--list"] -> mapM_ putStrLn (fst <$> allTests) >> exitWith (ExitFailure 1)-    _          -> case filter (matchPrefixes args . fst) allTests of-                    []    -> putStrLn "filter did not match any tests" >> exitWith (ExitFailure 1)-                    tests -> runTests tests-+    ("--dump-expected" : prefixes) -> mapM_ dumpExpected (filter (matchPrefixes prefixes . fst) allTests)+    _ -> warnMissingExpected microTests >> runTests allTests   where-    allTests = concat-     [ makeGroup "micro" Micro.testCases-     , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)-     , makeGroup "firing 1000" (Focused.firing 1000)-     , makeGroup "merge 100" (Focused.merging 100)-     , makeGroup "fan 50" (Focused.fans 50)-     ]+    microTests = makeGroup "micro" Micro.testCases++    allTests =+      concat+        [ microTests+        , makeGroup "subscribing (100,40)" (Focused.subscribing 100 40)+        , makeGroup "firing 1000" (Focused.firing 1000)+        , makeGroup "merge 100" (Focused.merging 100)+        , makeGroup "fan 50" (Focused.fans 50)+        ]      makeGroup name tests = first (\test -> intercalate "/" [name, test]) <$> tests