@@ -1,2265 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE ExistentialQuantification #-}
6−{-# LANGUAGE FlexibleContexts #-}
7−{-# LANGUAGE FlexibleInstances #-}
8−{-# LANGUAGE FunctionalDependencies #-}
10−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
11−{-# LANGUAGE LambdaCase #-}
12−{-# LANGUAGE MagicHash #-}
13−{-# LANGUAGE MultiParamTypeClasses #-}
14−{-# LANGUAGE MultiWayIf #-}
15−{-# LANGUAGE RankNTypes #-}
16−{-# LANGUAGE RoleAnnotations #-}
17−{-# LANGUAGE ScopedTypeVariables #-}
18−{-# LANGUAGE TypeFamilies #-}
19−{-# LANGUAGE TypeOperators #-}
20−{-# LANGUAGE UndecidableInstances #-}
21−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
22−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
23−module Reflex.Spider.Internal
34−import Control.Applicative
35−import Control.Concurrent
36−import Control.Exception
37−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
38−import Control.Monad.Exception
39−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
40−import Control.Monad.Primitive
41−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
42−import Control.Monad.Ref
45−import Data.Dependent.Map (DMap, DSum (..))
46−import qualified Data.Dependent.Map as DMap
47−import Data.Foldable hiding (concat, elem, sequence_)
49−import Data.Functor.Compose
50−import Data.Functor.Constant
51−import Data.Functor.Product
52−import Data.GADT.Compare
53−import Data.IntMap.Strict (IntMap)
54−import qualified Data.IntMap.Strict as IntMap
56−import Data.List hiding (foldl')
58−import Data.Monoid ((<>))
59−import Data.Some (Some)
60−import qualified Data.Some as Some
62−import Data.Traversable
64−import GHC.IORef (IORef (..))
66−import System.IO.Unsafe
67−import System.Mem.Weak
71−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
72−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
73−import qualified Data.List.NonEmpty as NonEmpty
74−import Data.Monoid (mempty)
75−import Data.Tree (Forest, Tree (..), drawForest)
78−import Data.WeakBag (WeakBag, WeakBagTicket)
79−import qualified Data.WeakBag as WeakBag
80−import qualified Reflex.Class as R
81−import qualified Reflex.Host.Class as R
83−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
84−import Prelude hiding (any, concat, mapM, mapM_, sequence)
86−debugPropagate :: Bool
88−debugInvalidateHeight :: Bool
90−debugInvalidate :: Bool
98−debugInvalidateHeight = False
100−debugInvalidate = True
102−class HasNodeId a where
103− getNodeId :: a -> Int
105−instance HasNodeId (Hold x p a) where
106− getNodeId = holdNodeId
108−instance HasNodeId (PushSubscribed x a b) where
109− getNodeId = pushSubscribedNodeId
111−instance HasNodeId (SwitchSubscribed x a) where
112− getNodeId = switchSubscribedNodeId
114−instance HasNodeId (MergeSubscribed x a) where
115− getNodeId = mergeSubscribedNodeId
117−instance HasNodeId (FanSubscribed x a) where
118− getNodeId = fanSubscribedNodeId
120−instance HasNodeId (CoincidenceSubscribed x a) where
121− getNodeId = coincidenceSubscribedNodeId
123−instance HasNodeId (RootSubscribed x a) where
124− getNodeId = rootSubscribedNodeId
126−instance HasNodeId (Pull x a) where
127− getNodeId = pullNodeId
129−{-# INLINE showNodeId #-}
130−showNodeId :: HasNodeId a => a -> String
131−showNodeId = ("#"<>) . show . getNodeId
133−showSubscriberType :: Subscriber x a -> String
134−showSubscriberType = \case
135− SubscriberPush _ _ -> "SubscriberPush"
136− SubscriberMerge _ _ -> "SubscriberMerge"
137− SubscriberFan _ -> "SubscriberFan"
138− SubscriberMergeChange _ -> "SubscriberMergeChange"
139− SubscriberHold _ -> "SubscriberHold"
140− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
141− SubscriberSwitch _ -> "SubscriberSwitch"
142− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
143− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
144− SubscriberHandle -> "SubscriberHandle"
146−showEventType :: Event x a -> String
147−showEventType = \case
148− EventRoot _ _ -> "EventRoot"
149− EventNever -> "EventNever"
150− EventPush _ -> "EventPush"
151− EventMerge _ -> "EventMerge"
152− EventFan _ _ -> "EventFan"
153− EventSwitch _ -> "EventSwitch"
154− EventCoincidence _ -> "EventCoincidence"
155− EventHold _ -> "EventHold"
156− EventDyn _ -> "EventDyn"
157− EventHoldIdentity _ -> "EventHoldIdentity"
158− EventDynIdentity _ -> "EventDynIdentity"
162−debugPropagate = False
164−debugInvalidateHeight = False
166−debugInvalidate = False
168−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
169−{-# INLINE showNodeId #-}
170−showNodeId :: a -> String
176−{-# NOINLINE nextNodeIdRef #-}
177−nextNodeIdRef :: IORef Int
178−nextNodeIdRef = unsafePerformIO $ newIORef 1
181−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
183−{-# NOINLINE unsafeNodeId #-}
184−unsafeNodeId :: a -> Int
185−unsafeNodeId a = unsafePerformIO $ do
190−--------------------------------------------------------------------------------
192−--------------------------------------------------------------------------------
194−newtype Event x a = Event { subscribeAndRead :: Subscriber x a -> EventM x (EventSubscription x a, Maybe a) }
196−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x a)
197−subscribe e s = fst <$> subscribeAndRead e s
200−wrap :: MonadIO m => (t -> EventSubscribed x a) -> (Subscriber x a -> m (WeakBagTicket (Subscriber x a), t, Maybe a)) -> Subscriber x a -> m (EventSubscription x a, Maybe a)
201−wrap tag getSpecificSubscribed sub = do
202− (sln, subd, occ) <- getSpecificSubscribed sub
204− return (EventSubscription (Just sln) es, occ)
206−eventRoot :: GCompare k => k a -> Root x k -> Event x a
207−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
209−eventNever :: Event x a
210−eventNever = Event $ \_ -> return (EventSubscription Nothing eventSubscribedNever, Nothing)
212−eventPush :: Push x b a -> Event x a
213−eventPush !p = Event $ wrap eventSubscribedPush $ getPushSubscribed p
215−eventMerge :: (GCompare k, a ~ DMap k Identity) => Merge x k -> Event x a
216−eventMerge !m = Event $ wrap eventSubscribedMerge $ getMergeSubscribed m
218−eventFan :: GCompare k => k a -> Fan x k -> Event x a
219−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
221−eventSwitch :: Switch x a -> Event x a
222−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
224−eventCoincidence :: Coincidence x a -> Event x a
225−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
227−eventHold :: a ~ p b => Hold x p b -> Event x a
228−eventHold !h = Event $ subscribeHoldEvent h
230−eventDyn :: (a ~ p b, R.Patch p) => Dyn x p b -> Event x a
231−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
233−{-# INLINE subscribeCoincidenceInner #-}
234−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x a)
235−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
236− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
237− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
238− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
239− let height = max innerHeight outerHeight
240− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
241− return (innerOcc, height, innerSubd)
243−--------------------------------------------------------------------------------
245−--------------------------------------------------------------------------------
247−data Subscriber x a = Subscriber
248− { subscriberPropagate :: !(a -> EventM x ())
249− , subscriberInvalidateHeight :: !(Height -> IO ())
250− , subscriberRecalculateHeight :: !(Height -> IO ())
253−--TODO: Move this comment to WeakBag
254−-- These function are constructor functions that are marked NOINLINE so they are
255−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
256−-- so any weak references that are attached to the constructors will have their
257−-- finalizer run. Using the opaque constructor, does not see the
258−-- constructor application, so it behaves like an IORef and cannot be fused away.
260−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
261−-- the weak pointer to it in some cases.
263−newSubscriberPush :: (a -> ComputeM x (Maybe b)) -> PushSubscribed x a b -> IO (Subscriber x a)
264−newSubscriberPush compute subscribed = return $ Subscriber
265− { subscriberPropagate = \a -> {-# SCC "traversePush" #-} do
266− tracePropagate $ "SubscriberPush" <> showNodeId subscribed
267− occ <- runComputeM $ compute a
269− Nothing -> return () -- No need to write a Nothing back into the Ref
271− liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
272− scheduleClear $ pushSubscribedOccurrence subscribed
273− propagate o $ pushSubscribedSubscribers subscribed
274− , subscriberInvalidateHeight = \old -> do
275− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
276− WeakBag.traverse (pushSubscribedSubscribers subscribed) $ invalidateSubscriberHeight old
277− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
278− , subscriberRecalculateHeight = \new -> do
279− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
280− WeakBag.traverse (pushSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
281− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
284−newSubscriberHold :: R.Patch p => Hold x p a -> IO (Subscriber x (p a))
285−newSubscriberHold h = return $ Subscriber
286− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
287− , subscriberInvalidateHeight = \_ -> return ()
288− , subscriberRecalculateHeight = \_ -> return ()
291−newSubscriberMerge :: GCompare k => k a -> MergeSubscribed x k -> IO (Subscriber x a)
292−newSubscriberMerge k subscribed = return $ Subscriber
293− { subscriberPropagate = \a -> {-# SCC "traverseMerge" #-} do
294− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
295− oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
296− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge" <> showNodeId subscribed) k (Identity a) oldM
297− tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
298− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! newM
299− when (DMap.null oldM) $ do -- Only schedule the firing once
300− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
301− --TODO: assertions about height
302− currentHeight <- getCurrentHeight
303− when (height <= currentHeight) $ do
304− if height /= invalidHeight
306− myStack <- liftIO $ whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
307− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
310− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
311− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
312− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
316− error $ "Causality loop found" <> cycleInfo
317− scheduleMerge height subscribed
318− , subscriberInvalidateHeight = \old -> do
319− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
320− removeMergeHeight old subscribed
321− invalidateMergeHeight subscribed
322− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
323− , subscriberRecalculateHeight = \new -> do
324− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
325− addMergeHeight new subscribed
326− revalidateMergeHeight subscribed
327− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
330−newSubscriberMergeChange :: GCompare k => MergeSubscribed x k -> IO (Subscriber x (R.PatchDMap (DMap k (Event x))))
331−newSubscriberMergeChange subscribed = return $ Subscriber
332− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
333− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
334− defer $ SomeMergeUpdate a subscribed
335− , subscriberInvalidateHeight = \_ -> return ()
336− , subscriberRecalculateHeight = \_ -> return ()
339−newSubscriberFan :: GCompare k => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
340−newSubscriberFan subscribed = return $ Subscriber
341− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
342− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
343− tracePropagate $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
344− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
345− scheduleClear $ fanSubscribedOccurrence subscribed
346− let f _ (Pair (Identity v) subsubs) = do
347− propagate v $ _fanSubscribedChildren_list subsubs
348− return $ Constant ()
349− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
351− , subscriberInvalidateHeight = \old -> do
352− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
353− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
354− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
355− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
356− , subscriberRecalculateHeight = \new -> do
357− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
358− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
359− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
360− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
363−newSubscriberSwitch :: SwitchSubscribed x a -> IO (Subscriber x a)
364−newSubscriberSwitch subscribed = return $ Subscriber
365− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
366− tracePropagate $ "SubscriberSwitch" <> showNodeId subscribed
367− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
368− scheduleClear $ switchSubscribedOccurrence subscribed
369− propagate a $ switchSubscribedSubscribers subscribed
370− , subscriberInvalidateHeight = \_ -> do
371− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
372− oldHeight <- readIORef $ switchSubscribedHeight subscribed
373− when (oldHeight /= invalidHeight) $ do
374− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
375− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
376− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
377− , subscriberRecalculateHeight = \new -> do
378− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
379− updateSwitchHeight new subscribed
380− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
383−newSubscriberCoincidenceOuter :: CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
384−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
385− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
386− tracePropagate $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
387− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
388− tracePropagate $ " outerHeight = " <> show outerHeight
389− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
390− tracePropagate $ " isJust occ = " <> show (isJust occ)
391− tracePropagate $ " innerHeight = " <> show innerHeight
392− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
393− scheduleClear $ coincidenceSubscribedInnerParent subscribed
396− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
397− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
398− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
399− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
400− Just o -> do -- Since it's already firing, no need to adjust height
401− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
402− scheduleClear $ coincidenceSubscribedOccurrence subscribed
403− propagate o $ coincidenceSubscribedSubscribers subscribed
404− , subscriberInvalidateHeight = \_ -> do
405− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
406− invalidateCoincidenceHeight subscribed
407− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
408− , subscriberRecalculateHeight = \_ -> do
409− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
410− recalculateCoincidenceHeight subscribed
411− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
414−newSubscriberCoincidenceInner :: CoincidenceSubscribed x a -> IO (Subscriber x a)
415−newSubscriberCoincidenceInner subscribed = return $ Subscriber
416− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
417− tracePropagate $ "SubscriberCoincidenceInner" <> showNodeId subscribed
418− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
420− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
422− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
423− scheduleClear $ coincidenceSubscribedOccurrence subscribed
424− propagate a $ coincidenceSubscribedSubscribers subscribed
425− , subscriberInvalidateHeight = \_ -> do
426− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
427− invalidateCoincidenceHeight subscribed
428− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
429− , subscriberRecalculateHeight = \_ -> do
430− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
431− recalculateCoincidenceHeight subscribed
432− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
435−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
436−invalidateSubscriberHeight = flip subscriberInvalidateHeight
438−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
439−recalculateSubscriberHeight = flip subscriberRecalculateHeight
441−-- | Propagate everything at the current height
442−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
443−propagate a subscribers = withIncreasedDepth $ do
444− -- 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
445− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
446− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
448−--------------------------------------------------------------------------------
450−--------------------------------------------------------------------------------
452−data EventSubscribed x a = forall b. EventSubscribed
453− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
454− , eventSubscribedRetained :: {-# NOUNPACK #-} !b
456− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
457− , eventSubscribedHasOwnHeightRef :: !Bool
458− , eventSubscribedWhoCreated :: !(IO [String])
462−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x a
463−eventSubscribedRoot !r = EventSubscribed
464− { eventSubscribedHeightRef = zeroRef
465− , eventSubscribedRetained = r
467− , eventSubscribedGetParents = return []
468− , eventSubscribedHasOwnHeightRef = False
469− , eventSubscribedWhoCreated = return ["root"]
473−eventSubscribedNever :: EventSubscribed x a
474−eventSubscribedNever = EventSubscribed
475− { eventSubscribedHeightRef = zeroRef
476− , eventSubscribedRetained = ()
478− , eventSubscribedGetParents = return []
479− , eventSubscribedHasOwnHeightRef = False
480− , eventSubscribedWhoCreated = return ["never"]
484−eventSubscribedPush :: PushSubscribed x b a -> EventSubscribed x a
485−eventSubscribedPush !subscribed = EventSubscribed
486− { eventSubscribedHeightRef = pushSubscribedHeight subscribed
487− , eventSubscribedRetained = subscribed
489− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ pushSubscribedParent subscribed]
490− , eventSubscribedHasOwnHeightRef = False
491− , eventSubscribedWhoCreated = whoCreatedIORef $ pushSubscribedCachedSubscribed subscribed
495−eventSubscribedMerge :: MergeSubscribed x k -> EventSubscribed x a
496−eventSubscribedMerge !subscribed = EventSubscribed
497− { eventSubscribedHeightRef = mergeSubscribedHeight subscribed
498− , eventSubscribedRetained = subscribed
500− , eventSubscribedGetParents = do
501− ps <- readIORef $ mergeSubscribedParents subscribed
502− return $ R.ffor (DMap.toList ps) $ \(_ :=> v) -> Some.This $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription v
503− , eventSubscribedHasOwnHeightRef = True
504− , eventSubscribedWhoCreated = whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
508−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x a
509−eventSubscribedFan !subscribed = EventSubscribed
510− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
511− , eventSubscribedRetained = subscribed
513− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
514− , eventSubscribedHasOwnHeightRef = False
515− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
519−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x a
520−eventSubscribedSwitch !subscribed = EventSubscribed
521− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
522− , eventSubscribedRetained = subscribed
524− , eventSubscribedGetParents = do
525− s <- readIORef $ switchSubscribedCurrentParent subscribed
526− return [Some.This $ _eventSubscription_subscribed s]
527− , eventSubscribedHasOwnHeightRef = True
528− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
532−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x a
533−eventSubscribedCoincidence !subscribed = EventSubscribed
534− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
535− , eventSubscribedRetained = subscribed
537− , eventSubscribedGetParents = do
538− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
539− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
540− innerParents = maybeToList $ fmap Some.This innerSubscription
541− return $ outerParent : innerParents
542− , eventSubscribedHasOwnHeightRef = True
543− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
547−getEventSubscribedHeight :: EventSubscribed x a -> IO Height
548−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
551−whoCreatedEventSubscribed :: EventSubscribed x a -> IO [String]
552−whoCreatedEventSubscribed = eventSubscribedWhoCreated
554−walkInvalidHeightParents :: EventSubscribed x a -> IO [Some (EventSubscribed x)]
555−walkInvalidHeightParents s0 = do
556− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
557− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
558− when (h == invalidHeight) $ do
559− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
560− modify (Some.This s :)
561− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
562− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
566−{-# INLINE subscribeHoldEvent #-}
567−subscribeHoldEvent :: CanSubscribe x m => Hold x p a -> Subscriber x (p a) -> m (EventSubscription x (p a), Maybe (p a))
568−subscribeHoldEvent = subscribeAndRead . holdEvent
570−--------------------------------------------------------------------------------
572−--------------------------------------------------------------------------------
574−data EventSubscription x a = EventSubscription
575− { _eventSubscription_ticket :: !(Maybe (WeakBagTicket (Subscriber x a)))
576− , _eventSubscription_subscribed :: !(EventSubscribed x a)
579−unsubscribe :: EventSubscription x a -> IO ()
580−unsubscribe (EventSubscription msln _) = forM_ msln $ \sln -> WeakBag.remove sln
582−--------------------------------------------------------------------------------
584−--------------------------------------------------------------------------------
586−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
588−behaviorHold :: Hold x p a -> Behavior x a
589−behaviorHold !h = Behavior $ readHoldTracked h
591−behaviorHoldIdentity :: Hold x Identity a -> Behavior x a
592−behaviorHoldIdentity = behaviorHold
594−behaviorConst :: a -> Behavior x a
595−behaviorConst !a = Behavior $ return a
597−behaviorPull :: Pull x a -> Behavior x a
598−behaviorPull !p = Behavior $ do
599− val <- liftIO $ readIORef $ pullValue p
601− Just subscribed -> do
602− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
603− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
604− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
605− return $ pullSubscribedValue subscribed
607− i <- liftIO $ newInvalidatorPull p
608− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
609− parentsRef <- liftIO $ newIORef []
610− holdInits <- askBehaviorHoldInits
611− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
612− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
613− parents <- liftIO $ readIORef parentsRef
614− let subscribed = PullSubscribed
615− { pullSubscribedValue = a
616− , pullSubscribedInvalidators = invsRef
617− , pullSubscribedOwnInvalidator = i
618− , pullSubscribedParents = parents
620− liftIO $ writeIORef (pullValue p) $ Just subscribed
621− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
624−behaviorDyn :: R.Patch p => Dyn x p a -> Behavior x a
625−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
627−{-# INLINE readHoldTracked #-}
628−readHoldTracked :: Hold x p a -> BehaviorM x a
629−readHoldTracked h = do
630− result <- liftIO $ readIORef $ holdValue h
631− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
632− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
635−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> BehaviorM x a #-}
636−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> EventM x a #-}
637−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
638−readBehaviorUntracked b = do
639− holdInits <- getDeferralQueue
640− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
642−--------------------------------------------------------------------------------
644−--------------------------------------------------------------------------------
646−data Dynamic x p a = Dynamic
647− { dynamicCurrent :: !(Behavior x a)
648− , dynamicUpdated :: !(Event x (p a))
651−dynamicHold :: Hold x p a -> Dynamic x p a
652−dynamicHold !h = Dynamic
653− { dynamicCurrent = behaviorHold h
654− , dynamicUpdated = eventHold h
657−dynamicHoldIdentity :: Hold x Identity a -> Dynamic x Identity a
658−dynamicHoldIdentity = dynamicHold
660−dynamicConst :: a -> Dynamic x p a
661−dynamicConst !a = Dynamic
662− { dynamicCurrent = behaviorConst a
663− , dynamicUpdated = eventNever
666−dynamicDyn :: R.Patch p => Dyn x p a -> Dynamic x p a
667−dynamicDyn !d = Dynamic
668− { dynamicCurrent = behaviorDyn d
669− , dynamicUpdated = eventDyn d
672−dynamicDynIdentity :: Dyn x Identity a -> Dynamic x Identity a
673−dynamicDynIdentity = dynamicDyn
675−--------------------------------------------------------------------------------
677−--------------------------------------------------------------------------------
679−--TODO: Figure out why certain things are not 'representational', then make them
680−--representational so we can use coerce
682−--type role Hold representational
684− = Hold { holdValue :: !(IORef a)
685− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
686− , holdEvent :: Event x (p a) -- This must be lazy, or holds cannot be defined before their input Events
687− , holdParent :: !(IORef (Maybe (EventSubscription x (p a)))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
694− = EventEnv { eventEnvSpiderEnv :: !(SpiderEnv x)
695− , eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
696− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
697− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
698− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
699− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
700− , eventEnvRootClears :: !(IORef [SomeRootClear])
701− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
702− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
703− , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge x]))
706−{-# INLINE runEventM #-}
707−runEventM :: EventM x a -> EventEnv x -> IO a
708−runEventM = runReaderT . unEventM
710−class MonadIO m => Defer a m where
711− getDeferralQueue :: m (IORef [a])
714−defer :: Defer a m => a -> m ()
716− q <- getDeferralQueue
717− liftIO $ modifyIORef' q (a:)
719−instance Defer (SomeAssignment x) (EventM x) where
720− {-# INLINE getDeferralQueue #-}
721− getDeferralQueue = EventM $ asks eventEnvAssignments
723−instance Defer (SomeHoldInit x) (EventM x) where
724− {-# INLINE getDeferralQueue #-}
725− getDeferralQueue = EventM $ asks eventEnvHoldInits
727−instance Defer (SomeHoldInit x) (BehaviorM x) where
728− {-# INLINE getDeferralQueue #-}
729− getDeferralQueue = BehaviorM $ asks snd
731−instance Defer (SomeMergeUpdate x) (EventM x) where
732− {-# INLINE getDeferralQueue #-}
733− getDeferralQueue = EventM $ asks eventEnvMergeUpdates
735−instance Defer (SomeMergeInit x) (EventM x) where
736− {-# INLINE getDeferralQueue #-}
737− getDeferralQueue = EventM $ asks eventEnvMergeInits
739−class HasCurrentHeight x m | m -> x where
740− getCurrentHeight :: m Height
741− scheduleMerge :: Height -> MergeSubscribed x a -> m ()
743−instance HasCurrentHeight x (EventM x) where
744− {-# INLINE getCurrentHeight #-}
745− getCurrentHeight = EventM $ do
746− heightRef <- asks eventEnvCurrentHeight
747− liftIO $ readIORef heightRef
748− {-# INLINE scheduleMerge #-}
749− scheduleMerge height subscribed = EventM $ do
750− delayedRef <- asks eventEnvDelayedMerges
751− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [DelayedMerge subscribed]
753−class HasSpiderEnv x m | m -> x where
754− -- | Retrieve the current SpiderEnv
755− askSpiderEnv :: m (SpiderEnv x)
757−instance HasSpiderEnv x (EventM x) where
758− {-# INLINE askSpiderEnv #-}
759− askSpiderEnv = EventM $ asks eventEnvSpiderEnv
761−instance HasSpiderEnv x (SpiderHost x) where
762− {-# INLINE askSpiderEnv #-}
763− askSpiderEnv = SpiderHost ask
765−putCurrentHeight :: Height -> EventM x ()
766−putCurrentHeight h = EventM $ do
767− heightRef <- asks eventEnvCurrentHeight
768− liftIO $ writeIORef heightRef $! h
770−instance Defer SomeClear (EventM x) where
771− {-# INLINE getDeferralQueue #-}
772− getDeferralQueue = EventM $ asks eventEnvClears
774−{-# INLINE scheduleClear #-}
775−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
776−scheduleClear r = defer $ SomeClear r
778−instance Defer SomeRootClear (EventM x) where
779− {-# INLINE getDeferralQueue #-}
780− getDeferralQueue = EventM $ asks eventEnvRootClears
782−{-# INLINE scheduleRootClear #-}
783−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
784−scheduleRootClear r = defer $ SomeRootClear r
786−instance Defer (SomeResetCoincidence x) (EventM x) where
787− {-# INLINE getDeferralQueue #-}
788− getDeferralQueue = EventM $ asks eventEnvResetCoincidences
790−-- Note: hold cannot examine its event until after the phase is over
791−{-# SPECIALIZE hold :: R.Patch p => a -> Event x (p a) -> EventM x (Hold x p a) #-}
792−{-# SPECIALIZE hold :: R.Patch p => a -> Event x (p a) -> ComputeM x (Hold x p a) #-}
793−hold :: (R.Patch p, Defer (SomeHoldInit x) m) => a -> Event x (p a) -> m (Hold x p a)
795− valRef <- liftIO $ newIORef v0
796− invsRef <- liftIO $ newIORef []
797− parentRef <- liftIO $ newIORef Nothing
799− nodeId <- liftIO newNodeId
802− { holdValue = valRef
803− , holdInvalidators = invsRef
805− , holdParent = parentRef
807− , holdNodeId = nodeId
810− defer $ SomeHoldInit h
813−{-# INLINE getHoldEventSubscription #-}
814−getHoldEventSubscription :: forall m p a x. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer SomeClear m, R.Patch p, HasCurrentHeight x m, Defer (SomeMergeInit x) m, Defer (SomeResetCoincidence x) m, HasSpiderEnv x m, m ~ EventM x) => Hold x p a -> m (EventSubscription x (p a))
815−getHoldEventSubscription h = do
816− ep <- liftIO $ readIORef $ holdParent h
818− Just subd -> return subd
821− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
822− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
823− liftIO $ writeIORef subscriptionRef $! subscription
825− Nothing -> return ()
827− old <- liftIO $ readIORef $ holdValue h
828− case R.apply o old of
829− Nothing -> return ()
831− -- Need to evaluate these so that we don't retain the Hold itself
832− v <- liftIO $ evaluate $ holdValue h
833− i <- liftIO $ evaluate $ holdInvalidators h
834− defer $ SomeAssignment v i new
835− liftIO $ writeIORef (holdParent h) $ Just subscription
838−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
840−--type role BehaviorM representational
841−-- BehaviorM can sample behaviors
842−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
844−instance Monad (BehaviorM x) where
845− {-# INLINE (>>=) #-}
846− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
848− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
849− {-# INLINE return #-}
850− return x = BehaviorM $ return x
852− fail s = BehaviorM $ fail s
854−data BehaviorSubscribed x a
855− = forall p. BehaviorSubscribedHold (Hold x p a)
856− | BehaviorSubscribedPull (PullSubscribed x a)
858−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
860−--type role PullSubscribed representational
861−data PullSubscribed x a
862− = PullSubscribed { pullSubscribedValue :: !a
863− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
864− , pullSubscribedOwnInvalidator :: !(Invalidator x)
865− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
868−--type role Pull representational
870− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
871− , pullCompute :: !(BehaviorM x a)
878− = forall a. InvalidatorPull (Pull x a)
879− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
881−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
882− { rootSubscribedKey :: !(k a)
883− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
884− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
885− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
886− , rootSubscribedUninit :: IO ()
887− , 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?
889− , rootSubscribedNodeId :: Int
893−data Root x (k :: * -> *)
894− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
895− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
896− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
899−data SomeHoldInit x = forall p a. R.Patch p => SomeHoldInit !(Hold x p a)
901−data SomeMergeUpdate x = forall k. GCompare k => SomeMergeUpdate (R.PatchDMap (DMap k (Event x))) (MergeSubscribed x k)
903−data SomeMergeInit x = forall k. GCompare k => SomeMergeInit !(MergeSubscribed x k) !(Event x (R.PatchDMap (DMap k (Event x))))
905−data SomeEventSubscription x = forall a. SomeEventSubscription (EventSubscription x a)
907−-- EventM can do everything BehaviorM can, plus create holds
908−newtype EventM x (a :: *) = EventM { unEventM :: ReaderT (EventEnv x) IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadFix, MonadException, MonadAsyncException) -- The environment should be Nothing if we are not in a frame, and Just if we are - in which case it is a list of assignments to be done after the frame is over
910−data PushSubscribed x a b
911− = PushSubscribed { pushSubscribedCachedSubscribed :: !(IORef (Maybe (PushSubscribed x a b)))
912− , pushSubscribedOccurrence :: !(IORef (Maybe b)) -- If the current height is less than our height, this should always be Nothing; during our height, this will get filled in at some point, always before our children are notified; after our height, this will be filled in with the correct value (Nothing if we are not firing, Just if we are)
913− , pushSubscribedHeight :: !(IORef Height)
914− , pushSubscribedSubscribers :: !(WeakBag (Subscriber x b))
915− , pushSubscribedSelf :: !(Subscriber x a) -- Hold this in memory to ensure our WeakReferences don't die --TODO: Probably unneeded now
916− , pushSubscribedWeakSelf :: !(IORef (Weak (PushSubscribed x a b)))
917− , pushSubscribedParent :: !(EventSubscription x a)
919− , pushSubscribedNodeId :: Int
923−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
925−instance Defer (SomeHoldInit x) (ComputeM x) where
926− getDeferralQueue = ComputeM ask
928−{-# SPECIALIZE runComputeM :: ComputeM x a -> EventM x a #-}
929−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
930−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
933− = Push { pushCompute :: !(a -> ComputeM x (Maybe b)) -- Compute the current firing value; assumes that its parent has been computed --TODO: This only uses Defer SomeHoldInit EventM; perhaps only the hold init queue should be passed in (also, perhaps those hold inits can be accelerated - can there be a loop we would need to worry about?)
934− , pushParent :: !(Event x a)
935− , pushSubscribed :: !(IORef (Maybe (PushSubscribed x a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
938−data MergeSubscribedParent (x :: *) k a = MergeSubscribedParent !(EventSubscription x a) !(Subscriber x a)
940−mergeSubscribedParentSubscription :: MergeSubscribedParent x k a -> EventSubscription x a
941−mergeSubscribedParentSubscription (MergeSubscribedParent es _) = es
943−data HeightBag = HeightBag
944− { _heightBag_size :: {-# UNPACK #-} !Int
945− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
947− deriving (Show, Read, Eq, Ord)
949−heightBagEmpty :: HeightBag
950−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
952−heightBagSize :: HeightBag -> Int
953−heightBagSize = _heightBag_size
955−heightBagFromList :: [Height] -> HeightBag
956−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
958−heightBagAdd :: Height -> HeightBag -> HeightBag
959−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
961−heightBagRemove :: Height -> HeightBag -> HeightBag
962−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
963− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
964− Just old -> HeightBag (pred s) $ case old of
965− 0 -> IntMap.delete h c
966− _ -> IntMap.insert h (pred old) c
968−heightBagMax :: HeightBag -> Height
969−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
970− Just ((h, _), _) -> Height h
971− Nothing -> zeroHeight
973−heightBagVerify :: HeightBag -> HeightBag
975−heightBagVerify b@(HeightBag s c) = if
976− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
977− -> error $ "heightBagVerify: size doesn't match: " <> show b
978− | unHeight invalidHeight `IntMap.member` c
979− -> error $ "heightBagVerify: contains invalid height: " <> show b
985−data MergeSubscribed x k
986− = MergeSubscribed { mergeSubscribedCachedSubscribed :: !(IORef (Maybe (MergeSubscribed x k))) -- From the original merge
987− , mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
988− , mergeSubscribedAccum :: !(IORef (DMap k Identity)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
989− , mergeSubscribedHeight :: !(IORef Height)
990− , mergeSubscribedHeightBag :: !(IORef HeightBag)
991− , mergeSubscribedSubscribers :: !(WeakBag (Subscriber x (DMap k Identity)))
992− , mergeSubscribedChange :: !(IORef (Subscriber x (R.PatchDMap (DMap k (Event x))), EventSubscribed x (R.PatchDMap (DMap k (Event x)))))
993− , mergeSubscribedParents :: !(IORef (DMap k (MergeSubscribedParent x k)))
994− , mergeSubscribedWeakSelf :: !(IORef (Weak (MergeSubscribed x k)))
996− , mergeSubscribedNodeId :: Int
1000−--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
1002− = Merge { mergeParents :: !(Dynamic x R.PatchDMap (DMap k (Event x)))
1003− , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed x k)))
1006−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1007− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1008− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1009− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1012−data FanSubscribed (x :: *) k
1013− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1014− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1015− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1016− , fanSubscribedParent :: !(EventSubscription x (DMap k Identity))
1017−#ifdef DEBUG_NODEIDS
1018− , fanSubscribedNodeId :: Int
1023− = Fan { fanParent :: !(Event x (DMap k Identity))
1024− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1027−data SwitchSubscribed x a
1028− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1029− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1030− , switchSubscribedHeight :: !(IORef Height)
1031− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1032− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1033− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1034− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1035− , switchSubscribedParent :: !(Behavior x (Event x a))
1036− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x a))
1037− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1038−#ifdef DEBUG_NODEIDS
1039− , switchSubscribedNodeId :: Int
1044− = Switch { switchParent :: !(Behavior x (Event x a))
1045− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1048−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1049−data CoincidenceSubscribed x a
1050− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1051− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1052− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1053− , coincidenceSubscribedHeight :: !(IORef Height)
1054− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1055− , coincidenceSubscribedOuterParent :: !(EventSubscription x (Event x a))
1056− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x a)))
1057− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1058−#ifdef DEBUG_NODEIDS
1059− , coincidenceSubscribedNodeId :: Int
1063−data Coincidence x a
1064− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1065− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1068−{-# NOINLINE newInvalidatorSwitch #-}
1069−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1070−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1072−{-# NOINLINE newInvalidatorPull #-}
1073−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1074−newInvalidatorPull p = return $! InvalidatorPull p
1076−instance R.FunctorMaybe (Event x) where
1077− fmapMaybe f = push $ return . f
1079−instance Align (Event x) where
1081− align ea eb = R.fmapMaybe R.dmapToThese $ merge $ dynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
1083−newtype Dyn x p a = Dyn { unDyn :: IORef (Either (BehaviorM x a, Event x (p a)) (Hold x p a)) }
1085−newMapDyn :: (a -> b) -> Dynamic x Identity a -> Dynamic x Identity b
1086−newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1088−instance Functor (Dynamic x Identity) where
1091−instance Applicative (Dynamic x Identity) where
1092− pure = dynamicConst
1093− (<*>) = zipDynWith ($)
1097−--TODO: Avoid the duplication between this and R.zipDynWith
1098−zipDynWith :: (a -> b -> c) -> Dynamic x Identity a -> Dynamic x Identity b -> Dynamic x Identity c
1099−zipDynWith f da db =
1100− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1101− ec = flip push eab $ \o -> do
1102− (a, b) <- case o of
1103− This (Identity a) -> do
1104− b <- readBehaviorUntracked $ dynamicCurrent db
1106− That (Identity b) -> do
1107− a <- readBehaviorUntracked $ dynamicCurrent da
1109− These (Identity a) (Identity b) -> return (a, b)
1110− return $ Just $ Identity $ f a b
1111− in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1113−instance Monad (Dynamic x Identity) where
1114− {-# INLINE return #-}
1116− {-# INLINE (>>=) #-}
1117− x >>= f = dynamicDynIdentity $ newJoinDyn $ newMapDyn f x
1118− {-# INLINE (>>) #-}
1120− {-# INLINE fail #-}
1121− fail _ = error "Dynamic does not support 'fail'"
1123−unsafeDyn :: BehaviorM x a -> Event x (p a) -> Dyn x p a
1124−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1125− where x = (readV0, v')
1127−newJoinDyn :: Dynamic x Identity (Dynamic x Identity a) -> Dyn x Identity a
1129− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
1130− eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
1131− eInner = switch $ dynamicUpdated <$> dynamicCurrent d
1132− eBoth = coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
1133− v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
1134− in unsafeDyn readV0 v'
1136−-- ResultM can read behaviors and events
1137−type ResultM = EventM
1139−{-# NOINLINE unsafeNewIORef #-}
1140−unsafeNewIORef :: a -> b -> IORef b
1141−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1143−instance Functor (Event x) where
1144− fmap f = push $ return . Just . f
1146−instance Functor (Behavior x) where
1147− fmap f = pull . fmap f . readBehaviorTracked
1149−{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
1150−push :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1151−push f e = eventPush $ Push
1154− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
1156−-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1158−{-# NOINLINE pull #-}
1159−pull :: BehaviorM x a -> Behavior x a
1160−pull a = behaviorPull $ Pull
1162− , pullValue = unsafeNewIORef a Nothing
1163−#ifdef DEBUG_NODEIDS
1164− , pullNodeId = unsafeNodeId a
1168−{-# NOINLINE switch #-}
1169−switch :: Behavior x (Event x a) -> Event x a
1170−switch a = eventSwitch $ Switch
1172− , switchSubscribed = unsafeNewIORef a Nothing
1175−coincidence :: Event x (Event x a) -> Event x a
1176−coincidence a = eventCoincidence $ Coincidence
1177− { coincidenceParent = a
1178− , coincidenceSubscribed = unsafeNewIORef a Nothing
1181−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1182−run :: [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1183−run roots after = do
1184− tracePropagate $ "Running an event frame with " <> show (length roots) <> " events"
1185− spiderEnv <- SpiderHost ask
1186− result <- SpiderHost $ lift $ withMVar (_spiderEnv_lock spiderEnv) $ \_ -> flip runReaderT spiderEnv $ unSpiderHost $ runFrame $ do
1187− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1188− occBefore <- liftIO $ do
1189− occBefore <- readIORef occRef
1190− writeIORef occRef $! DMap.insert k a occBefore
1192− if DMap.null occBefore
1193− then do scheduleRootClear occRef
1195− else return Nothing
1196− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1197− propagate a subscribersRef
1198− delayedRef <- EventM $ asks eventEnvDelayedMerges
1200− delayed <- liftIO $ readIORef delayedRef
1201− case IntMap.minViewWithKey delayed of
1202− Nothing -> return ()
1203− Just ((currentHeight, cur), future) -> do
1204− tracePropagate $ "Running height " ++ show currentHeight
1205− putCurrentHeight $ Height currentHeight
1206− liftIO $ writeIORef delayedRef $! future
1207− forM_ cur $ \d -> case d of
1208− DelayedMerge subscribed -> do
1209− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
1210− case height `compare` Height currentHeight of
1211− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1212− GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1214− m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
1215− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! DMap.empty
1216− --TODO: Assert that m is not empty
1217− liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
1218− scheduleClear $ mergeSubscribedOccurrence subscribed
1219− propagate m $ mergeSubscribedSubscribers subscribed
1222− putCurrentHeight maxBound
1224− tracePropagate "Done running an event frame"
1227−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1229−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1231−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1233−data DelayedMerge x = forall k. DelayedMerge (MergeSubscribed x k)
1235−debugFinalize :: Bool
1236−debugFinalize = False
1238−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1239−mkWeakPtrWithDebug x debugNote = do
1243− then Just $ putStrLn $ "finalizing: " ++ debugNote
1246−type WeakList a = [Weak a]
1248−{-# INLINE withIncreasedDepth #-}
1250−withIncreasedDepth :: CanTrace x m => m a -> m a
1251−withIncreasedDepth a = do
1252− spiderEnv <- askSpiderEnv
1253− liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) succ
1255− liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) pred
1258−withIncreasedDepth :: m a -> m a
1259−withIncreasedDepth = id
1262−type CanTrace x m = (HasSpiderEnv x m, MonadIO m)
1264−{-# INLINE tracePropagate #-}
1265−tracePropagate :: (CanTrace x m) => String -> m ()
1266−tracePropagate = traceWhen debugPropagate
1268−{-# INLINE traceInvalidate #-}
1269−traceInvalidate :: String -> IO ()
1270−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1272−{-# INLINE traceWhen #-}
1273−traceWhen :: (CanTrace x m) => Bool -> String -> m ()
1274−traceWhen b message = traceMWhen b $ return message
1276−{-# INLINE traceMWhen #-}
1277−traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
1278−traceMWhen b getMessage = when b $ do
1279− message <- getMessage
1281− spiderEnv <- askSpiderEnv
1282− d <- liftIO $ readIORef $ _spiderEnv_depth spiderEnv
1286− liftIO $ putStrLn $ replicate d ' ' <> message
1288−whoCreatedIORef :: IORef a -> IO [String]
1289−whoCreatedIORef (IORef a) = whoCreated $! a
1292−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1295− (x :| xs) : t -> case groupByHead t of
1296− [] -> [(x, xs :| [])]
1298− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1299− | otherwise -> (x, xs :| []) : l
1301−listsToForest :: Eq a => [[a]] -> Forest a
1302−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1305−{-# INLINE propagateSubscriberHold #-}
1306−propagateSubscriberHold :: R.Patch p => Hold x p a -> p a -> EventM x ()
1307−propagateSubscriberHold h a = do
1308− {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1309− invalidators <- liftIO $ readIORef $ holdInvalidators h
1310− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1311− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1312− case {-# SCC "apply" #-} R.apply a v of
1313− Nothing -> return ()
1315− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1316− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1317− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1318− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1320−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x a) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1322−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1323−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1325−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1327− (!m, _) <- BehaviorM ask
1329− Nothing -> return Nothing
1330− Just (!wi, _) -> return $ Just wi
1332−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1334− (!m, _) <- BehaviorM ask
1336− Nothing -> return Nothing
1337− Just (_, !p) -> return $ Just p
1339−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1340−askBehaviorHoldInits = do
1341− (_, !his) <- BehaviorM ask
1344−{-# INLINE getDynHold #-}
1345−getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p a -> m (Hold x p a)
1347− mh <- liftIO $ readIORef $ unDyn d
1349− Right h -> return h
1350− Left (readV0, v') -> do
1351− holdInits <- getDeferralQueue
1352− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1354− liftIO $ writeIORef (unDyn d) $ Right h
1357−-- Always refers to 0
1358−{-# NOINLINE zeroRef #-}
1359−zeroRef :: IORef Height
1360−zeroRef = unsafePerformIO $ newIORef zeroHeight
1362−type CanSubscribe x m =
1364− , HasCurrentHeight x m
1365− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1366− , Defer SomeClear m -- Wiping out event firings
1367− , Defer (SomeAssignment x) m -- Updating state
1368− , Defer (SomeResetCoincidence x) m
1372−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a), RootSubscribed x a, Maybe a)
1373−getRootSubscribed k r sub = do
1374− mSubscribed <- readIORef $ rootSubscribed r
1375− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1376− case DMap.lookup k mSubscribed of
1377− Just subscribed -> {-# SCC "hitRoot" #-} do
1378− sln <- subscribeRootSubscribed subscribed sub
1380− return (sln, subscribed, occ)
1381− Nothing -> {-# SCC "missRoot" #-} do
1382− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1383− let !cached = rootSubscribed r
1384− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1385− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1386− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1387− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1388− writeIORef uninitRef $! uninit
1389− let subscribed = RootSubscribed
1390− { rootSubscribedKey = k
1391− , rootSubscribedCachedSubscribed = cached
1392− , rootSubscribedOccurrence = getOcc
1393− , rootSubscribedSubscribers = subs
1394− , rootSubscribedUninit = uninit
1395− , rootSubscribedWeakSelf = weakSelf
1396−#ifdef DEBUG_NODEIDS
1397− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1400− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1401− 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
1403− return (sln, subscribed, occ)
1405−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1406−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1407−cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1408− rootSubscribedUninit self
1409− modifyIORef' cached $ DMap.delete k
1411−{-# INLINE subscribeRootSubscribed #-}
1412−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1413−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1415−-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
1416−{-# SPECIALIZE getPushSubscribed :: Push x a b -> Subscriber x b -> EventM x (WeakBagTicket (Subscriber x b), PushSubscribed x a b, Maybe b) #-}
1417−getPushSubscribed :: CanSubscribe x m => Push x a b -> Subscriber x b -> m (WeakBagTicket (Subscriber x b), PushSubscribed x a b, Maybe b)
1418−getPushSubscribed p sub = do
1419− mSubscribed <- liftIO $ readIORef $ pushSubscribed p
1420− case mSubscribed of
1421− Just subscribed -> {-# SCC "hitPush" #-} liftIO $ do
1422− sln <- subscribePushSubscribed subscribed sub
1423− occ <- readIORef $ pushSubscribedOccurrence subscribed
1424− return (sln, subscribed, occ)
1425− Nothing -> {-# SCC "missPush" #-} do -- Not yet subscribed
1426− subscribedRef <- liftIO $ newIORef $ error "getPushSubscribed: subscribed not yet intialized"
1427− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1428− s <- liftIO $ newSubscriberPush (pushCompute p) subscribedUnsafe
1429− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead (pushParent p) s
1430− occ <- runComputeM $ join <$> mapM (pushCompute p) parentOcc
1431− occRef <- liftIO $ newIORef occ
1432− when (isJust occ) $ scheduleClear occRef
1433− weakSelf <- liftIO $ newIORef $ error "getPushSubscribed: weakSelf not initialized"
1434− let !cached = pushSubscribed p
1435− (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupPushSubscribed
1436− let subscribed = PushSubscribed
1437− { pushSubscribedCachedSubscribed = cached
1438− , pushSubscribedOccurrence = occRef
1439− , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
1440− , pushSubscribedSubscribers = subs
1441− , pushSubscribedSelf = s
1442− , pushSubscribedWeakSelf = weakSelf
1443− , pushSubscribedParent = subscription
1444−#ifdef DEBUG_NODEIDS
1445− , pushSubscribedNodeId = unsafeNodeId p
1448− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
1449− liftIO $ writeIORef subscribedRef $! subscribed
1450− liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
1451− return (sln, subscribed, occ)
1453−cleanupPushSubscribed :: PushSubscribed x a b -> IO ()
1454−cleanupPushSubscribed self = do
1455− unsubscribe $ pushSubscribedParent self
1456− writeIORef (pushSubscribedCachedSubscribed self) $ Nothing
1458−{-# INLINE subscribePushSubscribed #-}
1459−subscribePushSubscribed :: PushSubscribed x a b -> Subscriber x b -> IO (WeakBagTicket (Subscriber x b))
1460−subscribePushSubscribed subscribed sub = WeakBag.insert sub (pushSubscribedSubscribers subscribed) (pushSubscribedWeakSelf subscribed) cleanupPushSubscribed
1462−{-# SPECIALIZE getMergeSubscribed :: GCompare k => Merge x k -> Subscriber x (DMap k Identity) -> EventM x (WeakBagTicket (Subscriber x (DMap k Identity)), MergeSubscribed x k, Maybe (DMap k Identity)) #-}
1463−getMergeSubscribed :: forall x k m. (CanSubscribe x m, GCompare k) => Merge x k -> Subscriber x (DMap k Identity) -> m (WeakBagTicket (Subscriber x (DMap k Identity)), MergeSubscribed x k, Maybe (DMap k Identity))
1464−getMergeSubscribed m sub = do
1465− mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
1466− case mSubscribed of
1467− Just subscribed -> {-# SCC "hitMerge" #-} liftIO $ do
1468− sln <- subscribeMergeSubscribed subscribed sub
1469− occ <- readIORef $ mergeSubscribedOccurrence subscribed
1470− return (sln, subscribed, occ)
1471− Nothing -> {-# SCC "missMerge" #-} do
1472− subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
1473− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1474− initialParents <- readBehaviorUntracked $ dynamicCurrent $ mergeParents m
1475− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x k))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1476− s <- liftIO $ newSubscriberMerge k subscribedUnsafe
1477− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1478− height <- liftIO $ getEventSubscribedHeight parentSubd
1479− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription s)
1480− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1481− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1482− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1483− myHeight = if invalidHeight `elem` heights
1485− else succHeight $ heightBagMax myHeightBag
1486− currentHeight <- getCurrentHeight
1487− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1488− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1490− unless (DMap.null accum) $ do
1491− scheduleMerge myHeight subscribedUnsafe
1492− occRef <- liftIO $ newIORef occ
1493− when (isJust occ) $ scheduleClear occRef
1494− accumRef <- liftIO $ newIORef accum
1495− heightRef <- liftIO $ newIORef myHeight
1496− heightMapRef <- liftIO $ newIORef myHeightBag
1497− weakSelf <- liftIO $ newIORef $ error "getMergeSubscribed: weakSelf not yet initialized"
1498− (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupMergeSubscribed
1499− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1500− parentsRef <- liftIO $ newIORef $ DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1501− let !subscribed = MergeSubscribed
1502− { mergeSubscribedCachedSubscribed = mergeSubscribed m
1503− , mergeSubscribedOccurrence = occRef
1504− , mergeSubscribedAccum = accumRef
1505− , mergeSubscribedHeight = heightRef
1506− , mergeSubscribedHeightBag = heightMapRef
1507− , mergeSubscribedSubscribers = subs
1508− , mergeSubscribedChange = changeSubdRef
1509− , mergeSubscribedParents = parentsRef
1510− , mergeSubscribedWeakSelf = weakSelf
1511−#ifdef DEBUG_NODEIDS
1512− , mergeSubscribedNodeId = unsafeNodeId m
1515− defer $ SomeMergeInit subscribed $ dynamicUpdated $ mergeParents m
1516− liftIO $ writeIORef subscribedRef $! subscribed
1517− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "MergeSubscribed"
1518− liftIO $ writeIORef (mergeSubscribed m) $ Just subscribed
1519− return (sln, subscribed, occ)
1521−cleanupMergeSubscribed :: MergeSubscribed x k -> IO ()
1522−cleanupMergeSubscribed subscribed = do
1523− parents <- readIORef $ mergeSubscribedParents subscribed
1524− forM_ (DMap.toList parents) $ \(_ :=> msp) -> unsubscribe $ mergeSubscribedParentSubscription msp
1525− -- Not necessary, because this whole MergeSubscribed is dead: writeIORef (mergeSubscribedParents subscribed) DMap.empty
1526− writeIORef (mergeSubscribedCachedSubscribed subscribed) $ Nothing -- Get rid of the cached subscribed
1528−{-# INLINE subscribeMergeSubscribed #-}
1529−subscribeMergeSubscribed :: MergeSubscribed x k -> Subscriber x (DMap k Identity) -> IO (WeakBagTicket (Subscriber x (DMap k Identity)))
1530−subscribeMergeSubscribed subscribed sub = WeakBag.insert sub (mergeSubscribedSubscribers subscribed) (mergeSubscribedWeakSelf subscribed) cleanupMergeSubscribed
1532−{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), FanSubscribed x k, Maybe a) #-}
1533−getFanSubscribed :: (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderEnv x m, m ~ EventM x, GCompare k) => k a -> Fan x k -> Subscriber x a -> m (WeakBagTicket (Subscriber x a), FanSubscribed x k, Maybe a)
1534−getFanSubscribed k f sub = do
1535− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1536− case mSubscribed of
1537− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1538− sln <- subscribeFanSubscribed k subscribed sub
1539− occ <- readIORef $ fanSubscribedOccurrence subscribed
1540− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1541− Nothing -> {-# SCC "missFan" #-} do
1542− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1543− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1544− s <- liftIO $ newSubscriberFan subscribedUnsafe
1545− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1546− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1547− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1548− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1549− occRef <- liftIO $ newIORef parentOcc
1550− when (isJust parentOcc) $ scheduleClear occRef
1551− let subscribed = FanSubscribed
1552− { fanSubscribedCachedSubscribed = fanSubscribed f
1553− , fanSubscribedOccurrence = occRef
1554− , fanSubscribedParent = subscription
1555− , fanSubscribedSubscribers = subscribersRef
1556−#ifdef DEBUG_NODEIDS
1557− , fanSubscribedNodeId = unsafeNodeId f
1560− let !self = (k, subscribed)
1561− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1562− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1563− liftIO $ writeIORef subscribedRef $! subscribed
1564− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1565− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1567−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1568−cleanupFanSubscribed (k, subscribed) = do
1569− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1570− let reducedSubscribers = DMap.delete k subscribers
1571− if DMap.null reducedSubscribers
1573− unsubscribe $ fanSubscribedParent subscribed
1574− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1575− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1576− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1578−{-# INLINE subscribeFanSubscribed #-}
1579−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1580−subscribeFanSubscribed k subscribed sub = do
1581− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1582− case DMap.lookup k subscribers of
1583− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1584− let !self = (k, subscribed)
1585− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1586− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1587− 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
1589− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1591−{-# SPECIALIZE getSwitchSubscribed :: Switch x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), SwitchSubscribed x a, Maybe a) #-}
1592−getSwitchSubscribed :: (Defer (SomeHoldInit x) m, Defer (SomeAssignment x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, Defer (SomeResetCoincidence x) m, HasCurrentHeight x m, HasSpiderEnv x m, m ~ EventM x) => Switch x a -> Subscriber x a -> m (WeakBagTicket (Subscriber x a), SwitchSubscribed x a, Maybe a)
1593−getSwitchSubscribed s sub = do
1594− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1595− case mSubscribed of
1596− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1597− sln <- subscribeSwitchSubscribed subscribed sub
1598− occ <- readIORef $ switchSubscribedOccurrence subscribed
1599− return (sln, subscribed, occ)
1600− Nothing -> {-# SCC "missSwitch" #-} do
1601− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1602− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1603− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1604− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1605− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1606− wiRef <- liftIO $ newIORef wi
1607− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1608− holdInits <- getDeferralQueue
1609− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1610− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1611− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1612− subscriptionRef <- liftIO $ newIORef subscription
1613− occRef <- liftIO $ newIORef parentOcc
1614− when (isJust parentOcc) $ scheduleClear occRef
1615− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1616− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1617− let !subscribed = SwitchSubscribed
1618− { switchSubscribedCachedSubscribed = switchSubscribed s
1619− , switchSubscribedOccurrence = occRef
1620− , switchSubscribedHeight = heightRef
1621− , switchSubscribedSubscribers = subs
1622− , switchSubscribedOwnInvalidator = i
1623− , switchSubscribedOwnWeakInvalidator = wiRef
1624− , switchSubscribedBehaviorParents = parentsRef
1625− , switchSubscribedParent = switchParent s
1626− , switchSubscribedCurrentParent = subscriptionRef
1627− , switchSubscribedWeakSelf = weakSelf
1628−#ifdef DEBUG_NODEIDS
1629− , switchSubscribedNodeId = unsafeNodeId s
1632− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1633− liftIO $ writeIORef subscribedRef $! subscribed
1634− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1635− return (slnForSub, subscribed, parentOcc)
1637−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1638−cleanupSwitchSubscribed subscribed = do
1639− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1640− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1641− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1643−{-# INLINE subscribeSwitchSubscribed #-}
1644−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1645−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1647−{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), CoincidenceSubscribed x a, Maybe a) #-}
1648−getCoincidenceSubscribed :: forall x a m. (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderEnv x m, m ~ EventM x) => Coincidence x a -> Subscriber x a -> m (WeakBagTicket (Subscriber x a), CoincidenceSubscribed x a, Maybe a)
1649−getCoincidenceSubscribed c sub = do
1650− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1651− case mSubscribed of
1652− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1653− sln <- subscribeCoincidenceSubscribed subscribed sub
1654− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1655− return (sln, subscribed, occ)
1656− Nothing -> {-# SCC "missCoincidence" #-} do
1657− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1658− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1659− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1660− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1661− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1662− (occ, height, mInnerSubd) <- case outerOcc of
1663− Nothing -> return (Nothing, outerHeight, Nothing)
1665− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1666− return (occ, height, Just innerSubd)
1667− occRef <- liftIO $ newIORef occ
1668− when (isJust occ) $ scheduleClear occRef
1669− heightRef <- liftIO $ newIORef height
1670− innerSubdRef <- liftIO $ newIORef mInnerSubd
1671− scheduleClear innerSubdRef
1672− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1673− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1674− let subscribed = CoincidenceSubscribed
1675− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1676− , coincidenceSubscribedOccurrence = occRef
1677− , coincidenceSubscribedHeight = heightRef
1678− , coincidenceSubscribedSubscribers = subs
1679− , coincidenceSubscribedOuter = subOuter
1680− , coincidenceSubscribedOuterParent = outerSubscription
1681− , coincidenceSubscribedInnerParent = innerSubdRef
1682− , coincidenceSubscribedWeakSelf = weakSelf
1683−#ifdef DEBUG_NODEIDS
1684− , coincidenceSubscribedNodeId = unsafeNodeId c
1687− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1688− liftIO $ writeIORef subscribedRef $! subscribed
1689− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1690− return (slnForSub, subscribed, occ)
1692−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1693−cleanupCoincidenceSubscribed subscribed = do
1694− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1695− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1697−{-# INLINE subscribeCoincidenceSubscribed #-}
1698−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1699−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1701−{-# INLINE merge #-}
1702−merge :: GCompare k => Dynamic x R.PatchDMap (DMap k (Event x)) -> Event x (DMap k Identity)
1703−merge m = eventMerge $ Merge
1705− , mergeSubscribed = unsafeNewIORef m Nothing
1708−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1710−fan :: GCompare k => Event x (DMap k Identity) -> EventSelector x k
1714− , fanSubscribed = unsafeNewIORef e Nothing
1716− in EventSelector $ \k -> eventFan k f
1718−runHoldInits :: IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1719−runHoldInits holdInitRef mergeInitRef = do
1720− holdInits <- liftIO $ readIORef holdInitRef
1721− mergeInits <- liftIO $ readIORef mergeInitRef
1722− unless (null holdInits && null mergeInits) $ do
1723− liftIO $ writeIORef holdInitRef []
1724− liftIO $ writeIORef mergeInitRef []
1725− mapM_ initHold holdInits
1726− mapM_ initMerge mergeInits
1727− runHoldInits holdInitRef mergeInitRef
1729−initHold :: SomeHoldInit x -> EventM x ()
1730−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1732−initMerge :: SomeMergeInit x -> EventM x ()
1733−initMerge (SomeMergeInit subscribed changed) = do
1734− changeSub <- liftIO $ newSubscriberMergeChange subscribed
1735− (EventSubscription _ changeSubd, change) <- subscribeAndRead changed changeSub
1736− forM_ change $ \c -> defer $ SomeMergeUpdate c subscribed
1737− liftIO $ writeIORef (mergeSubscribedChange subscribed) (changeSub, changeSubd)
1739−-- | Run an event action outside of a frame
1740−runFrame :: forall x a. EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1741−runFrame a = SpiderHost $ ask >>= \spiderEnv -> lift $ do
1742− -- Clear out pending unsubscriptions; these will need to happen eventually anyway, and might cause us a lot of extra work during the frame, so get rid of them now
1743− pendingCleanups <- atomicModifyIORef (_spiderEnv_cleanups spiderEnv) $ \x -> ([], x)
1744− {-# SCC "cleanups" #-} sequence_ pendingCleanups
1745− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1746− holdInitRef <- newIORef []
1747− mergeUpdateRef <- newIORef []
1748− mergeInitRef <- newIORef []
1749− heightRef <- newIORef zeroHeight
1750− toClearRef <- newIORef []
1751− toClearRootRef <- newIORef []
1752− coincidenceInfosRef <- newIORef []
1753− delayedRef <- liftIO $ newIORef IntMap.empty
1754− let env = EventEnv spiderEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1757− runHoldInits holdInitRef mergeInitRef -- This must happen before doing the assignments, in case subscribing a Hold causes existing Holds to be read by the newly-propagated events
1759− result <- runEventM go env
1760− toClear <- readIORef toClearRef
1761− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1762− toClearRoot <- readIORef toClearRootRef
1763− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1764− toAssign <- readIORef toAssignRef
1765− toReconnectRef <- newIORef []
1766− coincidenceInfos <- readIORef coincidenceInfosRef
1767− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1769− when debugInvalidate $ putStrLn $ "Invalidating Hold"
1770− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1771− mergeUpdates <- readIORef mergeUpdateRef
1772− writeIORef mergeUpdateRef []
1773− let updateMerge :: SomeMergeUpdate x -> IO [SomeEventSubscription x]
1774− updateMerge (SomeMergeUpdate (R.PatchDMap p :: R.PatchDMap (DMap k (Event x))) m) = do
1775− oldParents <- readIORef $ mergeSubscribedParents m
1776− let f (subscriptionsToKill, ps) (k :=> Compose me) = do
1777− (mOldSubd, newPs) <- case me of
1778− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1780− s <- liftIO $ newSubscriberMerge k m
1781− subscription@(EventSubscription _ subd) <- subscribe e s
1782− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1783− let newParent = MergeSubscribedParent subscription s
1784− liftIO $ addMergeHeight newParentHeight m
1785− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1786− forM_ mOldSubd $ \oldSubd -> do
1787− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription oldSubd
1788− liftIO $ removeMergeHeight oldHeight m
1789− return (maybeToList (SomeEventSubscription . mergeSubscribedParentSubscription <$> mOldSubd) ++ subscriptionsToKill, newPs)
1790− (subscriptionsToKill, newParents) <- flip runEventM env $ foldM f ([], oldParents) $ DMap.toList p --TODO: I think this runEventM is OK, since no events are firing at this time, but it might not be
1791− writeIORef (mergeSubscribedParents m) $! newParents
1792− return subscriptionsToKill
1793− when debugPropagate $ putStrLn "Updating merges"
1794− mergeSubscriptionsToKill <- concat <$> mapM updateMerge mergeUpdates
1795− when debugPropagate $ putStrLn "Updating merges done"
1796− toReconnect <- readIORef toReconnectRef
1797− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1798− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1799− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1800− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1802− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1803− wi' <- mkWeakPtrWithDebug i "wi'"
1804− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1805− writeIORef (switchSubscribedBehaviorParents subscribed) []
1806− writeIORef holdInitRef [] --TODO: Should we reuse this?
1807− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) holdInitRef
1808− runEventM (runHoldInits holdInitRef mergeInitRef) 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
1809− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1810− sub <- newSubscriberSwitch subscribed
1811− subscription <- runReaderT (unSpiderHost (runFrame ({-# SCC "subscribeSwitch" #-} subscribe e sub))) spiderEnv --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
1813− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1814− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1815− EventRoot _ -> "EventRoot"
1816− EventNever -> "EventNever"
1817− _ -> "something else"
1819− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1820− return $ SomeEventSubscription oldSubscription
1821− forM_ mergeSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1822− forM_ switchSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1823− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1824− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1825− parentHeight <- getEventSubscribedHeight subd'
1826− myHeight <- readIORef $ switchSubscribedHeight subscribed
1827− when (parentHeight /= myHeight) $ do
1828− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1829− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1830− forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> do
1831− invalidateMergeHeight m --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
1832− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1833− unsubscribe subscription
1834− mapM_ invalidateCoincidenceHeight mcs
1835− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1836− forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> revalidateMergeHeight m
1837− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1838− height <- calculateSwitchHeight subscribed
1839− updateSwitchHeight height subscribed
1842−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1844−{-# INLINE zeroHeight #-}
1845−zeroHeight :: Height
1846−zeroHeight = Height 0
1848−{-# INLINE invalidHeight #-}
1849−invalidHeight :: Height
1850−invalidHeight = Height (-1000)
1853−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1854−{-# INLINE invalidHeightBeingTraversed #-}
1855−invalidHeightBeingTraversed :: Height
1856−invalidHeightBeingTraversed = Height (-1001)
1859−{-# INLINE succHeight #-}
1860−succHeight :: Height -> Height
1861−succHeight h@(Height a) =
1862− if h == invalidHeight
1864− else Height $ succ a
1866−removeMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1867−removeMergeHeight oldParentHeight subscribed = do
1868− when debugInvalidateHeight $ putStrLn $ "removeMergeHeight: " <> show oldParentHeight <> " Merge" <> showNodeId subscribed
1869− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1870− let newHeights = heightBagRemove oldParentHeight oldHeights
1871− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1873−invalidateMergeHeight :: MergeSubscribed x k -> IO ()
1874−invalidateMergeHeight subscribed = do
1875− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1876− -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1877− when (oldHeight /= invalidHeight) $ do
1878− writeIORef (mergeSubscribedHeight subscribed) $! invalidHeight
1879− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1881−addMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1882−addMergeHeight newParentHeight subscribed = do
1883− when debugInvalidateHeight $ putStrLn $ "addMergeHeight: " <> show newParentHeight <> " Merge" <> showNodeId subscribed
1884− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1885− let newHeights = heightBagAdd newParentHeight oldHeights
1886− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1888−revalidateMergeHeight :: MergeSubscribed x k -> IO ()
1889−revalidateMergeHeight subscribed = do
1890− currentHeight <- readIORef $ mergeSubscribedHeight subscribed
1891− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1892− heights <- readIORef $ mergeSubscribedHeightBag subscribed
1893− parents <- readIORef $ mergeSubscribedParents subscribed
1894− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1895− case heightBagSize heights `compare` DMap.size parents of
1898− let height = succHeight $ heightBagMax heights
1899− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1900− writeIORef (mergeSubscribedHeight subscribed) $! height
1901− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1902− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge" <> showNodeId subscribed
1904−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1905−invalidateCoincidenceHeight subscribed = do
1906− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1907− when (oldHeight /= invalidHeight) $ do
1908− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1909− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1911−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1912−updateSwitchHeight new subscribed = do
1913− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1914− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1915− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1916− writeIORef (switchSubscribedHeight subscribed) $! new
1917− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1919−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1920−recalculateCoincidenceHeight subscribed = do
1921− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1922− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1923− height <- calculateCoincidenceHeight subscribed
1924− when (height /= invalidHeight) $ do
1925− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1926− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1928−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1929−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1931−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1932−calculateCoincidenceHeight subscribed = do
1933− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1934− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1935− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1937−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1939−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1940−invalidate toReconnectRef wis = do
1941− forM_ wis $ \wi -> do
1945− traceInvalidate "invalidate Dead"
1946− return () --TODO: Should we clean this up here?
1948− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1950− InvalidatorPull p -> do
1951− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1952− mVal <- readIORef $ pullValue p
1953− forM_ mVal $ \val -> do
1954− writeIORef (pullValue p) Nothing
1955− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1956− InvalidatorSwitch subscribed -> do
1957− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1958− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1959− return [] -- Since we always finalize everything, always return an empty list --TODO: There are some things that will need to be re-subscribed every time; we should try to avoid finalizing them
1961−--------------------------------------------------------------------------------
1962−-- Reflex integration
1963−--------------------------------------------------------------------------------
1965−-- | The default, global Spider environment
1966−type Spider = SpiderEnv Global
1968−-- | Designates the default, global Spider timeline
1971−{-# NOINLINE globalSpiderEnv #-}
1972−globalSpiderEnv :: SpiderEnv Global
1973−globalSpiderEnv = unsafePerformIO unsafeNewSpiderEnv
1975−-- | Stores all global data relevant to a particular Spider timeline; only one
1976−-- value should exist for each type @x@
1977−data SpiderEnv x = SpiderEnv
1978− { _spiderEnv_toUnsubscribe :: !(IORef [SomeEventSubscription x])
1979− , _spiderEnv_lock :: !(MVar ())
1980− , _spiderEnv_cleanups :: !(IORef [IO ()])
1982− , _spiderEnv_depth :: !(IORef Int)
1985−type role SpiderEnv nominal
1987−instance GEq SpiderEnv where
1988− a `geq` b = if _spiderEnv_lock a == _spiderEnv_lock b
1989− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderEnv can't have two different 'x' arguments
1992−unsafeNewSpiderEnv :: forall x. IO (SpiderEnv x)
1993−unsafeNewSpiderEnv = do
1994− toUnsubscribe <- newIORef []
1996− cleanups <- newIORef []
1998− depthRef <- newIORef 0
2001− { _spiderEnv_toUnsubscribe = toUnsubscribe
2002− , _spiderEnv_lock = lock
2003− , _spiderEnv_cleanups = cleanups
2005− , _spiderEnv_depth = depthRef
2009−-- | Create a new SpiderEnv
2010−newSpiderEnv :: IO (Some SpiderEnv)
2011−newSpiderEnv = Some.This <$> unsafeNewSpiderEnv
2013−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2015−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2017−instance R.Reflex (SpiderEnv x) where
2018− newtype Behavior (SpiderEnv x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2019− newtype Event (SpiderEnv x) a = SpiderEvent { unSpiderEvent :: Event x a }
2020− newtype Dynamic (SpiderEnv x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x Identity a } deriving (Functor, Applicative, Monad)
2021− newtype Incremental (SpiderEnv x) p a = SpiderIncremental { unSpiderIncremental :: Dynamic x p a }
2022− type PullM (SpiderEnv x) = SpiderPullM x
2023− type PushM (SpiderEnv x) = SpiderPushM x
2024− {-# INLINABLE never #-}
2025− never = SpiderEvent eventNever
2026− {-# INLINABLE constant #-}
2027− constant = SpiderBehavior . behaviorConst
2028− {-# INLINABLE push #-}
2029− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2030− {-# INLINABLE pull #-}
2031− pull = SpiderBehavior . pull . coerce
2032− {-# INLINABLE merge #-}
2033− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderEnv x)) -> DMap k (Event x))
2034− {-# INLINABLE fan #-}
2035− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2036− {-# INLINABLE switch #-}
2037− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderEnv x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2038− {-# INLINABLE coincidence #-}
2039− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderEnv x) a) -> Event x (Event x a)) . unSpiderEvent
2040− {-# INLINABLE current #-}
2041− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2042− {-# INLINABLE updated #-}
2043− updated = SpiderEvent . fmap runIdentity . dynamicUpdated . unSpiderDynamic
2044− {-# INLINABLE unsafeBuildDynamic #-}
2045− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
2046− {-# INLINABLE unsafeBuildIncremental #-}
2047− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2048− {-# INLINABLE mergeIncremental #-}
2049− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x R.PatchDMap (DMap k (R.Event (SpiderEnv x))) -> Dynamic x R.PatchDMap (DMap k (Event x))) . unSpiderIncremental
2050− {-# INLINABLE currentIncremental #-}
2051− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2052− {-# INLINABLE updatedIncremental #-}
2053− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2054− {-# INLINABLE incrementalToDynamic #-}
2055− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2056− c <- readBehaviorUntracked $ dynamicCurrent i
2057− return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
2059−instance R.MonadSample (SpiderEnv x) (EventM x) where
2060− {-# INLINABLE sample #-}
2061− sample (SpiderBehavior b) = readBehaviorUntracked b
2063−instance R.MonadHold (SpiderEnv x) (EventM x) where
2064− {-# INLINABLE hold #-}
2065− hold = holdSpiderEventM
2066− {-# INLINABLE holdDyn #-}
2067− holdDyn = holdDynSpiderEventM
2068− {-# INLINABLE holdIncremental #-}
2069− holdIncremental = holdIncrementalSpiderEventM
2071−holdSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Behavior (SpiderEnv x) a)
2072−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2074−holdDynSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Dynamic (SpiderEnv x) a)
2075−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2077−holdIncrementalSpiderEventM :: R.Patch p => a -> R.Event (SpiderEnv x) (p a) -> EventM x (R.Incremental (SpiderEnv x) p a)
2078−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2080−instance R.MonadHold (SpiderEnv x) (SpiderHost x) where
2081− {-# INLINABLE hold #-}
2082− hold v0 e = R.runHostFrame $ R.hold v0 e
2083− {-# INLINABLE holdDyn #-}
2084− holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
2085− {-# INLINABLE holdIncremental #-}
2086− holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
2088−instance R.MonadSample (SpiderEnv x) (SpiderHost x) where
2089− {-# INLINABLE sample #-}
2090− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2092−instance R.MonadSample (SpiderEnv x) (SpiderPullM x) where
2093− {-# INLINABLE sample #-}
2094− sample = coerce . readBehaviorTracked . unSpiderBehavior
2096−instance R.MonadSample (SpiderEnv x) (SpiderPushM x) where
2097− {-# INLINABLE sample #-}
2098− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2100−instance R.MonadHold (SpiderEnv x) (SpiderPushM x) where
2101− {-# INLINABLE hold #-}
2102− hold v0 e = R.current <$> R.holdDyn v0 e
2103− {-# INLINABLE holdDyn #-}
2104− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce e
2105− {-# INLINABLE holdIncremental #-}
2106− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> hold v0 e
2108−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2110−data SpiderEventHandle x a = SpiderEventHandle
2111− { spiderEventHandleSubscription :: EventSubscription x a
2112− , spiderEventHandleValue :: IORef (Maybe a)
2115−instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHostFrame x) where
2116− {-# INLINABLE subscribeEvent #-}
2117− subscribeEvent e = SpiderHostFrame $ do
2118− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2119− val <- liftIO $ newIORef Nothing
2120− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2121− { subscriberPropagate = \a -> do
2122− liftIO $ writeIORef val $ Just a
2124− , subscriberInvalidateHeight = \_ -> return ()
2125− , subscriberRecalculateHeight = \_ -> return ()
2127− return $ SpiderEventHandle
2128− { spiderEventHandleSubscription = subscription
2129− , spiderEventHandleValue = val
2132−instance R.ReflexHost (SpiderEnv x) where
2133− type EventTrigger (SpiderEnv x) = RootTrigger x
2134− type EventHandle (SpiderEnv x) = SpiderEventHandle x
2135− type HostFrame (SpiderEnv x) = SpiderHostFrame x
2137−instance R.MonadReadEvent (SpiderEnv x) (ReadPhase x) where
2138− {-# NOINLINE readEvent #-}
2139− readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2140− result <- readIORef $ spiderEventHandleValue h
2144−instance MonadRef (EventM x) where
2145− type Ref (EventM x) = Ref IO
2146− {-# INLINABLE newRef #-}
2147− {-# INLINABLE readRef #-}
2148− {-# INLINABLE writeRef #-}
2149− newRef = liftIO . newRef
2150− readRef = liftIO . readRef
2151− writeRef r a = liftIO $ writeRef r a
2153−instance MonadAtomicRef (EventM x) where
2154− {-# INLINABLE atomicModifyRef #-}
2155− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2157−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2158−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2160−instance Monad (SpiderHost x) where
2161− {-# INLINABLE (>>=) #-}
2162− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2163− {-# INLINABLE (>>) #-}
2164− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2165− {-# INLINABLE return #-}
2166− return x = SpiderHost $ return x
2167− {-# INLINABLE fail #-}
2168− fail s = SpiderHost $ fail s
2170−-- | Run an action affecting the global Spider timeline; this will be guarded by
2171−-- a mutex for that timeline
2172−runSpiderHost :: SpiderHost Global a -> IO a
2173−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderEnv
2175−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2177−instance Monad (SpiderHostFrame x) where
2178− {-# INLINABLE (>>=) #-}
2179− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2180− {-# INLINABLE (>>) #-}
2181− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2182− {-# INLINABLE return #-}
2183− return x = SpiderHostFrame $ return x
2184− {-# INLINABLE fail #-}
2185− fail s = SpiderHostFrame $ fail s
2187−instance R.MonadSample (SpiderEnv x) (SpiderHostFrame x) where
2188− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2190−instance R.MonadHold (SpiderEnv x) (SpiderHostFrame x) where
2191− {-# INLINABLE hold #-}
2192− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2193− {-# INLINABLE holdDyn #-}
2194− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2195− {-# INLINABLE holdIncremental #-}
2196− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2198−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2199−newEventWithTriggerIO f = do
2200− es <- newFanEventWithTriggerIO $ \Refl -> f
2201− return $ select es Refl
2203−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2204−newFanEventWithTriggerIO f = do
2205− occRef <- newIORef DMap.empty
2206− subscribedRef <- newIORef DMap.empty
2208− { rootOccurrence = occRef
2209− , rootSubscribed = subscribedRef
2212− return $ EventSelector $ \k -> eventRoot k r
2214−instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHost x) where
2215− newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2216− newFanEventWithTrigger f = SpiderHost $ lift $ do
2217− es <- newFanEventWithTriggerIO f
2218− return $ R.EventSelector $ SpiderEvent . select es
2220−instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHostFrame x) where
2221− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2222− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2223− es <- newFanEventWithTriggerIO f
2224− return $ R.EventSelector $ SpiderEvent . select es
2226−instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHost x) where
2227− {-# INLINABLE subscribeEvent #-}
2228− subscribeEvent = runFrame . runSpiderHostFrame . R.subscribeEvent
2230−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2232−instance R.MonadSample (SpiderEnv x) (ReadPhase x) where
2233− {-# INLINABLE sample #-}
2234− sample = ReadPhase . R.sample
2236−instance R.MonadHold (SpiderEnv x) (ReadPhase x) where
2237− {-# INLINABLE hold #-}
2238− hold v0 e = ReadPhase $ R.hold v0 e
2239− {-# INLINABLE holdDyn #-}
2240− holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2241− {-# INLINABLE holdIncremental #-}
2242− holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2244−instance R.MonadReflexHost (SpiderEnv x) (SpiderHost x) where
2245− type ReadPhase (SpiderHost x) = ReadPhase x
2246− fireEventsAndRead es (ReadPhase a) = run es a
2247− runHostFrame = runFrame . runSpiderHostFrame
2249−instance MonadRef (SpiderHost x) where
2250− type Ref (SpiderHost x) = Ref IO
2251− newRef = SpiderHost . newRef
2252− readRef = SpiderHost . readRef
2253− writeRef r = SpiderHost . writeRef r
2255−instance MonadAtomicRef (SpiderHost x) where
2256− atomicModifyRef r = SpiderHost . atomicModifyRef r
2258−instance MonadRef (SpiderHostFrame x) where
2259− type Ref (SpiderHostFrame x) = Ref IO
2260− newRef = SpiderHostFrame . newRef
2261− readRef = SpiderHostFrame . readRef
2262− writeRef r = SpiderHostFrame . writeRef r
2264−instance MonadAtomicRef (SpiderHostFrame x) where
2265− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r