@@ -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
33−import Control.Applicative
34−import Control.Concurrent
35−import Control.Exception
36−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
37−import Control.Monad.Exception
38−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
39−import Control.Monad.Primitive
40−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
41−import Control.Monad.Ref
42−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
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')
57−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
58−import qualified Data.List.NonEmpty as NonEmpty
60−import Data.Monoid (mempty, (<>))
61−import Data.Some (Some)
62−import qualified Data.Some as Some
64−import Data.Traversable
65−import Data.Tree (Forest, Tree (..), drawForest)
67−import GHC.IORef (IORef (..))
69−import System.IO.Unsafe
70−import System.Mem.Weak
73−import Data.WeakBag (WeakBag, WeakBagTicket)
74−import qualified Data.WeakBag as WeakBag
75−import qualified Reflex.Class as R
76−import qualified Reflex.Host.Class as R
78−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
79−import Prelude hiding (any, concat, mapM, mapM_, sequence)
81−debugPropagate :: Bool
83−debugInvalidateHeight :: Bool
85−debugInvalidate :: Bool
93−debugInvalidateHeight = False
95−debugInvalidate = True
97−class HasNodeId a where
98− getNodeId :: a -> Int
100−instance HasNodeId (Hold x p a) where
101− getNodeId = holdNodeId
103−instance HasNodeId (PushSubscribed x a b) where
104− getNodeId = pushSubscribedNodeId
106−instance HasNodeId (SwitchSubscribed x a) where
107− getNodeId = switchSubscribedNodeId
109−instance HasNodeId (MergeSubscribed x a) where
110− getNodeId = mergeSubscribedNodeId
112−instance HasNodeId (FanSubscribed x a) where
113− getNodeId = fanSubscribedNodeId
115−instance HasNodeId (CoincidenceSubscribed x a) where
116− getNodeId = coincidenceSubscribedNodeId
118−instance HasNodeId (RootSubscribed x a) where
119− getNodeId = rootSubscribedNodeId
121−instance HasNodeId (Pull x a) where
122− getNodeId = pullNodeId
124−{-# INLINE showNodeId #-}
125−showNodeId :: HasNodeId a => a -> String
126−showNodeId = ("#"<>) . show . getNodeId
128−showSubscriberType :: Subscriber x a -> String
129−showSubscriberType = \case
130− SubscriberPush _ _ -> "SubscriberPush"
131− SubscriberMerge _ _ -> "SubscriberMerge"
132− SubscriberFan _ -> "SubscriberFan"
133− SubscriberMergeChange _ -> "SubscriberMergeChange"
134− SubscriberHold _ -> "SubscriberHold"
135− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
136− SubscriberSwitch _ -> "SubscriberSwitch"
137− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
138− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
139− SubscriberHandle -> "SubscriberHandle"
141−showEventType :: Event x a -> String
142−showEventType = \case
143− EventRoot _ _ -> "EventRoot"
144− EventNever -> "EventNever"
145− EventPush _ -> "EventPush"
146− EventMerge _ -> "EventMerge"
147− EventFan _ _ -> "EventFan"
148− EventSwitch _ -> "EventSwitch"
149− EventCoincidence _ -> "EventCoincidence"
150− EventHold _ -> "EventHold"
151− EventDyn _ -> "EventDyn"
152− EventHoldIdentity _ -> "EventHoldIdentity"
153− EventDynIdentity _ -> "EventDynIdentity"
157−debugPropagate = False
159−debugInvalidateHeight = False
161−debugInvalidate = False
163−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
164−{-# INLINE showNodeId #-}
165−showNodeId :: a -> String
171−{-# NOINLINE nextNodeIdRef #-}
172−nextNodeIdRef :: IORef Int
173−nextNodeIdRef = unsafePerformIO $ newIORef 1
176−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
178−{-# NOINLINE unsafeNodeId #-}
179−unsafeNodeId :: a -> Int
180−unsafeNodeId a = unsafePerformIO $ do
185−--------------------------------------------------------------------------------
187−--------------------------------------------------------------------------------
189−newtype Event x a = Event { subscribe :: Subscriber x a -> EventM x (EventSubscription x a) }
191−wrap :: Monad m => (t -> EventSubscribed x a) -> (Subscriber x a -> m (WeakBagTicket (Subscriber x a), t)) -> Subscriber x a -> m (EventSubscription x a)
192−wrap tag getSpecificSubscribed sub = do
193− (sln, subd) <- getSpecificSubscribed sub
194− return $ EventSubscription (Just sln) $ tag subd
196−eventRoot :: GCompare k => k a -> Root x k -> Event x a
197−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
199−eventNever :: Event x a
200−eventNever = Event $ \_ -> return $ EventSubscription Nothing eventSubscribedNever
202−eventPush :: Push x b a -> Event x a
203−eventPush !p = Event $ wrap eventSubscribedPush $ getPushSubscribed p
205−eventMerge :: (GCompare k, a ~ DMap k Identity) => Merge x k -> Event x a
206−eventMerge !m = Event $ wrap eventSubscribedMerge $ getMergeSubscribed m
208−eventFan :: GCompare k => k a -> Fan x k -> Event x a
209−eventFan !k !f = Event $ wrap (eventSubscribedFan k) $ getFanSubscribed k f
211−eventSwitch :: Switch x a -> Event x a
212−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
214−eventCoincidence :: Coincidence x a -> Event x a
215−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
217−eventHold :: (a ~ p b, R.Patch p) => Hold x p b -> Event x a
218−eventHold !h = Event $ subscribeHoldEvent h
220−eventDyn :: (a ~ p b, R.Patch p) => Dyn x p b -> Event x a
221−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
223−eventHoldIdentity :: (a ~ Identity b) => Hold x Identity b -> Event x a
224−eventHoldIdentity !h = Event $ subscribeHoldEvent h
226−eventDynIdentity :: (a ~ Identity b) => Dyn x Identity b -> Event x a
227−eventDynIdentity !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
229−{-# INLINE subscribeCoincidenceInner #-}
230−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x a)
231−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
232− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
233− subscription@(EventSubscription _ innerSubd) <- subscribe inner subInner
234− innerOcc <- liftIO $ readEventSubscribed innerSubd
235− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
236− let height = max innerHeight outerHeight
237− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
238− return (innerOcc, height, innerSubd)
240−--------------------------------------------------------------------------------
242−--------------------------------------------------------------------------------
244−data Subscriber x a = Subscriber
245− { subscriberPropagate :: !(a -> EventM x ())
246− , subscriberInvalidateHeight :: !(Height -> IO ())
247− , subscriberRecalculateHeight :: !(Height -> IO ())
250−--TODO: Move this comment to WeakBag
251−-- These function are constructor functions that are marked NOINLINE so they are
252−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
253−-- so any weak references that are attached to the constructors will have their
254−-- finalizer run. Using the opaque constructor, does not see the
255−-- constructor application, so it behaves like an IORef and cannot be fused away.
257−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
258−-- the weak pointer to it in some cases.
260−newSubscriberPush :: (a -> ComputeM x (Maybe b)) -> PushSubscribed x a b -> IO (Subscriber x a)
261−newSubscriberPush compute subscribed = return $ Subscriber
262− { subscriberPropagate = \a -> {-# SCC "traversePush" #-} do
263− tracePropagate $ "SubscriberPush" <> showNodeId subscribed
264− occ <- runComputeM $ compute a
266− Nothing -> return () -- No need to write a Nothing back into the Ref
268− liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
269− scheduleClear $ pushSubscribedOccurrence subscribed
270− propagate o $ pushSubscribedSubscribers subscribed
271− , subscriberInvalidateHeight = \old -> do
272− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
273− WeakBag.traverse (pushSubscribedSubscribers subscribed) $ invalidateSubscriberHeight old
274− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
275− , subscriberRecalculateHeight = \new -> do
276− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
277− WeakBag.traverse (pushSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
278− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
281−newSubscriberHold :: R.Patch p => Hold x p a -> IO (Subscriber x (p a))
282−newSubscriberHold h = return $ Subscriber
283− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
284− , subscriberInvalidateHeight = \_ -> return ()
285− , subscriberRecalculateHeight = \_ -> return ()
288−newSubscriberMerge :: GCompare k => k a -> MergeSubscribed x k -> IO (Subscriber x a)
289−newSubscriberMerge k subscribed = return $ Subscriber
290− { subscriberPropagate = \a -> {-# SCC "traverseMerge" #-} do
291− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
292− oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
293− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge" <> showNodeId subscribed) k (Identity a) oldM
294− tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
295− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! newM
296− when (DMap.null oldM) $ do -- Only schedule the firing once
297− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
298− --TODO: assertions about height
299− currentHeight <- getCurrentHeight
300− when (height <= currentHeight) $ do
301− myStack <- liftIO $ whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
302− if height /= invalidHeight
303− then error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
305− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
306− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
307− error $ "Causality loop found:\n" <> drawForest (listsToForest stacks)
308− scheduleMerge height subscribed
309− , subscriberInvalidateHeight = \old -> do
310− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
311− removeMergeHeight old subscribed
312− invalidateMergeHeight subscribed
313− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
314− , subscriberRecalculateHeight = \new -> do
315− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
316− addMergeHeight new subscribed
317− revalidateMergeHeight subscribed
318− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
321−newSubscriberMergeChange :: GCompare k => MergeSubscribed x k -> IO (Subscriber x (R.PatchDMap (DMap k (Event x))))
322−newSubscriberMergeChange subscribed = return $ Subscriber
323− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
324− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
325− defer $ SomeMergeUpdate a subscribed
326− , subscriberInvalidateHeight = \_ -> return ()
327− , subscriberRecalculateHeight = \_ -> return ()
330−newSubscriberFan :: GCompare k => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
331−newSubscriberFan subscribed = return $ Subscriber
332− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
333− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
334− tracePropagate $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
335− let f _ (Pair (Identity v) subsubs) = do
336− propagate v $ _fanSubscribedChildren_list subsubs
337− return $ Constant ()
338− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
340− , subscriberInvalidateHeight = \old -> do
341− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
342− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
343− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
344− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
345− , subscriberRecalculateHeight = \new -> do
346− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
347− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
348− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
349− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
352−newSubscriberSwitch :: SwitchSubscribed x a -> IO (Subscriber x a)
353−newSubscriberSwitch subscribed = return $ Subscriber
354− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
355− tracePropagate $ "SubscriberSwitch" <> showNodeId subscribed
356− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
357− scheduleClear $ switchSubscribedOccurrence subscribed
358− propagate a $ switchSubscribedSubscribers subscribed
359− , subscriberInvalidateHeight = \_ -> do
360− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
361− oldHeight <- readIORef $ switchSubscribedHeight subscribed
362− when (oldHeight /= invalidHeight) $ do
363− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
364− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
365− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
366− , subscriberRecalculateHeight = \new -> do
367− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
368− updateSwitchHeight new subscribed
369− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
372−newSubscriberCoincidenceOuter :: CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
373−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
374− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
375− tracePropagate $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
376− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
377− tracePropagate $ " outerHeight = " <> show outerHeight
378− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
379− tracePropagate $ " isJust occ = " <> show (isJust occ)
380− tracePropagate $ " innerHeight = " <> show innerHeight
381− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
382− scheduleClear $ coincidenceSubscribedInnerParent subscribed
385− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
386− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
387− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
388− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
389− Just o -> do -- Since it's already firing, no need to adjust height
390− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
391− scheduleClear $ coincidenceSubscribedOccurrence subscribed
392− propagate o $ coincidenceSubscribedSubscribers subscribed
393− , subscriberInvalidateHeight = \_ -> do
394− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
395− invalidateCoincidenceHeight subscribed
396− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
397− , subscriberRecalculateHeight = \_ -> do
398− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
399− recalculateCoincidenceHeight subscribed
400− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
403−newSubscriberCoincidenceInner :: CoincidenceSubscribed x a -> IO (Subscriber x a)
404−newSubscriberCoincidenceInner subscribed = return $ Subscriber
405− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
406− tracePropagate $ "SubscriberCoincidenceInner" <> showNodeId subscribed
407− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
409− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
411− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
412− scheduleClear $ coincidenceSubscribedOccurrence subscribed
413− propagate a $ coincidenceSubscribedSubscribers subscribed
414− , subscriberInvalidateHeight = \_ -> do
415− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
416− invalidateCoincidenceHeight subscribed
417− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
418− , subscriberRecalculateHeight = \_ -> do
419− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
420− recalculateCoincidenceHeight subscribed
421− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
424−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
425−invalidateSubscriberHeight = flip subscriberInvalidateHeight
427−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
428−recalculateSubscriberHeight = flip subscriberRecalculateHeight
430−-- | Propagate everything at the current height
431−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
432−propagate a subscribers = withIncreasedDepth $ do
433− -- 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
434− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
435− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
437−--------------------------------------------------------------------------------
439−--------------------------------------------------------------------------------
441−data EventSubscribed x a = EventSubscribed
442− { eventSubscribedSubscribe :: !(Subscriber x a -> IO (Maybe (WeakBagTicket (Subscriber x a))))
443− , eventSubscribedRead :: !(IO (Maybe a))
444− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
445− , eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
446− , eventSubscribedHasOwnHeightRef :: !Bool
447− , eventSubscribedWhoCreated :: !(IO [String])
450−readEventSubscribed :: EventSubscribed x a -> IO (Maybe a)
451−readEventSubscribed = eventSubscribedRead
453−subscribeEventSubscribed :: EventSubscribed x a -> Subscriber x a -> IO (Maybe (WeakBagTicket (Subscriber x a)))
454−subscribeEventSubscribed = eventSubscribedSubscribe
456−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x a
457−eventSubscribedRoot !r = EventSubscribed
458− { eventSubscribedSubscribe = \sub -> Just <$> subscribeRootSubscribed r sub
459− , eventSubscribedRead = readRootSubscribed r
460− , eventSubscribedGetParents = return []
461− , eventSubscribedHeightRef = zeroRef
462− , eventSubscribedHasOwnHeightRef = False
463− , eventSubscribedWhoCreated = return ["root"]
466−eventSubscribedNever :: EventSubscribed x a
467−eventSubscribedNever = EventSubscribed
468− { eventSubscribedSubscribe = \_ -> return Nothing
469− , eventSubscribedRead = return Nothing
470− , eventSubscribedGetParents = return []
471− , eventSubscribedHeightRef = zeroRef
472− , eventSubscribedHasOwnHeightRef = False
473− , eventSubscribedWhoCreated = return ["never"]
476−eventSubscribedPush :: PushSubscribed x b a -> EventSubscribed x a
477−eventSubscribedPush !subscribed = EventSubscribed
478− { eventSubscribedSubscribe = \sub -> Just <$> subscribePushSubscribed subscribed sub
479− , eventSubscribedRead = readPushSubscribed subscribed
480− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ pushSubscribedParent subscribed]
481− , eventSubscribedHeightRef = pushSubscribedHeight subscribed
482− , eventSubscribedHasOwnHeightRef = False
483− , eventSubscribedWhoCreated = whoCreatedIORef $ pushSubscribedCachedSubscribed subscribed
486−eventSubscribedMerge :: a ~ DMap k Identity => MergeSubscribed x k -> EventSubscribed x a
487−eventSubscribedMerge !subscribed = EventSubscribed
488− { eventSubscribedSubscribe = \sub -> Just <$> subscribeMergeSubscribed subscribed sub
489− , eventSubscribedRead = readMergeSubscribed subscribed
490− , eventSubscribedGetParents = do
491− ps <- readIORef $ mergeSubscribedParents subscribed
492− return $ R.ffor (DMap.toList ps) $ \(_ :=> v) -> Some.This $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription v
493− , eventSubscribedHeightRef = mergeSubscribedHeight subscribed
494− , eventSubscribedHasOwnHeightRef = True
495− , eventSubscribedWhoCreated = whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
498−eventSubscribedFan :: GCompare k => k a -> FanSubscribed x k -> EventSubscribed x a
499−eventSubscribedFan !k !subscribed = EventSubscribed
500− { eventSubscribedSubscribe = \sub -> Just <$> subscribeFanSubscribed k subscribed sub
501− , eventSubscribedRead = readFanSubscribed k subscribed
502− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
503− , eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
504− , eventSubscribedHasOwnHeightRef = False
505− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
508−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x a
509−eventSubscribedSwitch !subscribed = EventSubscribed
510− { eventSubscribedSubscribe = \sub -> Just <$> subscribeSwitchSubscribed subscribed sub
511− , eventSubscribedRead = readSwitchSubscribed subscribed
512− , eventSubscribedGetParents = do
513− s <- readIORef $ switchSubscribedCurrentParent subscribed
514− return [Some.This $ _eventSubscription_subscribed s]
515− , eventSubscribedHeightRef = switchSubscribedHeight subscribed
516− , eventSubscribedHasOwnHeightRef = True
517− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
520−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x a
521−eventSubscribedCoincidence !subscribed = EventSubscribed
522− { eventSubscribedSubscribe = \sub -> Just <$> subscribeCoincidenceSubscribed subscribed sub
523− , eventSubscribedRead = readCoincidenceSubscribed subscribed
524− , eventSubscribedGetParents = do
525− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
526− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
527− innerParents = maybeToList $ fmap Some.This innerSubscription
528− return $ outerParent : innerParents
529− , eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
530− , eventSubscribedHasOwnHeightRef = True
531− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
534−getEventSubscribedHeight :: EventSubscribed x a -> IO Height
535−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
537−whoCreatedEventSubscribed :: EventSubscribed x a -> IO [String]
538−whoCreatedEventSubscribed = eventSubscribedWhoCreated
540−walkInvalidHeightParents :: EventSubscribed x a -> IO [Some (EventSubscribed x)]
541−walkInvalidHeightParents s0 = do
542− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
543− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
544− when (h == invalidHeight) $ do
545− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
546− modify (Some.This s :)
547− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
548− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
551−{-# INLINE subscribeHoldEvent #-}
552−subscribeHoldEvent :: (CanSubscribe x m, R.Patch p) => Hold x p a -> Subscriber x (p a) -> m (EventSubscription x (p a))
553−subscribeHoldEvent h sub = do
554− EventSubscription _ subd <- getHoldEventSubscription h
555− sln <- liftIO $ subscribeEventSubscribed subd sub
556− return $ EventSubscription sln subd
558−--------------------------------------------------------------------------------
560−--------------------------------------------------------------------------------
562−data EventSubscription x a = EventSubscription
563− { _eventSubscription_ticket :: !(Maybe (WeakBagTicket (Subscriber x a)))
564− , _eventSubscription_subscribed :: !(EventSubscribed x a)
567−unsubscribe :: EventSubscription x a -> IO ()
568−unsubscribe (EventSubscription msln _) = forM_ msln $ \sln -> WeakBag.remove sln
570−--------------------------------------------------------------------------------
572−--------------------------------------------------------------------------------
574−--TODO: Figure out why certain things are not 'representational', then make them
575−--representational so we can use coerce
577−--type role Hold representational
579− = Hold { holdValue :: !(IORef a)
580− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
581− , holdParent :: !(IORef (Either (Event x (p a)) (EventSubscription x (p a)))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
588− = EventEnv { eventEnvSpiderEnv :: !(SpiderEnv x)
589− , eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
590− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
591− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
592− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
593− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
594− , eventEnvRootClears :: !(IORef [SomeRootClear])
595− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
596− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
597− , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge x]))
600−{-# INLINE runEventM #-}
601−runEventM :: EventM x a -> EventEnv x -> IO a
602−runEventM = runReaderT . unEventM
604−class MonadIO m => Defer a m where
605− getDeferralQueue :: m (IORef [a])
608−defer :: Defer a m => a -> m ()
610− q <- getDeferralQueue
611− liftIO $ modifyIORef' q (a:)
613−instance Defer (SomeAssignment x) (EventM x) where
614− {-# INLINE getDeferralQueue #-}
615− getDeferralQueue = EventM $ asks eventEnvAssignments
617−instance Defer (SomeHoldInit x) (EventM x) where
618− {-# INLINE getDeferralQueue #-}
619− getDeferralQueue = EventM $ asks eventEnvHoldInits
621−instance Defer (SomeHoldInit x) (BehaviorM x) where
622− {-# INLINE getDeferralQueue #-}
623− getDeferralQueue = BehaviorM $ asks snd
625−instance Defer (SomeMergeUpdate x) (EventM x) where
626− {-# INLINE getDeferralQueue #-}
627− getDeferralQueue = EventM $ asks eventEnvMergeUpdates
629−instance Defer (SomeMergeInit x) (EventM x) where
630− {-# INLINE getDeferralQueue #-}
631− getDeferralQueue = EventM $ asks eventEnvMergeInits
633−class HasCurrentHeight x m | m -> x where
634− getCurrentHeight :: m Height
635− scheduleMerge :: Height -> MergeSubscribed x a -> m ()
637−instance HasCurrentHeight x (EventM x) where
638− {-# INLINE getCurrentHeight #-}
639− getCurrentHeight = EventM $ do
640− heightRef <- asks eventEnvCurrentHeight
641− liftIO $ readIORef heightRef
642− {-# INLINE scheduleMerge #-}
643− scheduleMerge height subscribed = EventM $ do
644− delayedRef <- asks eventEnvDelayedMerges
645− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [DelayedMerge subscribed]
647−class HasSpiderEnv x m | m -> x where
648− -- | Retrieve the current SpiderEnv
649− askSpiderEnv :: m (SpiderEnv x)
651−instance HasSpiderEnv x (EventM x) where
652− {-# INLINE askSpiderEnv #-}
653− askSpiderEnv = EventM $ asks eventEnvSpiderEnv
655−instance HasSpiderEnv x (SpiderHost x) where
656− {-# INLINE askSpiderEnv #-}
657− askSpiderEnv = SpiderHost ask
659−putCurrentHeight :: Height -> EventM x ()
660−putCurrentHeight h = EventM $ do
661− heightRef <- asks eventEnvCurrentHeight
662− liftIO $ writeIORef heightRef $! h
664−instance Defer SomeClear (EventM x) where
665− {-# INLINE getDeferralQueue #-}
666− getDeferralQueue = EventM $ asks eventEnvClears
668−{-# INLINE scheduleClear #-}
669−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
670−scheduleClear r = defer $ SomeClear r
672−instance Defer SomeRootClear (EventM x) where
673− {-# INLINE getDeferralQueue #-}
674− getDeferralQueue = EventM $ asks eventEnvRootClears
676−{-# INLINE scheduleRootClear #-}
677−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
678−scheduleRootClear r = defer $ SomeRootClear r
680−instance Defer (SomeResetCoincidence x) (EventM x) where
681− {-# INLINE getDeferralQueue #-}
682− getDeferralQueue = EventM $ asks eventEnvResetCoincidences
684−-- Note: hold cannot examine its event until after the phase is over
685−{-# SPECIALIZE hold :: R.Patch p => a -> Event x (p a) -> EventM x (Hold x p a) #-}
686−{-# SPECIALIZE hold :: R.Patch p => a -> Event x (p a) -> ComputeM x (Hold x p a) #-}
687−hold :: (R.Patch p, Defer (SomeHoldInit x) m) => a -> Event x (p a) -> m (Hold x p a)
689− valRef <- liftIO $ newIORef v0
690− invsRef <- liftIO $ newIORef []
691− parentRef <- liftIO $ newIORef $ Left e
693− nodeId <- liftIO newNodeId
696− { holdValue = valRef
697− , holdInvalidators = invsRef
698− , holdParent = parentRef
700− , holdNodeId = nodeId
703− defer $ SomeHoldInit h
706−{-# INLINE getHoldEventSubscription #-}
707−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))
708−getHoldEventSubscription h = do
709− ep <- liftIO $ readIORef $ holdParent h
711− Right subd -> return subd
713− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
714− subscription@(EventSubscription _ subd) <- subscribe e =<< liftIO (newSubscriberHold h)
715− occ <- liftIO $ readEventSubscribed subd
716− liftIO $ writeIORef subscriptionRef $! subscription
718− Nothing -> return ()
720− old <- liftIO $ readIORef $ holdValue h
721− case R.apply o old of
722− Nothing -> return ()
724− -- Need to evaluate these so that we don't retain the Hold itself
725− v <- liftIO $ evaluate $ holdValue h
726− i <- liftIO $ evaluate $ holdInvalidators h
727− defer $ SomeAssignment v i new
728− liftIO $ writeIORef (holdParent h) $ Right subscription
731−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
733−--type role BehaviorM representational
734−-- BehaviorM can sample behaviors
735−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
737−instance Monad (BehaviorM x) where
738− {-# INLINE (>>=) #-}
739− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
741− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
742− {-# INLINE return #-}
743− return x = BehaviorM $ return x
745− fail s = BehaviorM $ fail s
747−data BehaviorSubscribed x a
748− = forall p. BehaviorSubscribedHold (Hold x p a)
749− | BehaviorSubscribedPull (PullSubscribed x a)
751−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
753−--type role PullSubscribed representational
754−data PullSubscribed x a
755− = PullSubscribed { pullSubscribedValue :: !a
756− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
757− , pullSubscribedOwnInvalidator :: !(Invalidator x)
758− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
761−--type role Pull representational
763− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
764− , pullCompute :: !(BehaviorM x a)
771− = forall a. InvalidatorPull (Pull x a)
772− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
774−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
775− { rootSubscribedKey :: !(k a)
776− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
777− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
778− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
779− , rootSubscribedUninit :: IO ()
780− , 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?
782− , rootSubscribedNodeId :: Int
786−data Root x (k :: * -> *)
787− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
788− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
789− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
792−data SomeHoldInit x = forall p a. R.Patch p => SomeHoldInit !(Hold x p a)
794−data SomeMergeUpdate x = forall k. GCompare k => SomeMergeUpdate (R.PatchDMap (DMap k (Event x))) (MergeSubscribed x k)
796−data SomeMergeInit x = forall k. GCompare k => SomeMergeInit !(MergeSubscribed x k) !(Event x (R.PatchDMap (DMap k (Event x))))
798−data SomeEventSubscription x = forall a. SomeEventSubscription (EventSubscription x a)
800−-- EventM can do everything BehaviorM can, plus create holds
801−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
803−data PushSubscribed x a b
804− = PushSubscribed { pushSubscribedCachedSubscribed :: !(IORef (Maybe (PushSubscribed x a b)))
805− , 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)
806− , pushSubscribedHeight :: !(IORef Height)
807− , pushSubscribedSubscribers :: !(WeakBag (Subscriber x b))
808− , pushSubscribedSelf :: !(Subscriber x a) -- Hold this in memory to ensure our WeakReferences don't die --TODO: Probably unneeded now
809− , pushSubscribedWeakSelf :: !(IORef (Weak (PushSubscribed x a b)))
810− , pushSubscribedParent :: !(EventSubscription x a)
812− , pushSubscribedNodeId :: Int
816−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
818−instance Defer (SomeHoldInit x) (ComputeM x) where
819− getDeferralQueue = ComputeM ask
821−{-# SPECIALIZE runComputeM :: ComputeM x a -> EventM x a #-}
822−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
823−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
826− = 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?)
827− , pushParent :: !(Event x a)
828− , pushSubscribed :: !(IORef (Maybe (PushSubscribed x a b))) --TODO: Can we replace this with an unsafePerformIO thunk?
831−data MergeSubscribedParent (x :: *) k a = MergeSubscribedParent !(EventSubscription x a) !(Subscriber x a)
833−mergeSubscribedParentSubscription :: MergeSubscribedParent x k a -> EventSubscription x a
834−mergeSubscribedParentSubscription (MergeSubscribedParent es _) = es
836−data HeightBag = HeightBag
837− { _heightBag_size :: {-# UNPACK #-} !Int
838− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
840− deriving (Show, Read, Eq, Ord)
842−heightBagEmpty :: HeightBag
843−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
845−heightBagSize :: HeightBag -> Int
846−heightBagSize = _heightBag_size
848−heightBagFromList :: [Height] -> HeightBag
849−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
851−heightBagAdd :: Height -> HeightBag -> HeightBag
852−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
854−heightBagRemove :: Height -> HeightBag -> HeightBag
855−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
856− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
857− Just old -> HeightBag (pred s) $ case old of
858− 0 -> IntMap.delete h c
859− _ -> IntMap.insert h (pred old) c
861−heightBagMax :: HeightBag -> Height
862−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
863− Just ((h, _), _) -> Height h
864− Nothing -> zeroHeight
866−heightBagVerify :: HeightBag -> HeightBag
868−heightBagVerify b@(HeightBag s c) = if
869− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
870− -> error $ "heightBagVerify: size doesn't match: " <> show b
871− | unHeight invalidHeight `IntMap.member` c
872− -> error $ "heightBagVerify: contains invalid height: " <> show b
878−data MergeSubscribed x k
879− = MergeSubscribed { mergeSubscribedCachedSubscribed :: !(IORef (Maybe (MergeSubscribed x k))) -- From the original merge
880− , mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
881− , mergeSubscribedAccum :: !(IORef (DMap k Identity)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
882− , mergeSubscribedHeight :: !(IORef Height)
883− , mergeSubscribedHeightBag :: !(IORef HeightBag)
884− , mergeSubscribedSubscribers :: !(WeakBag (Subscriber x (DMap k Identity)))
885− , mergeSubscribedChange :: !(IORef (Subscriber x (R.PatchDMap (DMap k (Event x))), EventSubscribed x (R.PatchDMap (DMap k (Event x)))))
886− , mergeSubscribedParents :: !(IORef (DMap k (MergeSubscribedParent x k)))
887− , mergeSubscribedWeakSelf :: !(IORef (Weak (MergeSubscribed x k)))
889− , mergeSubscribedNodeId :: Int
893−--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
895− = Merge { mergeParents :: !(Dynamic x R.PatchDMap (DMap k (Event x)))
896− , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed x k)))
899−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
900− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
901− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
902− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
905−data FanSubscribed (x :: *) k
906− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
907− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
908− , fanSubscribedParent :: !(EventSubscription x (DMap k Identity))
910− , fanSubscribedNodeId :: Int
915− = Fan { fanParent :: !(Event x (DMap k Identity))
916− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
919−data SwitchSubscribed x a
920− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
921− , switchSubscribedOccurrence :: !(IORef (Maybe a))
922− , switchSubscribedHeight :: !(IORef Height)
923− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
924− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
925− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
926− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
927− , switchSubscribedParent :: !(Behavior x (Event x a))
928− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x a))
929− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
931− , switchSubscribedNodeId :: Int
936− = Switch { switchParent :: !(Behavior x (Event x a))
937− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
940−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
941−data CoincidenceSubscribed x a
942− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
943− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
944− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
945− , coincidenceSubscribedHeight :: !(IORef Height)
946− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
947− , coincidenceSubscribedOuterParent :: !(EventSubscription x (Event x a))
948− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x a)))
949− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
951− , coincidenceSubscribedNodeId :: Int
956− = Coincidence { coincidenceParent :: !(Event x (Event x a))
957− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
960−{-# NOINLINE newInvalidatorSwitch #-}
961−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
962−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
964−{-# NOINLINE newInvalidatorPull #-}
965−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
966−newInvalidatorPull p = return $! InvalidatorPull p
969− = DynamicHold !(Hold x p a)
970− | p ~ Identity => DynamicHoldIdentity !(Hold x Identity a)
972− | DynamicDyn !(Dyn x p a)
973− | p ~ Identity => DynamicDynIdentity !(Dyn x Identity a)
975−{-# INLINE current #-}
976−current :: R.Patch p => Dynamic x p a -> Behavior x a
978− DynamicHold h -> BehaviorHold h
979− DynamicHoldIdentity h -> BehaviorHoldIdentity h
980− DynamicConst a -> BehaviorConst a
981− DynamicDyn d -> BehaviorDyn d
982− DynamicDynIdentity d -> BehaviorDynIdentity d
984−--TODO: If you only need updated, not current, can we avoid actually constructing the Hold?
985−{-# INLINE updated #-}
986−updated :: R.Patch p => Dynamic x p a -> Event x (p a)
988− DynamicHold h -> eventHold h
989− DynamicHoldIdentity h -> eventHoldIdentity h
990− DynamicConst _ -> eventNever
991− DynamicDyn d -> eventDyn d
992− DynamicDynIdentity d -> eventDynIdentity d
994−newMapDyn :: (a -> b) -> Dynamic x Identity a -> Dynamic x Identity b
995−newMapDyn f d = DynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ current d) (Identity . f . runIdentity <$> updated d)
997−instance Functor (Dynamic x Identity) where
1000−instance Applicative (Dynamic x Identity) where
1001− pure = DynamicConst
1002− (<*>) = zipDynWith ($)
1006−instance R.FunctorMaybe (Event x) where
1007− fmapMaybe f = push $ return . f
1009−instance Align (Event x) where
1011− align ea eb = R.fmapMaybe R.dmapToThese $ merge $ DynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
1013−--TODO: Avoid the duplication between this and R.zipDynWith
1014−zipDynWith :: (a -> b -> c) -> Dynamic x Identity a -> Dynamic x Identity b -> Dynamic x Identity c
1015−zipDynWith f da db =
1016− let eab = align (updated da) (updated db)
1017− ec = flip push eab $ \o -> do
1018− (a, b) <- case o of
1019− This (Identity a) -> do
1020− b <- readBehaviorUntracked $ current db
1022− That (Identity b) -> do
1023− a <- readBehaviorUntracked $ current da
1025− These (Identity a) (Identity b) -> return (a, b)
1026− return $ Just $ Identity $ f a b
1027− in DynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (current da) <*> readBehaviorUntracked (current db)) ec
1029−instance Monad (Dynamic x Identity) where
1030− {-# INLINE return #-}
1032− {-# INLINE (>>=) #-}
1033− x >>= f = DynamicDynIdentity $ newJoinDyn $ newMapDyn f x --TODO: (>>), fail
1034− {-# INLINE (>>) #-}
1036− {-# INLINE fail #-}
1037− fail _ = error "Dynamic does not support 'fail'"
1039−newtype Dyn x p a = Dyn { unDyn :: IORef (Either (BehaviorM x a, Event x (p a)) (Hold x p a)) }
1041−unsafeDyn :: BehaviorM x a -> Event x (p a) -> Dyn x p a
1042−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1043− where x = (readV0, v')
1045−newJoinDyn :: Dynamic x Identity (Dynamic x Identity a) -> Dyn x Identity a
1047− let readV0 = readBehaviorTracked . current =<< readBehaviorTracked (current d)
1048− eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . current . runIdentity) $ updated d
1049− eInner = switch $ updated <$> current d
1050− eBoth = coincidence $ updated . runIdentity <$> updated d
1051− v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
1052− in unsafeDyn readV0 v'
1054−--type role Behavior representational
1056− = forall p. BehaviorHold !(Hold x p a)
1057− | BehaviorHoldIdentity !(Hold x Identity a)
1059− | BehaviorPull !(Pull x a)
1060− | BehaviorDynIdentity !(Dyn x Identity a)
1061− | forall p. R.Patch p => BehaviorDyn !(Dyn x p a)
1063−-- ResultM can read behaviors and events
1064−type ResultM = EventM
1066−{-# NOINLINE unsafeNewIORef #-}
1067−unsafeNewIORef :: a -> b -> IORef b
1068−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1070−instance Functor (Event x) where
1071− fmap f = push $ return . Just . f
1073−instance Functor (Behavior x) where
1074− fmap f = pull . fmap f . readBehaviorTracked
1076−{-# NOINLINE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
1077−push :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1078−push f e = eventPush $ Push
1081− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
1083−-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1085−{-# NOINLINE pull #-}
1086−pull :: BehaviorM x a -> Behavior x a
1087−pull a = BehaviorPull $ Pull
1089− , pullValue = unsafeNewIORef a Nothing
1090−#ifdef DEBUG_NODEIDS
1091− , pullNodeId = unsafeNodeId a
1095−{-# NOINLINE switch #-}
1096−switch :: Behavior x (Event x a) -> Event x a
1097−switch a = eventSwitch $ Switch
1099− , switchSubscribed = unsafeNewIORef a Nothing
1102−coincidence :: Event x (Event x a) -> Event x a
1103−coincidence a = eventCoincidence $ Coincidence
1104− { coincidenceParent = a
1105− , coincidenceSubscribed = unsafeNewIORef a Nothing
1108−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1109−run :: [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1110−run roots after = do
1111− tracePropagate $ "Running an event frame with " <> show (length roots) <> " events"
1112− spiderEnv <- SpiderHost ask
1113− result <- SpiderHost $ lift $ withMVar (_spiderEnv_lock spiderEnv) $ \_ -> flip runReaderT spiderEnv $ unSpiderHost $ runFrame $ do
1114− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1115− occBefore <- liftIO $ do
1116− occBefore <- readIORef occRef
1117− writeIORef occRef $! DMap.insert k a occBefore
1119− if DMap.null occBefore
1120− then do scheduleRootClear occRef
1122− else return Nothing
1123− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1124− propagate a subscribersRef
1125− delayedRef <- EventM $ asks eventEnvDelayedMerges
1127− delayed <- liftIO $ readIORef delayedRef
1128− case IntMap.minViewWithKey delayed of
1129− Nothing -> return ()
1130− Just ((currentHeight, cur), future) -> do
1131− tracePropagate $ "Running height " ++ show currentHeight
1132− putCurrentHeight $ Height currentHeight
1133− liftIO $ writeIORef delayedRef $! future
1134− forM_ cur $ \d -> case d of
1135− DelayedMerge subscribed -> do
1136− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
1137− case height `compare` Height currentHeight of
1138− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1139− GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1141− m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
1142− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! DMap.empty
1143− --TODO: Assert that m is not empty
1144− liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
1145− scheduleClear $ mergeSubscribedOccurrence subscribed
1146− propagate m $ mergeSubscribedSubscribers subscribed
1149− putCurrentHeight maxBound
1151− tracePropagate "Done running an event frame"
1154−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1156−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1158−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1160−data DelayedMerge x = forall k. DelayedMerge (MergeSubscribed x k)
1162−debugFinalize :: Bool
1163−debugFinalize = False
1165−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1166−mkWeakPtrWithDebug x debugNote = do
1170− then Just $ putStrLn $ "finalizing: " ++ debugNote
1173−type WeakList a = [Weak a]
1175−{-# INLINE withIncreasedDepth #-}
1177−withIncreasedDepth :: CanTrace x m => m a -> m a
1178−withIncreasedDepth a = do
1179− spiderEnv <- askSpiderEnv
1180− liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) succ
1182− liftIO $ modifyIORef' (_spiderEnv_depth spiderEnv) pred
1185−withIncreasedDepth :: m a -> m a
1186−withIncreasedDepth = id
1189−type CanTrace x m = (HasSpiderEnv x m, MonadIO m)
1191−{-# INLINE tracePropagate #-}
1192−tracePropagate :: (CanTrace x m) => String -> m ()
1193−tracePropagate = traceWhen debugPropagate
1195−{-# INLINE traceInvalidate #-}
1196−traceInvalidate :: String -> IO ()
1197−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1199−{-# INLINE traceWhen #-}
1200−traceWhen :: (CanTrace x m) => Bool -> String -> m ()
1201−traceWhen b message = traceMWhen b $ return message
1203−{-# INLINE traceMWhen #-}
1204−traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
1205−traceMWhen b getMessage = when b $ do
1206− message <- getMessage
1208− spiderEnv <- askSpiderEnv
1209− d <- liftIO $ readIORef $ _spiderEnv_depth spiderEnv
1213− liftIO $ putStrLn $ replicate d ' ' <> message
1215−whoCreatedIORef :: IORef a -> IO [String]
1216−whoCreatedIORef (IORef a) = whoCreated $! a
1218−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1221− (x :| xs) : t -> case groupByHead t of
1222− [] -> [(x, xs :| [])]
1224− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1225− | otherwise -> (x, xs :| []) : l
1227−listsToForest :: Eq a => [[a]] -> Forest a
1228−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1230−{-# INLINE propagateSubscriberHold #-}
1231−propagateSubscriberHold :: R.Patch p => Hold x p a -> p a -> EventM x ()
1232−propagateSubscriberHold h a = do
1233− {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1234− invalidators <- liftIO $ readIORef $ holdInvalidators h
1235− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1236− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1237− case {-# SCC "apply" #-} R.apply a v of
1238− Nothing -> return ()
1240− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1241− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1242− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1243− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1245−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
1247−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> BehaviorM x a #-}
1248−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> EventM x a #-}
1249−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
1250−readBehaviorUntracked b = do
1251− holdInits <- getDeferralQueue
1252− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
1254−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1255−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1257−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1259− (!m, _) <- BehaviorM ask
1261− Nothing -> return Nothing
1262− Just (!wi, _) -> return $ Just wi
1264−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1266− (!m, _) <- BehaviorM ask
1268− Nothing -> return Nothing
1269− Just (_, !p) -> return $ Just p
1271−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1272−askBehaviorHoldInits = do
1273− (_, !his) <- BehaviorM ask
1276−readBehaviorTracked :: Behavior x a -> BehaviorM x a
1277−readBehaviorTracked b = case b of
1278− BehaviorHold h -> readHoldTracked h
1279− BehaviorHoldIdentity h -> readHoldTracked h
1280− BehaviorConst a -> return a
1281− BehaviorPull p -> do
1282− val <- liftIO $ readIORef $ pullValue p
1284− Just subscribed -> do
1285− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1286− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
1287− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
1288− return $ pullSubscribedValue subscribed
1290− i <- liftIO $ newInvalidatorPull p
1291− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
1292− parentsRef <- liftIO $ newIORef []
1293− holdInits <- askBehaviorHoldInits
1294− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
1295− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
1296− parents <- liftIO $ readIORef parentsRef
1297− let subscribed = PullSubscribed
1298− { pullSubscribedValue = a
1299− , pullSubscribedInvalidators = invsRef
1300− , pullSubscribedOwnInvalidator = i
1301− , pullSubscribedParents = parents
1303− liftIO $ writeIORef (pullValue p) $ Just subscribed
1304− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1306− BehaviorDyn d -> readHoldTracked =<< getDynHold d
1307− BehaviorDynIdentity d -> readHoldTracked =<< getDynHold d
1309−{-# INLINE readHoldTracked #-}
1310−readHoldTracked :: Hold x p a -> BehaviorM x a
1311−readHoldTracked h = do
1312− result <- liftIO $ readIORef $ holdValue h
1313− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
1314− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
1317−{-# INLINE getDynHold #-}
1318−getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p a -> m (Hold x p a)
1320− mh <- liftIO $ readIORef $ unDyn d
1322− Right h -> return h
1323− Left (readV0, v') -> do
1324− holdInits <- getDeferralQueue
1325− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1327− liftIO $ writeIORef (unDyn d) $ Right h
1330−readRootSubscribed :: RootSubscribed x a -> IO (Maybe a)
1331−readRootSubscribed = rootSubscribedOccurrence
1333−readPushSubscribed :: PushSubscribed x b a -> IO (Maybe a)
1334−readPushSubscribed subscribed = do
1335− result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
1336− touch $ pushSubscribedSelf subscribed
1339−readMergeSubscribed :: MergeSubscribed x k -> IO (Maybe (DMap k Identity))
1340−readMergeSubscribed subscribed = do
1341− result <- readIORef $ mergeSubscribedOccurrence subscribed
1342− touch $ mergeSubscribedParents subscribed
1345−readFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> IO (Maybe a)
1346−readFanSubscribed k fs = do
1347− parentOcc <- readEventSubscribed $ _eventSubscription_subscribed $ fanSubscribedParent fs
1348− return $ coerce $ DMap.lookup k =<< parentOcc
1350−readSwitchSubscribed :: SwitchSubscribed x a -> IO (Maybe a)
1351−readSwitchSubscribed subscribed = do
1352− result <- readIORef $ switchSubscribedOccurrence subscribed
1353− touch $ switchSubscribedOwnInvalidator subscribed
1356−readCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO (Maybe a)
1357−readCoincidenceSubscribed subscribed = do
1358− result <- readIORef $ coincidenceSubscribedOccurrence subscribed
1359− touch $ coincidenceSubscribedOuter subscribed
1360− --TODO: do we need to touch the inner subscriber?
1363−-- Always refers to 0
1364−{-# NOINLINE zeroRef #-}
1365−zeroRef :: IORef Height
1366−zeroRef = unsafePerformIO $ newIORef zeroHeight
1368−type CanSubscribe x m =
1370− , HasCurrentHeight x m
1371− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1372− , Defer SomeClear m -- Wiping out event firings
1373− , Defer (SomeAssignment x) m -- Updating state
1374− , Defer (SomeResetCoincidence x) m
1378−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a), RootSubscribed x a)
1379−getRootSubscribed k r sub = do
1380− mSubscribed <- readIORef $ rootSubscribed r
1381− case DMap.lookup k mSubscribed of
1382− Just subscribed -> {-# SCC "hitRoot" #-} do
1383− sln <- subscribeRootSubscribed subscribed sub
1384− return (sln, subscribed)
1385− Nothing -> {-# SCC "missRoot" #-} do
1386− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1387− let !cached = rootSubscribed r
1388− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1389− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1390− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1391− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1392− writeIORef uninitRef $! uninit
1393− let subscribed = RootSubscribed
1394− { rootSubscribedKey = k
1395− , rootSubscribedCachedSubscribed = cached
1396− , rootSubscribedOccurrence = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1397− , rootSubscribedSubscribers = subs
1398− , rootSubscribedUninit = uninit
1399− , rootSubscribedWeakSelf = weakSelf
1400−#ifdef DEBUG_NODEIDS
1401− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1404− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1405− 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
1406− return (sln, subscribed)
1408−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1409−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1410−cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1411− rootSubscribedUninit self
1412− modifyIORef' cached $ DMap.delete k
1414−{-# INLINE subscribeRootSubscribed #-}
1415−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1416−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1418−-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
1419−{-# SPECIALIZE getPushSubscribed :: Push x a b -> Subscriber x b -> EventM x (WeakBagTicket (Subscriber x b), PushSubscribed x a b) #-}
1420−getPushSubscribed :: CanSubscribe x m => Push x a b -> Subscriber x b -> m (WeakBagTicket (Subscriber x b), PushSubscribed x a b)
1421−getPushSubscribed p sub = do
1422− mSubscribed <- liftIO $ readIORef $ pushSubscribed p
1423− case mSubscribed of
1424− Just subscribed -> {-# SCC "hitPush" #-} do
1425− sln <- liftIO $ subscribePushSubscribed subscribed sub
1426− return (sln, subscribed)
1427− Nothing -> {-# SCC "missPush" #-} do -- Not yet subscribed
1428− subscribedRef <- liftIO $ newIORef $ error "getPushSubscribed: subscribed not yet intialized"
1429− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1430− s <- liftIO $ newSubscriberPush (pushCompute p) subscribedUnsafe
1431− subscription@(EventSubscription _ subd) <- subscribe (pushParent p) s
1432− parentOcc <- liftIO $ readEventSubscribed subd
1433− occ <- runComputeM $ join <$> mapM (pushCompute p) parentOcc
1434− occRef <- liftIO $ newIORef occ
1435− when (isJust occ) $ scheduleClear occRef
1436− weakSelf <- liftIO $ newIORef $ error "getPushSubscribed: weakSelf not initialized"
1437− let !cached = pushSubscribed p
1438− (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupPushSubscribed
1439− let subscribed = PushSubscribed
1440− { pushSubscribedCachedSubscribed = cached
1441− , pushSubscribedOccurrence = occRef
1442− , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
1443− , pushSubscribedSubscribers = subs
1444− , pushSubscribedSelf = s
1445− , pushSubscribedWeakSelf = weakSelf
1446− , pushSubscribedParent = subscription
1447−#ifdef DEBUG_NODEIDS
1448− , pushSubscribedNodeId = unsafeNodeId p
1451− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
1452− liftIO $ writeIORef subscribedRef $! subscribed
1453− liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
1454− return (sln, subscribed)
1456−cleanupPushSubscribed :: PushSubscribed x a b -> IO ()
1457−cleanupPushSubscribed self = do
1458− unsubscribe $ pushSubscribedParent self
1459− writeIORef (pushSubscribedCachedSubscribed self) $ Nothing
1461−{-# INLINE subscribePushSubscribed #-}
1462−subscribePushSubscribed :: PushSubscribed x a b -> Subscriber x b -> IO (WeakBagTicket (Subscriber x b))
1463−subscribePushSubscribed subscribed sub = WeakBag.insert sub (pushSubscribedSubscribers subscribed) (pushSubscribedWeakSelf subscribed) cleanupPushSubscribed
1465−{-# SPECIALIZE getMergeSubscribed :: GCompare k => Merge x k -> Subscriber x (DMap k Identity) -> EventM x (WeakBagTicket (Subscriber x (DMap k Identity)), MergeSubscribed x k) #-}
1466−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)
1467−getMergeSubscribed m sub = do
1468− mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
1469− case mSubscribed of
1470− Just subscribed -> {-# SCC "hitMerge" #-} do
1471− sln <- liftIO $ subscribeMergeSubscribed subscribed sub
1472− return (sln, subscribed)
1473− Nothing -> {-# SCC "missMerge" #-} do
1474− subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
1475− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1476− initialParents <- readBehaviorUntracked $ current $ mergeParents m
1477− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x k))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1478− s <- liftIO $ newSubscriberMerge k subscribedUnsafe
1479− subscription@(EventSubscription _ parentSubd) <- subscribe e s
1480− parentOcc <- liftIO $ readEventSubscribed parentSubd
1481− height <- liftIO $ getEventSubscribedHeight parentSubd
1482− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription s)
1483− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1484− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1485− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1486− myHeight = if invalidHeight `elem` heights
1488− else succHeight $ heightBagMax myHeightBag
1489− currentHeight <- getCurrentHeight
1490− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1491− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1493− unless (DMap.null accum) $ do
1494− scheduleMerge myHeight subscribedUnsafe
1495− occRef <- liftIO $ newIORef occ
1496− when (isJust occ) $ scheduleClear occRef
1497− accumRef <- liftIO $ newIORef accum
1498− heightRef <- liftIO $ newIORef myHeight
1499− heightMapRef <- liftIO $ newIORef myHeightBag
1500− weakSelf <- liftIO $ newIORef $ error "getMergeSubscribed: weakSelf not yet initialized"
1501− (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupMergeSubscribed
1502− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1503− parentsRef <- liftIO $ newIORef $ DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1504− let !subscribed = MergeSubscribed
1505− { mergeSubscribedCachedSubscribed = mergeSubscribed m
1506− , mergeSubscribedOccurrence = occRef
1507− , mergeSubscribedAccum = accumRef
1508− , mergeSubscribedHeight = heightRef
1509− , mergeSubscribedHeightBag = heightMapRef
1510− , mergeSubscribedSubscribers = subs
1511− , mergeSubscribedChange = changeSubdRef
1512− , mergeSubscribedParents = parentsRef
1513− , mergeSubscribedWeakSelf = weakSelf
1514−#ifdef DEBUG_NODEIDS
1515− , mergeSubscribedNodeId = unsafeNodeId m
1518− defer $ SomeMergeInit subscribed $ updated $ mergeParents m
1519− liftIO $ writeIORef subscribedRef $! subscribed
1520− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "MergeSubscribed"
1521− liftIO $ writeIORef (mergeSubscribed m) $ Just subscribed
1522− return (sln, subscribed)
1524−cleanupMergeSubscribed :: MergeSubscribed x k -> IO ()
1525−cleanupMergeSubscribed subscribed = do
1526− parents <- readIORef $ mergeSubscribedParents subscribed
1527− forM_ (DMap.toList parents) $ \(_ :=> msp) -> unsubscribe $ mergeSubscribedParentSubscription msp
1528− -- Not necessary, because this whole MergeSubscribed is dead: writeIORef (mergeSubscribedParents subscribed) DMap.empty
1529− writeIORef (mergeSubscribedCachedSubscribed subscribed) $ Nothing -- Get rid of the cached subscribed
1531−{-# INLINE subscribeMergeSubscribed #-}
1532−subscribeMergeSubscribed :: MergeSubscribed x k -> Subscriber x (DMap k Identity) -> IO (WeakBagTicket (Subscriber x (DMap k Identity)))
1533−subscribeMergeSubscribed subscribed sub = WeakBag.insert sub (mergeSubscribedSubscribers subscribed) (mergeSubscribedWeakSelf subscribed) cleanupMergeSubscribed
1535−{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), FanSubscribed x k) #-}
1536−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)
1537−getFanSubscribed k f sub = do
1538− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1539− case mSubscribed of
1540− Just subscribed -> {-# SCC "hitFan" #-} do
1541− sln <- liftIO $ subscribeFanSubscribed k subscribed sub
1542− return (sln, subscribed)
1543− Nothing -> {-# SCC "missFan" #-} do
1544− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1545− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1546− s <- liftIO $ newSubscriberFan subscribedUnsafe
1547− subscription <- subscribe (fanParent f) s
1548− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1549− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1550− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1551− let subscribed = FanSubscribed
1552− { fanSubscribedCachedSubscribed = fanSubscribed f
1553− , fanSubscribedParent = subscription
1554− , fanSubscribedSubscribers = subscribersRef
1555−#ifdef DEBUG_NODEIDS
1556− , fanSubscribedNodeId = unsafeNodeId f
1559− let !self = (k, subscribed)
1560− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1561− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1562− liftIO $ writeIORef subscribedRef $! subscribed
1563− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1564− return (slnForSub, subscribed)
1566−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1567−cleanupFanSubscribed (k, subscribed) = do
1568− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1569− let reducedSubscribers = DMap.delete k subscribers
1570− if DMap.null reducedSubscribers
1572− unsubscribe $ fanSubscribedParent subscribed
1573− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1574− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1575− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1577−{-# INLINE subscribeFanSubscribed #-}
1578−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1579−subscribeFanSubscribed k subscribed sub = do
1580− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1581− case DMap.lookup k subscribers of
1582− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1583− let !self = (k, subscribed)
1584− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1585− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1586− writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeEventSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1588− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1590−{-# SPECIALIZE getSwitchSubscribed :: Switch x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), SwitchSubscribed x a) #-}
1591−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)
1592−getSwitchSubscribed s sub = do
1593− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1594− case mSubscribed of
1595− Just subscribed -> {-# SCC "hitSwitch" #-} do
1596− sln <- liftIO $ subscribeSwitchSubscribed subscribed sub
1597− return (sln, subscribed)
1598− Nothing -> {-# SCC "missSwitch" #-} do
1599− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1600− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1601− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1602− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1603− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1604− wiRef <- liftIO $ newIORef wi
1605− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1606− holdInits <- getDeferralQueue
1607− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1608− subscription@(EventSubscription _ subd) <- subscribe e mySub
1609− parentOcc <- liftIO $ readEventSubscribed subd
1610− subscriptionRef <- liftIO $ newIORef subscription
1611− occRef <- liftIO $ newIORef parentOcc
1612− when (isJust parentOcc) $ scheduleClear occRef
1613− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1614− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1615− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1616− let !subscribed = SwitchSubscribed
1617− { switchSubscribedCachedSubscribed = switchSubscribed s
1618− , switchSubscribedOccurrence = occRef
1619− , switchSubscribedHeight = heightRef
1620− , switchSubscribedSubscribers = subs
1621− , switchSubscribedOwnInvalidator = i
1622− , switchSubscribedOwnWeakInvalidator = wiRef
1623− , switchSubscribedBehaviorParents = parentsRef
1624− , switchSubscribedParent = switchParent s
1625− , switchSubscribedCurrentParent = subscriptionRef
1626− , switchSubscribedWeakSelf = weakSelf
1627−#ifdef DEBUG_NODEIDS
1628− , switchSubscribedNodeId = unsafeNodeId s
1631− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1632− liftIO $ writeIORef subscribedRef $! subscribed
1633− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1634− return (slnForSub, subscribed)
1636−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1637−cleanupSwitchSubscribed subscribed = do
1638− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1639− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1640− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1642−{-# INLINE subscribeSwitchSubscribed #-}
1643−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1644−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1646−{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), CoincidenceSubscribed x a) #-}
1647−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)
1648−getCoincidenceSubscribed c sub = do
1649− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1650− case mSubscribed of
1651− Just subscribed -> {-# SCC "hitCoincidence" #-} do
1652− sln <- liftIO $ subscribeCoincidenceSubscribed subscribed sub
1653− return (sln, subscribed)
1654− Nothing -> {-# SCC "missCoincidence" #-} do
1655− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1656− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1657− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1658− outerSubscription@(EventSubscription _ outerSubd) <- subscribe (coincidenceParent c) subOuter
1659− outerOcc <- liftIO $ readEventSubscribed outerSubd
1660− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1661− (occ, height, mInnerSubd) <- case outerOcc of
1662− Nothing -> return (Nothing, outerHeight, Nothing)
1664− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1665− return (occ, height, Just innerSubd)
1666− occRef <- liftIO $ newIORef occ
1667− when (isJust occ) $ scheduleClear occRef
1668− heightRef <- liftIO $ newIORef height
1669− innerSubdRef <- liftIO $ newIORef mInnerSubd
1670− scheduleClear innerSubdRef
1671− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1672− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1673− let subscribed = CoincidenceSubscribed
1674− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1675− , coincidenceSubscribedOccurrence = occRef
1676− , coincidenceSubscribedHeight = heightRef
1677− , coincidenceSubscribedSubscribers = subs
1678− , coincidenceSubscribedOuter = subOuter
1679− , coincidenceSubscribedOuterParent = outerSubscription
1680− , coincidenceSubscribedInnerParent = innerSubdRef
1681− , coincidenceSubscribedWeakSelf = weakSelf
1682−#ifdef DEBUG_NODEIDS
1683− , coincidenceSubscribedNodeId = unsafeNodeId c
1686− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1687− liftIO $ writeIORef subscribedRef $! subscribed
1688− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1689− return (slnForSub, subscribed)
1691−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1692−cleanupCoincidenceSubscribed subscribed = do
1693− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1694− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1696−{-# INLINE subscribeCoincidenceSubscribed #-}
1697−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1698−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1700−{-# INLINE merge #-}
1701−merge :: GCompare k => Dynamic x R.PatchDMap (DMap k (Event x)) -> Event x (DMap k Identity)
1702−merge m = eventMerge $ Merge
1704− , mergeSubscribed = unsafeNewIORef m Nothing
1707−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1709−fan :: GCompare k => Event x (DMap k Identity) -> EventSelector x k
1713− , fanSubscribed = unsafeNewIORef e Nothing
1715− in EventSelector $ \k -> eventFan k f
1717−runHoldInits :: IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1718−runHoldInits holdInitRef mergeInitRef = do
1719− holdInits <- liftIO $ readIORef holdInitRef
1720− mergeInits <- liftIO $ readIORef mergeInitRef
1721− unless (null holdInits && null mergeInits) $ do
1722− liftIO $ writeIORef holdInitRef []
1723− liftIO $ writeIORef mergeInitRef []
1724− mapM_ initHold holdInits
1725− mapM_ initMerge mergeInits
1726− runHoldInits holdInitRef mergeInitRef
1728−initHold :: SomeHoldInit x -> EventM x ()
1729−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1731−initMerge :: SomeMergeInit x -> EventM x ()
1732−initMerge (SomeMergeInit subscribed changed) = do
1733− changeSub <- liftIO $ newSubscriberMergeChange subscribed
1734− EventSubscription _ changeSubd <- subscribe changed changeSub
1735− change <- liftIO $ readEventSubscribed changeSubd
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− let newParent = MergeSubscribedParent subscription s
1783− newParentHeight <- liftIO $ getEventSubscribedHeight subd
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)
1852−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1853−{-# INLINE invalidHeightBeingTraversed #-}
1854−invalidHeightBeingTraversed :: Height
1855−invalidHeightBeingTraversed = Height (-1001)
1857−{-# INLINE succHeight #-}
1858−succHeight :: Height -> Height
1859−succHeight h@(Height a) =
1860− if h == invalidHeight
1862− else Height $ succ a
1864−removeMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1865−removeMergeHeight oldParentHeight subscribed = do
1866− when debugInvalidateHeight $ putStrLn $ "removeMergeHeight: " <> show oldParentHeight <> " Merge" <> showNodeId subscribed
1867− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1868− let newHeights = heightBagRemove oldParentHeight oldHeights
1869− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1871−invalidateMergeHeight :: MergeSubscribed x k -> IO ()
1872−invalidateMergeHeight subscribed = do
1873− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1874− -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1875− when (oldHeight /= invalidHeight) $ do
1876− writeIORef (mergeSubscribedHeight subscribed) $! invalidHeight
1877− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1879−addMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1880−addMergeHeight newParentHeight subscribed = do
1881− when debugInvalidateHeight $ putStrLn $ "addMergeHeight: " <> show newParentHeight <> " Merge" <> showNodeId subscribed
1882− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1883− let newHeights = heightBagAdd newParentHeight oldHeights
1884− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1886−revalidateMergeHeight :: MergeSubscribed x k -> IO ()
1887−revalidateMergeHeight subscribed = do
1888− currentHeight <- readIORef $ mergeSubscribedHeight subscribed
1889− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1890− heights <- readIORef $ mergeSubscribedHeightBag subscribed
1891− parents <- readIORef $ mergeSubscribedParents subscribed
1892− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1893− case heightBagSize heights `compare` DMap.size parents of
1896− let height = succHeight $ heightBagMax heights
1897− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1898− writeIORef (mergeSubscribedHeight subscribed) $! height
1899− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1900− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge" <> showNodeId subscribed
1902−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1903−invalidateCoincidenceHeight subscribed = do
1904− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1905− when (oldHeight /= invalidHeight) $ do
1906− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1907− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1909−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1910−updateSwitchHeight new subscribed = do
1911− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1912− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1913− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1914− writeIORef (switchSubscribedHeight subscribed) $! new
1915− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1917−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1918−recalculateCoincidenceHeight subscribed = do
1919− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1920− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1921− height <- calculateCoincidenceHeight subscribed
1922− when (height /= invalidHeight) $ do
1923− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1924− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1926−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1927−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1929−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1930−calculateCoincidenceHeight subscribed = do
1931− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1932− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1933− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1935−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1937−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1938−invalidate toReconnectRef wis = do
1939− forM_ wis $ \wi -> do
1943− traceInvalidate "invalidate Dead"
1944− return () --TODO: Should we clean this up here?
1946− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1948− InvalidatorPull p -> do
1949− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1950− mVal <- readIORef $ pullValue p
1951− forM_ mVal $ \val -> do
1952− writeIORef (pullValue p) Nothing
1953− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1954− InvalidatorSwitch subscribed -> do
1955− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1956− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1957− 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
1959−--------------------------------------------------------------------------------
1960−-- Reflex integration
1961−--------------------------------------------------------------------------------
1963−-- | The default, global Spider environment
1964−type Spider = SpiderEnv Global
1966−-- | Designates the default, global Spider timeline
1969−{-# NOINLINE globalSpiderEnv #-}
1970−globalSpiderEnv :: SpiderEnv Global
1971−globalSpiderEnv = unsafePerformIO unsafeNewSpiderEnv
1973−-- | Stores all global data relevant to a particular Spider timeline; only one
1974−-- value should exist for each type @x@
1975−data SpiderEnv x = SpiderEnv
1976− { _spiderEnv_toUnsubscribe :: !(IORef [SomeEventSubscription x])
1977− , _spiderEnv_lock :: !(MVar ())
1978− , _spiderEnv_cleanups :: !(IORef [IO ()])
1980− , _spiderEnv_depth :: !(IORef Int)
1983−type role SpiderEnv nominal
1985−instance GEq SpiderEnv where
1986− a `geq` b = if _spiderEnv_lock a == _spiderEnv_lock b
1987− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderEnv can't have two different 'x' arguments
1990−unsafeNewSpiderEnv :: forall x. IO (SpiderEnv x)
1991−unsafeNewSpiderEnv = do
1992− toUnsubscribe <- newIORef []
1994− cleanups <- newIORef []
1996− depthRef <- newIORef 0
1999− { _spiderEnv_toUnsubscribe = toUnsubscribe
2000− , _spiderEnv_lock = lock
2001− , _spiderEnv_cleanups = cleanups
2003− , _spiderEnv_depth = depthRef
2007−-- | Create a new SpiderEnv
2008−newSpiderEnv :: IO (Some SpiderEnv)
2009−newSpiderEnv = Some.This <$> unsafeNewSpiderEnv
2011−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2013−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2015−instance R.Reflex (SpiderEnv x) where
2016− newtype Behavior (SpiderEnv x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2017− newtype Event (SpiderEnv x) a = SpiderEvent { unSpiderEvent :: Event x a }
2018− newtype Dynamic (SpiderEnv x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x Identity a } deriving (Functor, Applicative, Monad)
2019− newtype Incremental (SpiderEnv x) p a = SpiderIncremental { unSpiderIncremental :: Dynamic x p a }
2020− type PullM (SpiderEnv x) = SpiderPullM x
2021− type PushM (SpiderEnv x) = SpiderPushM x
2022− {-# INLINABLE never #-}
2023− never = SpiderEvent eventNever
2024− {-# INLINABLE constant #-}
2025− constant = SpiderBehavior . BehaviorConst
2026− {-# INLINABLE push #-}
2027− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2028− {-# INLINABLE pull #-}
2029− pull = SpiderBehavior . pull . coerce
2030− {-# INLINABLE merge #-}
2031− merge = SpiderEvent . merge . DynamicConst . (unsafeCoerce :: DMap k (R.Event (SpiderEnv x)) -> DMap k (Event x))
2032− {-# INLINABLE fan #-}
2033− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2034− {-# INLINABLE switch #-}
2035− switch = SpiderEvent . switch . (unsafeCoerce :: Behavior x (R.Event (SpiderEnv x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2036− {-# INLINABLE coincidence #-}
2037− coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event x (R.Event (SpiderEnv x) a) -> Event x (Event x a)) . unSpiderEvent
2038− {-# INLINABLE current #-}
2039− current = SpiderBehavior . current . unSpiderDynamic
2040− {-# INLINABLE updated #-}
2041− updated = SpiderEvent . fmap runIdentity . updated . unSpiderDynamic
2042− {-# INLINABLE unsafeBuildDynamic #-}
2043− unsafeBuildDynamic readV0 v' = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (coerce readV0) $ addIdentity $ unSpiderEvent v'
2044− {-# INLINABLE unsafeBuildIncremental #-}
2045− unsafeBuildIncremental readV0 dv = SpiderIncremental $ DynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2046− {-# INLINABLE mergeIncremental #-}
2047− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x R.PatchDMap (DMap k (R.Event (SpiderEnv x))) -> Dynamic x R.PatchDMap (DMap k (Event x))) . unSpiderIncremental
2048− {-# INLINABLE currentIncremental #-}
2049− currentIncremental = SpiderBehavior . current . unSpiderIncremental
2050− {-# INLINABLE updatedIncremental #-}
2051− updatedIncremental = SpiderEvent . updated . unSpiderIncremental
2052− {-# INLINABLE incrementalToDynamic #-}
2053− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ current i) $ flip push (updated i) $ \p -> do
2054− c <- readBehaviorUntracked $ current i
2055− return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
2057−instance R.MonadSample (SpiderEnv x) (EventM x) where
2058− {-# INLINABLE sample #-}
2059− sample (SpiderBehavior b) = readBehaviorUntracked b
2061−instance R.MonadHold (SpiderEnv x) (EventM x) where
2062− {-# INLINABLE hold #-}
2063− hold = holdSpiderEventM
2064− {-# INLINABLE holdDyn #-}
2065− holdDyn = holdDynSpiderEventM
2066− {-# INLINABLE holdIncremental #-}
2067− holdIncremental = holdIncrementalSpiderEventM
2069−holdSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Behavior (SpiderEnv x) a)
2070−holdSpiderEventM v0 e = fmap (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2072−holdDynSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Dynamic (SpiderEnv x) a)
2073−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2075−holdIncrementalSpiderEventM :: R.Patch p => a -> R.Event (SpiderEnv x) (p a) -> EventM x (R.Incremental (SpiderEnv x) p a)
2076−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2078−instance R.MonadHold (SpiderEnv x) (SpiderHost x) where
2079− {-# INLINABLE hold #-}
2080− hold v0 e = R.runHostFrame $ R.hold v0 e
2081− {-# INLINABLE holdDyn #-}
2082− holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
2083− {-# INLINABLE holdIncremental #-}
2084− holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
2086−instance R.MonadSample (SpiderEnv x) (SpiderHost x) where
2087− {-# INLINABLE sample #-}
2088− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2090−instance R.MonadSample (SpiderEnv x) (SpiderPullM x) where
2091− {-# INLINABLE sample #-}
2092− sample = coerce . readBehaviorTracked . unSpiderBehavior
2094−instance R.MonadSample (SpiderEnv x) (SpiderPushM x) where
2095− {-# INLINABLE sample #-}
2096− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2098−instance R.MonadHold (SpiderEnv x) (SpiderPushM x) where
2099− {-# INLINABLE hold #-}
2100− hold v0 e = R.current <$> R.holdDyn v0 e
2101− {-# INLINABLE holdDyn #-}
2102− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity e
2103− {-# INLINABLE holdIncremental #-}
2104− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . DynamicHold <$> hold v0 e
2106−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2107−newtype SpiderEventHandle x a = SpiderEventHandle { unSpiderEventHandle :: EventSubscription x a }
2109−emptySubscriber :: Subscriber x a
2110−emptySubscriber = Subscriber
2111− { subscriberPropagate = \_ -> return ()
2112− , subscriberInvalidateHeight = \_ -> return ()
2113− , subscriberRecalculateHeight = \_ -> return ()
2116−instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHostFrame x) where
2117− {-# INLINABLE subscribeEvent #-}
2118− subscribeEvent e = SpiderHostFrame $ do
2119− subscription <- subscribe (unSpiderEvent e) emptySubscriber --TODO: Unsubscribe eventually (manually and/or with weak ref)
2120− return $ SpiderEventHandle subscription
2122−instance R.ReflexHost (SpiderEnv x) where
2123− type EventTrigger (SpiderEnv x) = RootTrigger x
2124− type EventHandle (SpiderEnv x) = SpiderEventHandle x
2125− type HostFrame (SpiderEnv x) = SpiderHostFrame x
2127−instance R.MonadReadEvent (SpiderEnv x) (ReadPhase x) where
2128− {-# INLINABLE readEvent #-}
2129− readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2130− let EventSubscription sln subscribed = unSpiderEventHandle h
2131− result <- readEventSubscribed subscribed
2135−instance MonadRef (EventM x) where
2136− type Ref (EventM x) = Ref IO
2137− {-# INLINABLE newRef #-}
2138− {-# INLINABLE readRef #-}
2139− {-# INLINABLE writeRef #-}
2140− newRef = liftIO . newRef
2141− readRef = liftIO . readRef
2142− writeRef r a = liftIO $ writeRef r a
2144−instance MonadAtomicRef (EventM x) where
2145− {-# INLINABLE atomicModifyRef #-}
2146− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2148−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2149−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2151−instance Monad (SpiderHost x) where
2152− {-# INLINABLE (>>=) #-}
2153− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2154− {-# INLINABLE (>>) #-}
2155− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2156− {-# INLINABLE return #-}
2157− return x = SpiderHost $ return x
2158− {-# INLINABLE fail #-}
2159− fail s = SpiderHost $ fail s
2161−-- | Run an action affecting the global Spider timeline; this will be guarded by
2162−-- a mutex for that timeline
2163−runSpiderHost :: SpiderHost Global a -> IO a
2164−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderEnv
2166−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2168−instance Monad (SpiderHostFrame x) where
2169− {-# INLINABLE (>>=) #-}
2170− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2171− {-# INLINABLE (>>) #-}
2172− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2173− {-# INLINABLE return #-}
2174− return x = SpiderHostFrame $ return x
2175− {-# INLINABLE fail #-}
2176− fail s = SpiderHostFrame $ fail s
2178−instance R.MonadSample (SpiderEnv x) (SpiderHostFrame x) where
2179− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2181−addIdentity :: Event x a -> Event x (Identity a)
2182−--addIdentity = fmap Identity
2183−addIdentity = unsafeCoerce
2185−instance R.MonadHold (SpiderEnv x) (SpiderHostFrame x) where
2186− {-# INLINABLE hold #-}
2187− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2188− {-# INLINABLE holdDyn #-}
2189− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2190− {-# INLINABLE holdIncremental #-}
2191− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2193−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2194−newEventWithTriggerIO f = do
2195− es <- newFanEventWithTriggerIO $ \Refl -> f
2196− return $ select es Refl
2198−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2199−newFanEventWithTriggerIO f = do
2200− occRef <- newIORef DMap.empty
2201− subscribedRef <- newIORef DMap.empty
2203− { rootOccurrence = occRef
2204− , rootSubscribed = subscribedRef
2207− return $ EventSelector $ \k -> eventRoot k r
2209−instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHost x) where
2210− newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2211− newFanEventWithTrigger f = SpiderHost $ lift $ do
2212− es <- newFanEventWithTriggerIO f
2213− return $ R.EventSelector $ SpiderEvent . select es
2215−instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHostFrame x) where
2216− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2217− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2218− es <- newFanEventWithTriggerIO f
2219− return $ R.EventSelector $ SpiderEvent . select es
2221−instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHost x) where
2222− {-# INLINABLE subscribeEvent #-}
2223− subscribeEvent = subscribeEventSpiderHost
2225−subscribeEventSpiderHost :: R.Event (SpiderEnv x) a -> SpiderHost x (R.EventHandle (SpiderEnv x) a)
2226−subscribeEventSpiderHost e = do
2227− subscription <- runFrame $ subscribe (unSpiderEvent e) emptySubscriber --TODO: Unsubscribe eventually (manually and/or with weak ref)
2228− return $ SpiderEventHandle subscription
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