@@ -0,0 +1,2273 @@
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.GADT.Compare
51+import Data.IntMap.Strict (IntMap)
52+import qualified Data.IntMap.Strict as IntMap
54+import Data.List hiding (foldl')
55+import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
56+import qualified Data.List.NonEmpty as NonEmpty
58+import Data.Monoid (mempty, (<>))
59+import Data.Some (Some)
60+import qualified Data.Some as Some
62+import Data.Traversable
63+import Data.Tree (Forest, Tree (..), drawForest)
65+import GHC.IORef (IORef (..))
67+import System.IO.Unsafe
68+import System.Mem.Weak
71+import Data.WeakBag (WeakBag, WeakBagTicket)
72+import qualified Data.WeakBag as WeakBag
73+import qualified Reflex.Class as R
74+import qualified Reflex.Host.Class as R
76+-- Note: must come last to silence warnings due to AMP on GHC < 7.10
77+import Prelude hiding (any, concat, mapM, mapM_, sequence)
79+debugPropagate :: Bool
81+debugInvalidateHeight :: Bool
83+debugInvalidate :: Bool
91+debugInvalidateHeight = False
93+debugInvalidate = True
95+class HasNodeId a where
96+ getNodeId :: a -> Int
98+instance HasNodeId (Hold x p a) where
99+ getNodeId = holdNodeId
101+instance HasNodeId (PushSubscribed x a b) where
102+ getNodeId = pushSubscribedNodeId
104+instance HasNodeId (SwitchSubscribed x a) where
105+ getNodeId = switchSubscribedNodeId
107+instance HasNodeId (MergeSubscribed x a) where
108+ getNodeId = mergeSubscribedNodeId
110+instance HasNodeId (FanSubscribed x a) where
111+ getNodeId = fanSubscribedNodeId
113+instance HasNodeId (CoincidenceSubscribed x a) where
114+ getNodeId = coincidenceSubscribedNodeId
116+instance HasNodeId (RootSubscribed x a) where
117+ getNodeId = rootSubscribedNodeId
119+instance HasNodeId (Pull x a) where
120+ getNodeId = pullNodeId
122+{-# INLINE showNodeId #-}
123+showNodeId :: HasNodeId a => a -> String
124+showNodeId = ("#"<>) . show . getNodeId
126+showSubscriberType :: Subscriber x a -> String
127+showSubscriberType = \case
128+ SubscriberPush _ _ -> "SubscriberPush"
129+ SubscriberMerge _ _ -> "SubscriberMerge"
130+ SubscriberFan _ -> "SubscriberFan"
131+ SubscriberMergeChange _ -> "SubscriberMergeChange"
132+ SubscriberHold _ -> "SubscriberHold"
133+ SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
134+ SubscriberSwitch _ -> "SubscriberSwitch"
135+ SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
136+ SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
137+ SubscriberHandle -> "SubscriberHandle"
139+showEventType :: Event x a -> String
140+showEventType = \case
141+ EventRoot _ _ -> "EventRoot"
142+ EventNever -> "EventNever"
143+ EventPush _ -> "EventPush"
144+ EventMerge _ -> "EventMerge"
145+ EventFan _ _ -> "EventFan"
146+ EventSwitch _ -> "EventSwitch"
147+ EventCoincidence _ -> "EventCoincidence"
148+ EventHold _ -> "EventHold"
149+ EventDyn _ -> "EventDyn"
150+ EventHoldIdentity _ -> "EventHoldIdentity"
151+ EventDynIdentity _ -> "EventDynIdentity"
155+debugPropagate = False
157+debugInvalidateHeight = False
159+debugInvalidate = False
161+-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
162+{-# INLINE showNodeId #-}
163+showNodeId :: a -> String
169+{-# NOINLINE nextNodeIdRef #-}
170+nextNodeIdRef :: IORef Int
171+nextNodeIdRef = unsafePerformIO $ newIORef 1
174+newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
176+{-# NOINLINE unsafeNodeId #-}
177+unsafeNodeId :: a -> Int
178+unsafeNodeId a = unsafePerformIO $ do
183+--------------------------------------------------------------------------------
185+--------------------------------------------------------------------------------
187+newtype Event x a = Event { subscribe :: Subscriber x a -> EventM x (EventSubscription x a) }
189+wrap :: Monad m => (t -> EventSubscribed x a) -> (Subscriber x a -> m (WeakBagTicket (Subscriber x a), t)) -> Subscriber x a -> m (EventSubscription x a)
190+wrap tag getSpecificSubscribed sub = do
191+ (sln, subd) <- getSpecificSubscribed sub
192+ return $ EventSubscription (Just sln) $ tag subd
194+eventRoot :: GCompare k => k a -> Root x k -> Event x a
195+eventRoot !k !r = Event $ wrap EventSubscribedRoot $ liftIO . getRootSubscribed k r
197+eventNever :: Event x a
198+eventNever = Event $ \_ -> return $ EventSubscription Nothing EventSubscribedNever
200+eventPush :: Push x b a -> Event x a
201+eventPush !p = Event $ wrap EventSubscribedPush $ getPushSubscribed p
203+eventMerge :: (GCompare k, a ~ DMap k Identity) => Merge x k -> Event x a
204+eventMerge !m = Event $ wrap EventSubscribedMerge $ getMergeSubscribed m
206+eventFan :: GCompare k => k a -> Fan x k -> Event x a
207+eventFan !k !f = Event $ wrap (EventSubscribedFan k) $ getFanSubscribed k f
209+eventSwitch :: Switch x a -> Event x a
210+eventSwitch !s = Event $ wrap EventSubscribedSwitch $ getSwitchSubscribed s
212+eventCoincidence :: Coincidence x a -> Event x a
213+eventCoincidence !c = Event $ wrap EventSubscribedCoincidence $ getCoincidenceSubscribed c
215+eventHold :: (a ~ p b, R.Patch p) => Hold x p b -> Event x a
216+eventHold !h = Event $ subscribeHoldEvent h
218+eventDyn :: (a ~ p b, R.Patch p) => Dyn x p b -> Event x a
219+eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
221+eventHoldIdentity :: (a ~ Identity b) => Hold x Identity b -> Event x a
222+eventHoldIdentity !h = Event $ subscribeHoldEvent h
224+eventDynIdentity :: (a ~ Identity b) => Dyn x Identity b -> Event x a
225+eventDynIdentity !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
227+{-# INLINE subscribeCoincidenceInner #-}
228+subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x a)
229+subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
230+ subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
231+ subscription@(EventSubscription _ innerSubd) <- subscribe inner subInner
232+ innerOcc <- liftIO $ readEventSubscribed innerSubd
233+ innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
234+ let height = max innerHeight outerHeight
235+ defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
236+ return (innerOcc, height, innerSubd)
238+--------------------------------------------------------------------------------
240+--------------------------------------------------------------------------------
242+data Subscriber x a = Subscriber
243+ { subscriberPropagate :: !(a -> EventM x ())
244+ , subscriberInvalidateHeight :: !(Height -> IO ())
245+ , subscriberRecalculateHeight :: !(Height -> IO ())
248+--TODO: Move this comment to WeakBag
249+-- These function are constructor functions that are marked NOINLINE so they are
250+-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
251+-- so any weak references that are attached to the constructors will have their
252+-- finalizer run. Using the opaque constructor, does not see the
253+-- constructor application, so it behaves like an IORef and cannot be fused away.
255+-- The result is also evaluated to WHNF, since forcing a thunk invalidates
256+-- the weak pointer to it in some cases.
258+newSubscriberPush :: (a -> ComputeM x (Maybe b)) -> PushSubscribed x a b -> IO (Subscriber x a)
259+newSubscriberPush compute subscribed = return $ Subscriber
260+ { subscriberPropagate = \a -> {-# SCC "traversePush" #-} do
261+ tracePropagate $ "SubscriberPush" <> showNodeId subscribed
262+ occ <- runComputeM $ compute a
264+ Nothing -> return () -- No need to write a Nothing back into the Ref
266+ liftIO $ writeIORef (pushSubscribedOccurrence subscribed) occ
267+ scheduleClear $ pushSubscribedOccurrence subscribed
268+ propagate o $ pushSubscribedSubscribers subscribed
269+ , subscriberInvalidateHeight = \old -> do
270+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
271+ WeakBag.traverse (pushSubscribedSubscribers subscribed) $ invalidateSubscriberHeight old
272+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
273+ , subscriberRecalculateHeight = \new -> do
274+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed
275+ WeakBag.traverse (pushSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
276+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberPush" <> showNodeId subscribed <> " done"
279+newSubscriberHold :: R.Patch p => Hold x p a -> IO (Subscriber x (p a))
280+newSubscriberHold h = return $ Subscriber
281+ { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
282+ , subscriberInvalidateHeight = \_ -> return ()
283+ , subscriberRecalculateHeight = \_ -> return ()
286+newSubscriberMerge :: GCompare k => k a -> MergeSubscribed x k -> IO (Subscriber x a)
287+newSubscriberMerge k subscribed = return $ Subscriber
288+ { subscriberPropagate = \a -> {-# SCC "traverseMerge" #-} do
289+ tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
290+ oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
291+ let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge" <> showNodeId subscribed) k (Identity a) oldM
292+ tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
293+ liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! newM
294+ when (DMap.null oldM) $ do -- Only schedule the firing once
295+ height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
296+ --TODO: assertions about height
297+ currentHeight <- getCurrentHeight
298+ when (height <= currentHeight) $ do
299+ myStack <- liftIO $ whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
300+ if height /= invalidHeight
301+ then error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
303+ nodesInvolvedInCycle <- walkInvalidHeightParents $ EventSubscribedMerge subscribed
304+ stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
305+ error $ "Causality loop found:\n" <> drawForest (listsToForest stacks)
306+ scheduleMerge height subscribed
307+ , subscriberInvalidateHeight = \old -> do
308+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
309+ removeMergeHeight old subscribed
310+ invalidateMergeHeight subscribed
311+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
312+ , subscriberRecalculateHeight = \new -> do
313+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
314+ addMergeHeight new subscribed
315+ revalidateMergeHeight subscribed
316+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
319+newSubscriberMergeChange :: GCompare k => MergeSubscribed x k -> IO (Subscriber x (R.PatchDMap (DMap k (Event x))))
320+newSubscriberMergeChange subscribed = return $ Subscriber
321+ { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
322+ tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
323+ defer $ SomeMergeUpdate a subscribed
324+ , subscriberInvalidateHeight = \_ -> return ()
325+ , subscriberRecalculateHeight = \_ -> return ()
328+newSubscriberFan :: GCompare k => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
329+newSubscriberFan subscribed = return $ Subscriber
330+ { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
331+ subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
332+ tracePropagate $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
333+ --TODO: We need a better DMap intersection; here, we are assuming that the number of firing keys is small and the number of subscribers is large
334+ forM_ (DMap.toList a) $ \(k :=> Identity v) -> {-# SCC "SubscriberFan" #-} case DMap.lookup k subs of
336+ tracePropagate "No subscriber for key"
339+ propagate v $ _fanSubscribedChildren_list subsubs
341+ , subscriberInvalidateHeight = \old -> do
342+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
343+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
344+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
345+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
346+ , subscriberRecalculateHeight = \new -> do
347+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
348+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
349+ forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
350+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
353+newSubscriberSwitch :: SwitchSubscribed x a -> IO (Subscriber x a)
354+newSubscriberSwitch subscribed = return $ Subscriber
355+ { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
356+ tracePropagate $ "SubscriberSwitch" <> showNodeId subscribed
357+ liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
358+ scheduleClear $ switchSubscribedOccurrence subscribed
359+ propagate a $ switchSubscribedSubscribers subscribed
360+ , subscriberInvalidateHeight = \_ -> do
361+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
362+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
363+ when (oldHeight /= invalidHeight) $ do
364+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
365+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
366+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
367+ , subscriberRecalculateHeight = \new -> do
368+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
369+ updateSwitchHeight new subscribed
370+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
373+newSubscriberCoincidenceOuter :: CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
374+newSubscriberCoincidenceOuter subscribed = return $ Subscriber
375+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
376+ tracePropagate $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
377+ outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
378+ tracePropagate $ " outerHeight = " <> show outerHeight
379+ (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
380+ tracePropagate $ " isJust occ = " <> show (isJust occ)
381+ tracePropagate $ " innerHeight = " <> show innerHeight
382+ liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
383+ scheduleClear $ coincidenceSubscribedInnerParent subscribed
386+ when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
387+ writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
388+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
389+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
390+ Just o -> do -- Since it's already firing, no need to adjust height
391+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
392+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
393+ propagate o $ coincidenceSubscribedSubscribers subscribed
394+ , subscriberInvalidateHeight = \_ -> do
395+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
396+ invalidateCoincidenceHeight subscribed
397+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
398+ , subscriberRecalculateHeight = \_ -> do
399+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
400+ recalculateCoincidenceHeight subscribed
401+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
404+newSubscriberCoincidenceInner :: CoincidenceSubscribed x a -> IO (Subscriber x a)
405+newSubscriberCoincidenceInner subscribed = return $ Subscriber
406+ { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
407+ tracePropagate $ "SubscriberCoincidenceInner" <> showNodeId subscribed
408+ occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
410+ Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
412+ liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
413+ scheduleClear $ coincidenceSubscribedOccurrence subscribed
414+ propagate a $ coincidenceSubscribedSubscribers subscribed
415+ , subscriberInvalidateHeight = \_ -> do
416+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
417+ invalidateCoincidenceHeight subscribed
418+ when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
419+ , subscriberRecalculateHeight = \_ -> do
420+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
421+ recalculateCoincidenceHeight subscribed
422+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
425+invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
426+invalidateSubscriberHeight = flip subscriberInvalidateHeight
428+recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
429+recalculateSubscriberHeight = flip subscriberRecalculateHeight
431+-- | Propagate everything at the current height
432+propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
433+propagate a subscribers = withIncreasedDepth $ do
434+ -- 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
435+ --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
436+ WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
438+--------------------------------------------------------------------------------
440+--------------------------------------------------------------------------------
442+data EventSubscribed x a
443+ = EventSubscribedRoot {-# NOUNPACK #-} (RootSubscribed x a)
444+ | EventSubscribedNever
445+ | forall b. EventSubscribedPush !(PushSubscribed x b a)
446+ | forall k. (GCompare k, a ~ DMap k Identity) => EventSubscribedMerge !(MergeSubscribed x k)
447+ | forall k. GCompare k => EventSubscribedFan !(k a) !(FanSubscribed x k)
448+ | EventSubscribedSwitch !(SwitchSubscribed x a)
449+ | EventSubscribedCoincidence !(CoincidenceSubscribed x a)
451+readEventSubscribed :: EventSubscribed x a -> IO (Maybe a)
452+readEventSubscribed = \case
453+ EventSubscribedRoot rs -> readRootSubscribed rs
454+ EventSubscribedNever -> return Nothing
455+ EventSubscribedPush ps -> readPushSubscribed ps
456+ EventSubscribedMerge ms -> readMergeSubscribed ms
457+ EventSubscribedFan k fs -> readFanSubscribed k fs
458+ EventSubscribedSwitch ss -> readSwitchSubscribed ss
459+ EventSubscribedCoincidence cs -> readCoincidenceSubscribed cs
461+{-# INLINE subscribeEventSubscribed #-}
462+subscribeEventSubscribed :: EventSubscribed x a -> Subscriber x a -> IO (Maybe (WeakBagTicket (Subscriber x a)))
463+subscribeEventSubscribed es sub = case es of
464+ EventSubscribedRoot r -> do
465+ traceSubscribe $ "subscribeEventSubscribed Root"
466+ Just <$> subscribeRootSubscribed r sub
467+ EventSubscribedNever -> do
468+ traceSubscribe $ "subscribeEventSubscribed Never"
470+ EventSubscribedPush subscribed -> do
471+ traceSubscribe $ "subscribeEventSubscribed Push"
472+ Just <$> subscribePushSubscribed subscribed sub
473+ EventSubscribedFan k subscribed -> do
474+ traceSubscribe $ "subscribeEventSubscribed Fan"
475+ Just <$> subscribeFanSubscribed k subscribed sub
476+ EventSubscribedMerge subscribed -> do
477+ traceSubscribe $ "subscribeEventSubscribed Merge"
478+ Just <$> subscribeMergeSubscribed subscribed sub
479+ EventSubscribedSwitch subscribed -> do
480+ traceSubscribe $ "subscribeEventSubscribed Switch"
481+ Just <$> subscribeSwitchSubscribed subscribed sub
482+ EventSubscribedCoincidence subscribed -> do
483+ traceSubscribe $ "subscribeEventSubscribed Coincidence"
484+ Just <$> subscribeCoincidenceSubscribed subscribed sub
486+{-# INLINE eventSubscribedGetParents #-}
487+eventSubscribedGetParents :: EventSubscribed x a -> IO [Some (EventSubscribed x)]
488+eventSubscribedGetParents = \case
489+ EventSubscribedRoot _ -> return []
490+ EventSubscribedNever -> return []
491+ EventSubscribedPush subscribed -> return [Some.This $ _eventSubscription_subscribed $ pushSubscribedParent subscribed]
492+ EventSubscribedFan _ subscribed -> return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
493+ EventSubscribedMerge subscribed -> do
494+ ps <- readIORef $ mergeSubscribedParents subscribed
495+ return $ R.ffor (DMap.toList ps) $ \(_ :=> v) -> Some.This $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription v
496+ EventSubscribedSwitch subscribed -> do
497+ s <- readIORef $ switchSubscribedCurrentParent subscribed
498+ return [Some.This $ _eventSubscription_subscribed s]
499+ EventSubscribedCoincidence subscribed -> do
500+ innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
501+ let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
502+ innerParents = maybeToList $ fmap Some.This innerSubscription
503+ return $ outerParent : innerParents
505+getEventSubscribedHeight :: EventSubscribed x a -> IO Height
506+getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
508+{-# INLINE eventSubscribedHeightRef #-}
509+eventSubscribedHeightRef :: EventSubscribed x a -> IORef Height
510+eventSubscribedHeightRef = \case
511+ EventSubscribedRoot _ -> zeroRef
512+ EventSubscribedNever -> zeroRef
513+ EventSubscribedPush subscribed -> pushSubscribedHeight subscribed
514+ EventSubscribedFan _ subscribed -> eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
515+ EventSubscribedMerge subscribed -> mergeSubscribedHeight subscribed
516+ EventSubscribedSwitch subscribed -> switchSubscribedHeight subscribed
517+ EventSubscribedCoincidence subscribed -> coincidenceSubscribedHeight subscribed
519+whoCreatedEventSubscribed :: EventSubscribed x a -> IO [String]
520+whoCreatedEventSubscribed = \case
521+ EventSubscribedRoot _ -> return ["root"]
522+ EventSubscribedNever -> return ["never"]
523+ EventSubscribedPush subscribed -> whoCreatedIORef $ pushSubscribedCachedSubscribed subscribed
524+ EventSubscribedFan _ subscribed -> whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
525+ EventSubscribedMerge subscribed -> whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
526+ EventSubscribedSwitch subscribed -> whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
527+ EventSubscribedCoincidence subscribed -> whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
529+{-# INLINE eventSubscribedHasOwnHeightRef #-}
530+eventSubscribedHasOwnHeightRef :: EventSubscribed x a -> Bool
531+eventSubscribedHasOwnHeightRef = \case
532+ EventSubscribedRoot _ -> False
533+ EventSubscribedNever -> False
534+ EventSubscribedPush _ -> False
535+ EventSubscribedFan _ _ -> False
536+ EventSubscribedMerge _ -> True
537+ EventSubscribedSwitch _ -> True
538+ EventSubscribedCoincidence _ -> True
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+ liftIO $ writeIORef subscriptionRef $! subscription
716+ occ <- liftIO $ readEventSubscribed subd
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 traceSubscribe #-}
1196+traceSubscribe :: String -> IO ()
1197+traceSubscribe = when debugSubscribe . liftIO . putStrLn
1199+{-# INLINE traceInvalidate #-}
1200+traceInvalidate :: String -> IO ()
1201+traceInvalidate = when debugInvalidate . liftIO . putStrLn
1203+{-# INLINE traceWhen #-}
1204+traceWhen :: (CanTrace x m) => Bool -> String -> m ()
1205+traceWhen b message = traceMWhen b $ return message
1207+{-# INLINE traceMWhen #-}
1208+traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
1209+traceMWhen b getMessage = when b $ do
1210+ message <- getMessage
1212+ spiderEnv <- askSpiderEnv
1213+ d <- liftIO $ readIORef $ _spiderEnv_depth spiderEnv
1217+ liftIO $ putStrLn $ replicate d ' ' <> message
1219+whoCreatedIORef :: IORef a -> IO [String]
1220+whoCreatedIORef (IORef a) = whoCreated $! a
1222+groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1225+ (x :| xs) : t -> case groupByHead t of
1226+ [] -> [(x, xs :| [])]
1228+ | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1229+ | otherwise -> (x, xs :| []) : l
1231+listsToForest :: Eq a => [[a]] -> Forest a
1232+listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1234+{-# INLINE propagateSubscriberHold #-}
1235+propagateSubscriberHold :: R.Patch p => Hold x p a -> p a -> EventM x ()
1236+propagateSubscriberHold h a = do
1237+ {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1238+ invalidators <- liftIO $ readIORef $ holdInvalidators h
1239+ return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1240+ v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1241+ case {-# SCC "apply" #-} R.apply a v of
1242+ Nothing -> return ()
1244+ {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1245+ vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1246+ iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1247+ defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1249+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
1251+{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> BehaviorM x a #-}
1252+{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> EventM x a #-}
1253+readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
1254+readBehaviorUntracked b = do
1255+ holdInits <- getDeferralQueue
1256+ liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
1258+runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1259+runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1261+askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1263+ (!m, _) <- BehaviorM ask
1265+ Nothing -> return Nothing
1266+ Just (!wi, _) -> return $ Just wi
1268+askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1270+ (!m, _) <- BehaviorM ask
1272+ Nothing -> return Nothing
1273+ Just (_, !p) -> return $ Just p
1275+askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1276+askBehaviorHoldInits = do
1277+ (_, !his) <- BehaviorM ask
1280+readBehaviorTracked :: Behavior x a -> BehaviorM x a
1281+readBehaviorTracked b = case b of
1282+ BehaviorHold h -> readHoldTracked h
1283+ BehaviorHoldIdentity h -> readHoldTracked h
1284+ BehaviorConst a -> return a
1285+ BehaviorPull p -> do
1286+ val <- liftIO $ readIORef $ pullValue p
1288+ Just subscribed -> do
1289+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1290+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
1291+ liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
1292+ return $ pullSubscribedValue subscribed
1294+ i <- liftIO $ newInvalidatorPull p
1295+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
1296+ parentsRef <- liftIO $ newIORef []
1297+ holdInits <- askBehaviorHoldInits
1298+ a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
1299+ invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
1300+ parents <- liftIO $ readIORef parentsRef
1301+ let subscribed = PullSubscribed
1302+ { pullSubscribedValue = a
1303+ , pullSubscribedInvalidators = invsRef
1304+ , pullSubscribedOwnInvalidator = i
1305+ , pullSubscribedParents = parents
1307+ liftIO $ writeIORef (pullValue p) $ Just subscribed
1308+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
1310+ BehaviorDyn d -> readHoldTracked =<< getDynHold d
1311+ BehaviorDynIdentity d -> readHoldTracked =<< getDynHold d
1313+{-# INLINE readHoldTracked #-}
1314+readHoldTracked :: Hold x p a -> BehaviorM x a
1315+readHoldTracked h = do
1316+ result <- liftIO $ readIORef $ holdValue h
1317+ askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
1318+ askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
1321+{-# INLINE getDynHold #-}
1322+getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p a -> m (Hold x p a)
1324+ mh <- liftIO $ readIORef $ unDyn d
1326+ Right h -> return h
1327+ Left (readV0, v') -> do
1328+ holdInits <- getDeferralQueue
1329+ v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1331+ liftIO $ writeIORef (unDyn d) $ Right h
1334+readRootSubscribed :: RootSubscribed x a -> IO (Maybe a)
1335+readRootSubscribed = rootSubscribedOccurrence
1337+readPushSubscribed :: PushSubscribed x b a -> IO (Maybe a)
1338+readPushSubscribed subscribed = do
1339+ result <- readIORef $ pushSubscribedOccurrence subscribed -- Since ResultM is always called after the final height is reached, this will always be valid
1340+ touch $ pushSubscribedSelf subscribed
1343+readMergeSubscribed :: MergeSubscribed x k -> IO (Maybe (DMap k Identity))
1344+readMergeSubscribed subscribed = do
1345+ result <- readIORef $ mergeSubscribedOccurrence subscribed
1346+ touch $ mergeSubscribedParents subscribed
1349+readFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> IO (Maybe a)
1350+readFanSubscribed k fs = do
1351+ parentOcc <- readEventSubscribed $ _eventSubscription_subscribed $ fanSubscribedParent fs
1352+ return $ coerce $ DMap.lookup k =<< parentOcc
1354+readSwitchSubscribed :: SwitchSubscribed x a -> IO (Maybe a)
1355+readSwitchSubscribed subscribed = do
1356+ result <- readIORef $ switchSubscribedOccurrence subscribed
1357+ touch $ switchSubscribedOwnInvalidator subscribed
1360+readCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO (Maybe a)
1361+readCoincidenceSubscribed subscribed = do
1362+ result <- readIORef $ coincidenceSubscribedOccurrence subscribed
1363+ touch $ coincidenceSubscribedOuter subscribed
1364+ --TODO: do we need to touch the inner subscriber?
1367+-- Always refers to 0
1368+{-# NOINLINE zeroRef #-}
1369+zeroRef :: IORef Height
1370+zeroRef = unsafePerformIO $ newIORef zeroHeight
1372+{-# INLINE debugSubscribe #-}
1373+debugSubscribe :: Bool
1374+debugSubscribe = False
1376+type CanSubscribe x m =
1378+ , HasCurrentHeight x m
1379+ , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1380+ , Defer SomeClear m -- Wiping out event firings
1381+ , Defer (SomeAssignment x) m -- Updating state
1382+ , Defer (SomeResetCoincidence x) m
1386+getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a), RootSubscribed x a)
1387+getRootSubscribed k r sub = do
1388+ mSubscribed <- readIORef $ rootSubscribed r
1389+ case DMap.lookup k mSubscribed of
1390+ Just subscribed -> {-# SCC "hitRoot" #-} do
1391+ sln <- subscribeRootSubscribed subscribed sub
1392+ return (sln, subscribed)
1393+ Nothing -> {-# SCC "missRoot" #-} do
1394+ weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1395+ let !cached = rootSubscribed r
1396+ uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1397+ (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1398+ when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1399+ uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1400+ writeIORef uninitRef $! uninit
1401+ let subscribed = RootSubscribed
1402+ { rootSubscribedKey = k
1403+ , rootSubscribedCachedSubscribed = cached
1404+ , rootSubscribedOccurrence = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1405+ , rootSubscribedSubscribers = subs
1406+ , rootSubscribedUninit = uninit
1407+ , rootSubscribedWeakSelf = weakSelf
1408+#ifdef DEBUG_NODEIDS
1409+ , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1412+ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1413+ 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
1414+ return (sln, subscribed)
1416+{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1417+cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1418+cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1419+ rootSubscribedUninit self
1420+ modifyIORef' cached $ DMap.delete k
1422+{-# INLINE subscribeRootSubscribed #-}
1423+subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1424+subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1426+-- When getPushSubscribed returns, the PushSubscribed returned will have a fully filled-in
1427+{-# SPECIALIZE getPushSubscribed :: Push x a b -> Subscriber x b -> EventM x (WeakBagTicket (Subscriber x b), PushSubscribed x a b) #-}
1428+getPushSubscribed :: CanSubscribe x m => Push x a b -> Subscriber x b -> m (WeakBagTicket (Subscriber x b), PushSubscribed x a b)
1429+getPushSubscribed p sub = do
1430+ mSubscribed <- liftIO $ readIORef $ pushSubscribed p
1431+ case mSubscribed of
1432+ Just subscribed -> {-# SCC "hitPush" #-} do
1433+ sln <- liftIO $ subscribePushSubscribed subscribed sub
1434+ return (sln, subscribed)
1435+ Nothing -> {-# SCC "missPush" #-} do -- Not yet subscribed
1436+ subscribedRef <- liftIO $ newIORef $ error "getPushSubscribed: subscribed not yet intialized"
1437+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1438+ s <- liftIO $ newSubscriberPush (pushCompute p) subscribedUnsafe
1439+ subscription@(EventSubscription _ subd) <- subscribe (pushParent p) s
1440+ parentOcc <- liftIO $ readEventSubscribed subd
1441+ occ <- runComputeM $ join <$> mapM (pushCompute p) parentOcc
1442+ occRef <- liftIO $ newIORef occ
1443+ when (isJust occ) $ scheduleClear occRef
1444+ weakSelf <- liftIO $ newIORef $ error "getPushSubscribed: weakSelf not initialized"
1445+ let !cached = pushSubscribed p
1446+ (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupPushSubscribed
1447+ let subscribed = PushSubscribed
1448+ { pushSubscribedCachedSubscribed = cached
1449+ , pushSubscribedOccurrence = occRef
1450+ , pushSubscribedHeight = eventSubscribedHeightRef subd -- Since pushes have the same height as their parents, share the ref
1451+ , pushSubscribedSubscribers = subs
1452+ , pushSubscribedSelf = s
1453+ , pushSubscribedWeakSelf = weakSelf
1454+ , pushSubscribedParent = subscription
1455+#ifdef DEBUG_NODEIDS
1456+ , pushSubscribedNodeId = unsafeNodeId p
1459+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
1460+ liftIO $ writeIORef subscribedRef $! subscribed
1461+ liftIO $ writeIORef (pushSubscribed p) $ Just subscribed
1462+ return (sln, subscribed)
1464+cleanupPushSubscribed :: PushSubscribed x a b -> IO ()
1465+cleanupPushSubscribed self = do
1466+ unsubscribe $ pushSubscribedParent self
1467+ writeIORef (pushSubscribedCachedSubscribed self) $ Nothing
1469+{-# INLINE subscribePushSubscribed #-}
1470+subscribePushSubscribed :: PushSubscribed x a b -> Subscriber x b -> IO (WeakBagTicket (Subscriber x b))
1471+subscribePushSubscribed subscribed sub = WeakBag.insert sub (pushSubscribedSubscribers subscribed) (pushSubscribedWeakSelf subscribed) cleanupPushSubscribed
1473+{-# SPECIALIZE getMergeSubscribed :: GCompare k => Merge x k -> Subscriber x (DMap k Identity) -> EventM x (WeakBagTicket (Subscriber x (DMap k Identity)), MergeSubscribed x k) #-}
1474+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)
1475+getMergeSubscribed m sub = do
1476+ mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
1477+ case mSubscribed of
1478+ Just subscribed -> {-# SCC "hitMerge" #-} do
1479+ sln <- liftIO $ subscribeMergeSubscribed subscribed sub
1480+ return (sln, subscribed)
1481+ Nothing -> {-# SCC "missMerge" #-} do
1482+ subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
1483+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1484+ initialParents <- readBehaviorUntracked $ current $ mergeParents m
1485+ subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x k))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1486+ s <- liftIO $ newSubscriberMerge k subscribedUnsafe
1487+ subscription@(EventSubscription _ parentSubd) <- subscribe e s
1488+ parentOcc <- liftIO $ readEventSubscribed parentSubd
1489+ height <- liftIO $ getEventSubscribedHeight parentSubd
1490+ return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription s)
1491+ let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1492+ heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1493+ myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1494+ myHeight = if invalidHeight `elem` heights
1496+ else succHeight $ heightBagMax myHeightBag
1497+ currentHeight <- getCurrentHeight
1498+ let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1499+ then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1501+ unless (DMap.null accum) $ do
1502+ scheduleMerge myHeight subscribedUnsafe
1503+ occRef <- liftIO $ newIORef occ
1504+ when (isJust occ) $ scheduleClear occRef
1505+ accumRef <- liftIO $ newIORef accum
1506+ heightRef <- liftIO $ newIORef myHeight
1507+ heightMapRef <- liftIO $ newIORef myHeightBag
1508+ weakSelf <- liftIO $ newIORef $ error "getMergeSubscribed: weakSelf not yet initialized"
1509+ (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupMergeSubscribed
1510+ changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1511+ parentsRef <- liftIO $ newIORef $ DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1512+ let !subscribed = MergeSubscribed
1513+ { mergeSubscribedCachedSubscribed = mergeSubscribed m
1514+ , mergeSubscribedOccurrence = occRef
1515+ , mergeSubscribedAccum = accumRef
1516+ , mergeSubscribedHeight = heightRef
1517+ , mergeSubscribedHeightBag = heightMapRef
1518+ , mergeSubscribedSubscribers = subs
1519+ , mergeSubscribedChange = changeSubdRef
1520+ , mergeSubscribedParents = parentsRef
1521+ , mergeSubscribedWeakSelf = weakSelf
1522+#ifdef DEBUG_NODEIDS
1523+ , mergeSubscribedNodeId = unsafeNodeId m
1526+ defer $ SomeMergeInit subscribed $ updated $ mergeParents m
1527+ liftIO $ writeIORef subscribedRef $! subscribed
1528+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "MergeSubscribed"
1529+ liftIO $ writeIORef (mergeSubscribed m) $ Just subscribed
1530+ return (sln, subscribed)
1532+cleanupMergeSubscribed :: MergeSubscribed x k -> IO ()
1533+cleanupMergeSubscribed subscribed = do
1534+ parents <- readIORef $ mergeSubscribedParents subscribed
1535+ forM_ (DMap.toList parents) $ \(_ :=> msp) -> unsubscribe $ mergeSubscribedParentSubscription msp
1536+ -- Not necessary, because this whole MergeSubscribed is dead: writeIORef (mergeSubscribedParents subscribed) DMap.empty
1537+ writeIORef (mergeSubscribedCachedSubscribed subscribed) $ Nothing -- Get rid of the cached subscribed
1539+{-# INLINE subscribeMergeSubscribed #-}
1540+subscribeMergeSubscribed :: MergeSubscribed x k -> Subscriber x (DMap k Identity) -> IO (WeakBagTicket (Subscriber x (DMap k Identity)))
1541+subscribeMergeSubscribed subscribed sub = WeakBag.insert sub (mergeSubscribedSubscribers subscribed) (mergeSubscribedWeakSelf subscribed) cleanupMergeSubscribed
1543+{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), FanSubscribed x k) #-}
1544+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)
1545+getFanSubscribed k f sub = do
1546+ mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1547+ case mSubscribed of
1548+ Just subscribed -> {-# SCC "hitFan" #-} do
1549+ sln <- liftIO $ subscribeFanSubscribed k subscribed sub
1550+ return (sln, subscribed)
1551+ Nothing -> {-# SCC "missFan" #-} do
1552+ subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1553+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1554+ s <- liftIO $ newSubscriberFan subscribedUnsafe
1555+ subscription <- subscribe (fanParent f) s
1556+ weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1557+ (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1558+ subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1559+ let subscribed = FanSubscribed
1560+ { fanSubscribedCachedSubscribed = fanSubscribed f
1561+ , fanSubscribedParent = subscription
1562+ , fanSubscribedSubscribers = subscribersRef
1563+#ifdef DEBUG_NODEIDS
1564+ , fanSubscribedNodeId = unsafeNodeId f
1567+ let !self = (k, subscribed)
1568+ liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1569+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1570+ liftIO $ writeIORef subscribedRef $! subscribed
1571+ liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1572+ return (slnForSub, subscribed)
1574+cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1575+cleanupFanSubscribed (k, subscribed) = do
1576+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1577+ let reducedSubscribers = DMap.delete k subscribers
1578+ if DMap.null reducedSubscribers
1580+ unsubscribe $ fanSubscribedParent subscribed
1581+ -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1582+ writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1583+ else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1585+{-# INLINE subscribeFanSubscribed #-}
1586+subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1587+subscribeFanSubscribed k subscribed sub = do
1588+ subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1589+ case DMap.lookup k subscribers of
1590+ Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1591+ let !self = (k, subscribed)
1592+ weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1593+ (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1594+ 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
1596+ Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1598+{-# SPECIALIZE getSwitchSubscribed :: Switch x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), SwitchSubscribed x a) #-}
1599+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)
1600+getSwitchSubscribed s sub = do
1601+ mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1602+ case mSubscribed of
1603+ Just subscribed -> {-# SCC "hitSwitch" #-} do
1604+ sln <- liftIO $ subscribeSwitchSubscribed subscribed sub
1605+ return (sln, subscribed)
1606+ Nothing -> {-# SCC "missSwitch" #-} do
1607+ subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1608+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1609+ i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1610+ mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1611+ wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1612+ wiRef <- liftIO $ newIORef wi
1613+ parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1614+ holdInits <- getDeferralQueue
1615+ e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1616+ subscription@(EventSubscription _ subd) <- subscribe e mySub
1617+ subscriptionRef <- liftIO $ newIORef subscription
1618+ parentOcc <- liftIO $ readEventSubscribed subd
1619+ occRef <- liftIO $ newIORef parentOcc
1620+ when (isJust parentOcc) $ scheduleClear occRef
1621+ heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1622+ weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1623+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1624+ let !subscribed = SwitchSubscribed
1625+ { switchSubscribedCachedSubscribed = switchSubscribed s
1626+ , switchSubscribedOccurrence = occRef
1627+ , switchSubscribedHeight = heightRef
1628+ , switchSubscribedSubscribers = subs
1629+ , switchSubscribedOwnInvalidator = i
1630+ , switchSubscribedOwnWeakInvalidator = wiRef
1631+ , switchSubscribedBehaviorParents = parentsRef
1632+ , switchSubscribedParent = switchParent s
1633+ , switchSubscribedCurrentParent = subscriptionRef
1634+ , switchSubscribedWeakSelf = weakSelf
1635+#ifdef DEBUG_NODEIDS
1636+ , switchSubscribedNodeId = unsafeNodeId s
1639+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1640+ liftIO $ writeIORef subscribedRef $! subscribed
1641+ liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1642+ return (slnForSub, subscribed)
1644+cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1645+cleanupSwitchSubscribed subscribed = do
1646+ unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1647+ finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1648+ writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1650+{-# INLINE subscribeSwitchSubscribed #-}
1651+subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1652+subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1654+{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket (Subscriber x a), CoincidenceSubscribed x a) #-}
1655+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)
1656+getCoincidenceSubscribed c sub = do
1657+ mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1658+ case mSubscribed of
1659+ Just subscribed -> {-# SCC "hitCoincidence" #-} do
1660+ sln <- liftIO $ subscribeCoincidenceSubscribed subscribed sub
1661+ return (sln, subscribed)
1662+ Nothing -> {-# SCC "missCoincidence" #-} do
1663+ subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1664+ subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1665+ subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1666+ outerSubscription@(EventSubscription _ outerSubd) <- subscribe (coincidenceParent c) subOuter
1667+ outerOcc <- liftIO $ readEventSubscribed outerSubd
1668+ outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1669+ (occ, height, mInnerSubd) <- case outerOcc of
1670+ Nothing -> return (Nothing, outerHeight, Nothing)
1672+ (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1673+ return (occ, height, Just innerSubd)
1674+ occRef <- liftIO $ newIORef occ
1675+ when (isJust occ) $ scheduleClear occRef
1676+ heightRef <- liftIO $ newIORef height
1677+ innerSubdRef <- liftIO $ newIORef mInnerSubd
1678+ scheduleClear innerSubdRef
1679+ weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1680+ (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1681+ let subscribed = CoincidenceSubscribed
1682+ { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1683+ , coincidenceSubscribedOccurrence = occRef
1684+ , coincidenceSubscribedHeight = heightRef
1685+ , coincidenceSubscribedSubscribers = subs
1686+ , coincidenceSubscribedOuter = subOuter
1687+ , coincidenceSubscribedOuterParent = outerSubscription
1688+ , coincidenceSubscribedInnerParent = innerSubdRef
1689+ , coincidenceSubscribedWeakSelf = weakSelf
1690+#ifdef DEBUG_NODEIDS
1691+ , coincidenceSubscribedNodeId = unsafeNodeId c
1694+ liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1695+ liftIO $ writeIORef subscribedRef $! subscribed
1696+ liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1697+ return (slnForSub, subscribed)
1699+cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1700+cleanupCoincidenceSubscribed subscribed = do
1701+ unsubscribe $ coincidenceSubscribedOuterParent subscribed
1702+ writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1704+{-# INLINE subscribeCoincidenceSubscribed #-}
1705+subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO (WeakBagTicket (Subscriber x a))
1706+subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1708+{-# INLINE merge #-}
1709+merge :: GCompare k => Dynamic x R.PatchDMap (DMap k (Event x)) -> Event x (DMap k Identity)
1710+merge m = eventMerge $ Merge
1712+ , mergeSubscribed = unsafeNewIORef m Nothing
1715+newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1717+fan :: GCompare k => Event x (DMap k Identity) -> EventSelector x k
1721+ , fanSubscribed = unsafeNewIORef e Nothing
1723+ in EventSelector $ \k -> eventFan k f
1725+runHoldInits :: IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1726+runHoldInits holdInitRef mergeInitRef = do
1727+ holdInits <- liftIO $ readIORef holdInitRef
1728+ mergeInits <- liftIO $ readIORef mergeInitRef
1729+ unless (null holdInits && null mergeInits) $ do
1730+ liftIO $ writeIORef holdInitRef []
1731+ liftIO $ writeIORef mergeInitRef []
1732+ mapM_ initHold holdInits
1733+ mapM_ initMerge mergeInits
1734+ runHoldInits holdInitRef mergeInitRef
1736+initHold :: SomeHoldInit x -> EventM x ()
1737+initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1739+initMerge :: SomeMergeInit x -> EventM x ()
1740+initMerge (SomeMergeInit subscribed changed) = do
1741+ changeSub <- liftIO $ newSubscriberMergeChange subscribed
1742+ EventSubscription _ changeSubd <- subscribe changed changeSub
1743+ change <- liftIO $ readEventSubscribed changeSubd
1744+ forM_ change $ \c -> defer $ SomeMergeUpdate c subscribed
1745+ liftIO $ writeIORef (mergeSubscribedChange subscribed) (changeSub, changeSubd)
1747+-- | Run an event action outside of a frame
1748+runFrame :: forall x a. EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1749+runFrame a = SpiderHost $ ask >>= \spiderEnv -> lift $ do
1750+ -- 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
1751+ pendingCleanups <- atomicModifyIORef (_spiderEnv_cleanups spiderEnv) $ \x -> ([], x)
1752+ {-# SCC "cleanups" #-} sequence_ pendingCleanups
1753+ toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1754+ holdInitRef <- newIORef []
1755+ mergeUpdateRef <- newIORef []
1756+ mergeInitRef <- newIORef []
1757+ heightRef <- newIORef zeroHeight
1758+ toClearRef <- newIORef []
1759+ toClearRootRef <- newIORef []
1760+ coincidenceInfosRef <- newIORef []
1761+ delayedRef <- liftIO $ newIORef IntMap.empty
1762+ let env = EventEnv spiderEnv toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1765+ 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
1767+ result <- runEventM go env
1768+ toClear <- readIORef toClearRef
1769+ forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1770+ toClearRoot <- readIORef toClearRootRef
1771+ forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1772+ toAssign <- readIORef toAssignRef
1773+ toReconnectRef <- newIORef []
1774+ coincidenceInfos <- readIORef coincidenceInfosRef
1775+ forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1777+ when debugInvalidate $ putStrLn $ "Invalidating Hold"
1778+ writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1779+ mergeUpdates <- readIORef mergeUpdateRef
1780+ writeIORef mergeUpdateRef []
1781+ let updateMerge :: SomeMergeUpdate x -> IO [SomeEventSubscription x]
1782+ updateMerge (SomeMergeUpdate (R.PatchDMap p :: R.PatchDMap (DMap k (Event x))) m) = do
1783+ oldParents <- readIORef $ mergeSubscribedParents m
1784+ let f (subscriptionsToKill, ps) (k :=> Compose me) = do
1785+ (mOldSubd, newPs) <- case me of
1786+ Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1788+ s <- liftIO $ newSubscriberMerge k m
1789+ subscription@(EventSubscription _ subd) <- subscribe e s
1790+ let newParent = MergeSubscribedParent subscription s
1791+ newParentHeight <- liftIO $ getEventSubscribedHeight subd
1792+ liftIO $ addMergeHeight newParentHeight m
1793+ return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1794+ forM_ mOldSubd $ \oldSubd -> do
1795+ oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription oldSubd
1796+ liftIO $ removeMergeHeight oldHeight m
1797+ return (maybeToList (SomeEventSubscription . mergeSubscribedParentSubscription <$> mOldSubd) ++ subscriptionsToKill, newPs)
1798+ (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
1799+ writeIORef (mergeSubscribedParents m) $! newParents
1800+ return subscriptionsToKill
1801+ when debugPropagate $ putStrLn "Updating merges"
1802+ mergeSubscriptionsToKill <- concat <$> mapM updateMerge mergeUpdates
1803+ when debugPropagate $ putStrLn "Updating merges done"
1804+ toReconnect <- readIORef toReconnectRef
1805+ switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1806+ oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1807+ wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1808+ when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1810+ i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1811+ wi' <- mkWeakPtrWithDebug i "wi'"
1812+ writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1813+ writeIORef (switchSubscribedBehaviorParents subscribed) []
1814+ writeIORef holdInitRef [] --TODO: Should we reuse this?
1815+ e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) holdInitRef
1816+ 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
1817+ --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1818+ sub <- newSubscriberSwitch subscribed
1819+ 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
1821+ stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1822+ liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1823+ EventRoot _ -> "EventRoot"
1824+ EventNever -> "EventNever"
1825+ _ -> "something else"
1827+ writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1828+ return $ SomeEventSubscription oldSubscription
1829+ forM_ mergeSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1830+ forM_ switchSubscriptionsToKill $ \(SomeEventSubscription oldSubscription) -> liftIO $ unsubscribe oldSubscription
1831+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1832+ EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1833+ parentHeight <- getEventSubscribedHeight subd'
1834+ myHeight <- readIORef $ switchSubscribedHeight subscribed
1835+ when (parentHeight /= myHeight) $ do
1836+ writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1837+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1838+ forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> do
1839+ 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
1840+ forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1841+ unsubscribe subscription
1842+ mapM_ invalidateCoincidenceHeight mcs
1843+ forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1844+ forM_ mergeUpdates $ \(SomeMergeUpdate _ m) -> revalidateMergeHeight m
1845+ forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1846+ height <- calculateSwitchHeight subscribed
1847+ updateSwitchHeight height subscribed
1850+newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1852+{-# INLINE zeroHeight #-}
1853+zeroHeight :: Height
1854+zeroHeight = Height 0
1856+{-# INLINE invalidHeight #-}
1857+invalidHeight :: Height
1858+invalidHeight = Height (-1000)
1860+-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1861+{-# INLINE invalidHeightBeingTraversed #-}
1862+invalidHeightBeingTraversed :: Height
1863+invalidHeightBeingTraversed = Height (-1001)
1865+{-# INLINE succHeight #-}
1866+succHeight :: Height -> Height
1867+succHeight h@(Height a) =
1868+ if h == invalidHeight
1870+ else Height $ succ a
1872+removeMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1873+removeMergeHeight oldParentHeight subscribed = do
1874+ when debugInvalidateHeight $ putStrLn $ "removeMergeHeight: " <> show oldParentHeight <> " Merge" <> showNodeId subscribed
1875+ oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1876+ let newHeights = heightBagRemove oldParentHeight oldHeights
1877+ writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1879+invalidateMergeHeight :: MergeSubscribed x k -> IO ()
1880+invalidateMergeHeight subscribed = do
1881+ oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1882+ -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1883+ when (oldHeight /= invalidHeight) $ do
1884+ writeIORef (mergeSubscribedHeight subscribed) $! invalidHeight
1885+ WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1887+addMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1888+addMergeHeight newParentHeight subscribed = do
1889+ when debugInvalidateHeight $ putStrLn $ "addMergeHeight: " <> show newParentHeight <> " Merge" <> showNodeId subscribed
1890+ oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1891+ let newHeights = heightBagAdd newParentHeight oldHeights
1892+ writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1894+revalidateMergeHeight :: MergeSubscribed x k -> IO ()
1895+revalidateMergeHeight subscribed = do
1896+ currentHeight <- readIORef $ mergeSubscribedHeight subscribed
1897+ when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1898+ heights <- readIORef $ mergeSubscribedHeightBag subscribed
1899+ parents <- readIORef $ mergeSubscribedParents subscribed
1900+ -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1901+ case heightBagSize heights `compare` DMap.size parents of
1904+ let height = succHeight $ heightBagMax heights
1905+ when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1906+ writeIORef (mergeSubscribedHeight subscribed) $! height
1907+ WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1908+ GT -> error $ "revalidateMergeHeight: more heights than parents for Merge" <> showNodeId subscribed
1910+invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1911+invalidateCoincidenceHeight subscribed = do
1912+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1913+ when (oldHeight /= invalidHeight) $ do
1914+ writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1915+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1917+updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1918+updateSwitchHeight new subscribed = do
1919+ oldHeight <- readIORef $ switchSubscribedHeight subscribed
1920+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1921+ when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1922+ writeIORef (switchSubscribedHeight subscribed) $! new
1923+ WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1925+recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1926+recalculateCoincidenceHeight subscribed = do
1927+ oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1928+ when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1929+ height <- calculateCoincidenceHeight subscribed
1930+ when (height /= invalidHeight) $ do
1931+ writeIORef (coincidenceSubscribedHeight subscribed) $! height
1932+ WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1934+calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1935+calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1937+calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1938+calculateCoincidenceHeight subscribed = do
1939+ outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1940+ innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1941+ return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1943+data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1945+invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1946+invalidate toReconnectRef wis = do
1947+ forM_ wis $ \wi -> do
1951+ traceInvalidate "invalidate Dead"
1952+ return () --TODO: Should we clean this up here?
1954+ finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1956+ InvalidatorPull p -> do
1957+ traceInvalidate $ "invalidate: Pull" <> showNodeId p
1958+ mVal <- readIORef $ pullValue p
1959+ forM_ mVal $ \val -> do
1960+ writeIORef (pullValue p) Nothing
1961+ writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1962+ InvalidatorSwitch subscribed -> do
1963+ traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1964+ modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1965+ 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
1967+--------------------------------------------------------------------------------
1968+-- Reflex integration
1969+--------------------------------------------------------------------------------
1971+-- | The default, global Spider environment
1972+type Spider = SpiderEnv Global
1974+-- | Designates the default, global Spider timeline
1977+{-# NOINLINE globalSpiderEnv #-}
1978+globalSpiderEnv :: SpiderEnv Global
1979+globalSpiderEnv = unsafePerformIO unsafeNewSpiderEnv
1981+-- | Stores all global data relevant to a particular Spider timeline; only one
1982+-- value should exist for each type @x@
1983+data SpiderEnv x = SpiderEnv
1984+ { _spiderEnv_toUnsubscribe :: !(IORef [SomeEventSubscription x])
1985+ , _spiderEnv_lock :: !(MVar ())
1986+ , _spiderEnv_cleanups :: !(IORef [IO ()])
1988+ , _spiderEnv_depth :: !(IORef Int)
1991+type role SpiderEnv nominal
1993+instance GEq SpiderEnv where
1994+ a `geq` b = if _spiderEnv_lock a == _spiderEnv_lock b
1995+ then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderEnv can't have two different 'x' arguments
1998+unsafeNewSpiderEnv :: forall x. IO (SpiderEnv x)
1999+unsafeNewSpiderEnv = do
2000+ toUnsubscribe <- newIORef []
2002+ cleanups <- newIORef []
2004+ depthRef <- newIORef 0
2007+ { _spiderEnv_toUnsubscribe = toUnsubscribe
2008+ , _spiderEnv_lock = lock
2009+ , _spiderEnv_cleanups = cleanups
2011+ , _spiderEnv_depth = depthRef
2015+-- | Create a new SpiderEnv
2016+newSpiderEnv :: IO (Some SpiderEnv)
2017+newSpiderEnv = Some.This <$> unsafeNewSpiderEnv
2019+newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2021+newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
2023+instance R.Reflex (SpiderEnv x) where
2024+ newtype Behavior (SpiderEnv x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
2025+ newtype Event (SpiderEnv x) a = SpiderEvent { unSpiderEvent :: Event x a }
2026+ newtype Dynamic (SpiderEnv x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x Identity a } deriving (Functor, Applicative, Monad)
2027+ newtype Incremental (SpiderEnv x) p a = SpiderIncremental { unSpiderIncremental :: Dynamic x p a }
2028+ type PullM (SpiderEnv x) = SpiderPullM x
2029+ type PushM (SpiderEnv x) = SpiderPushM x
2030+ {-# INLINABLE never #-}
2031+ never = SpiderEvent eventNever
2032+ {-# INLINABLE constant #-}
2033+ constant = SpiderBehavior . BehaviorConst
2034+ {-# INLINABLE push #-}
2035+ push f = SpiderEvent . push (coerce f) . unSpiderEvent
2036+ {-# INLINABLE pull #-}
2037+ pull = SpiderBehavior . pull . coerce
2038+ {-# INLINABLE merge #-}
2039+ merge = SpiderEvent . merge . DynamicConst . (unsafeCoerce :: DMap k (R.Event (SpiderEnv x)) -> DMap k (Event x))
2040+ {-# INLINABLE fan #-}
2041+ fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2042+ {-# INLINABLE switch #-}
2043+ switch = SpiderEvent . switch . (unsafeCoerce :: Behavior x (R.Event (SpiderEnv x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2044+ {-# INLINABLE coincidence #-}
2045+ coincidence = SpiderEvent . coincidence . (unsafeCoerce :: Event x (R.Event (SpiderEnv x) a) -> Event x (Event x a)) . unSpiderEvent
2046+ {-# INLINABLE current #-}
2047+ current = SpiderBehavior . current . unSpiderDynamic
2048+ {-# INLINABLE updated #-}
2049+ updated = SpiderEvent . fmap runIdentity . updated . unSpiderDynamic
2050+ {-# INLINABLE unsafeBuildDynamic #-}
2051+ unsafeBuildDynamic readV0 v' = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (coerce readV0) $ addIdentity $ unSpiderEvent v'
2052+ {-# INLINABLE unsafeBuildIncremental #-}
2053+ unsafeBuildIncremental readV0 dv = SpiderIncremental $ DynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2054+ {-# INLINABLE mergeIncremental #-}
2055+ mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x R.PatchDMap (DMap k (R.Event (SpiderEnv x))) -> Dynamic x R.PatchDMap (DMap k (Event x))) . unSpiderIncremental
2056+ {-# INLINABLE currentIncremental #-}
2057+ currentIncremental = SpiderBehavior . current . unSpiderIncremental
2058+ {-# INLINABLE updatedIncremental #-}
2059+ updatedIncremental = SpiderEvent . updated . unSpiderIncremental
2060+ {-# INLINABLE incrementalToDynamic #-}
2061+ incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ DynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ current i) $ flip push (updated i) $ \p -> do
2062+ c <- readBehaviorUntracked $ current i
2063+ return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
2065+instance R.MonadSample (SpiderEnv x) (EventM x) where
2066+ {-# INLINABLE sample #-}
2067+ sample (SpiderBehavior b) = readBehaviorUntracked b
2069+instance R.MonadHold (SpiderEnv x) (EventM x) where
2070+ {-# INLINABLE hold #-}
2071+ hold = holdSpiderEventM
2072+ {-# INLINABLE holdDyn #-}
2073+ holdDyn = holdDynSpiderEventM
2074+ {-# INLINABLE holdIncremental #-}
2075+ holdIncremental = holdIncrementalSpiderEventM
2077+holdSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Behavior (SpiderEnv x) a)
2078+holdSpiderEventM v0 e = fmap (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2080+holdDynSpiderEventM :: a -> R.Event (SpiderEnv x) a -> EventM x (R.Dynamic (SpiderEnv x) a)
2081+holdDynSpiderEventM v0 e = fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2083+holdIncrementalSpiderEventM :: R.Patch p => a -> R.Event (SpiderEnv x) (p a) -> EventM x (R.Incremental (SpiderEnv x) p a)
2084+holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2086+instance R.MonadHold (SpiderEnv x) (SpiderHost x) where
2087+ {-# INLINABLE hold #-}
2088+ hold v0 e = R.runHostFrame $ R.hold v0 e
2089+ {-# INLINABLE holdDyn #-}
2090+ holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
2091+ {-# INLINABLE holdIncremental #-}
2092+ holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
2094+instance R.MonadSample (SpiderEnv x) (SpiderHost x) where
2095+ {-# INLINABLE sample #-}
2096+ sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2098+instance R.MonadSample (SpiderEnv x) (SpiderPullM x) where
2099+ {-# INLINABLE sample #-}
2100+ sample = coerce . readBehaviorTracked . unSpiderBehavior
2102+instance R.MonadSample (SpiderEnv x) (SpiderPushM x) where
2103+ {-# INLINABLE sample #-}
2104+ sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2106+instance R.MonadHold (SpiderEnv x) (SpiderPushM x) where
2107+ {-# INLINABLE hold #-}
2108+ hold v0 e = R.current <$> R.holdDyn v0 e
2109+ {-# INLINABLE holdDyn #-}
2110+ holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity e
2111+ {-# INLINABLE holdIncremental #-}
2112+ holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . DynamicHold <$> hold v0 e
2114+data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2115+newtype SpiderEventHandle x a = SpiderEventHandle { unSpiderEventHandle :: EventSubscription x a }
2117+emptySubscriber :: Subscriber x a
2118+emptySubscriber = Subscriber
2119+ { subscriberPropagate = \_ -> return ()
2120+ , subscriberInvalidateHeight = \_ -> return ()
2121+ , subscriberRecalculateHeight = \_ -> return ()
2124+instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHostFrame x) where
2125+ {-# INLINABLE subscribeEvent #-}
2126+ subscribeEvent e = SpiderHostFrame $ do
2127+ subscription <- subscribe (unSpiderEvent e) emptySubscriber --TODO: Unsubscribe eventually (manually and/or with weak ref)
2128+ return $ SpiderEventHandle subscription
2130+instance R.ReflexHost (SpiderEnv x) where
2131+ type EventTrigger (SpiderEnv x) = RootTrigger x
2132+ type EventHandle (SpiderEnv x) = SpiderEventHandle x
2133+ type HostFrame (SpiderEnv x) = SpiderHostFrame x
2135+instance R.MonadReadEvent (SpiderEnv x) (ReadPhase x) where
2136+ {-# INLINABLE readEvent #-}
2137+ readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2138+ let EventSubscription sln subscribed = unSpiderEventHandle h
2139+ result <- readEventSubscribed subscribed
2143+instance MonadRef (EventM x) where
2144+ type Ref (EventM x) = Ref IO
2145+ {-# INLINABLE newRef #-}
2146+ {-# INLINABLE readRef #-}
2147+ {-# INLINABLE writeRef #-}
2148+ newRef = liftIO . newRef
2149+ readRef = liftIO . readRef
2150+ writeRef r a = liftIO $ writeRef r a
2152+instance MonadAtomicRef (EventM x) where
2153+ {-# INLINABLE atomicModifyRef #-}
2154+ atomicModifyRef r f = liftIO $ atomicModifyRef r f
2156+-- | The monad for actions that manipulate a Spider timeline identified by @x@
2157+newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderEnv x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2159+instance Monad (SpiderHost x) where
2160+ {-# INLINABLE (>>=) #-}
2161+ SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2162+ {-# INLINABLE (>>) #-}
2163+ SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2164+ {-# INLINABLE return #-}
2165+ return x = SpiderHost $ return x
2166+ {-# INLINABLE fail #-}
2167+ fail s = SpiderHost $ fail s
2169+-- | Run an action affecting the global Spider timeline; this will be guarded by
2170+-- a mutex for that timeline
2171+runSpiderHost :: SpiderHost Global a -> IO a
2172+runSpiderHost (SpiderHost a) = runReaderT a globalSpiderEnv
2174+newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2176+instance Monad (SpiderHostFrame x) where
2177+ {-# INLINABLE (>>=) #-}
2178+ SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2179+ {-# INLINABLE (>>) #-}
2180+ SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2181+ {-# INLINABLE return #-}
2182+ return x = SpiderHostFrame $ return x
2183+ {-# INLINABLE fail #-}
2184+ fail s = SpiderHostFrame $ fail s
2186+instance R.MonadSample (SpiderEnv x) (SpiderHostFrame x) where
2187+ sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2189+addIdentity :: Event x a -> Event x (Identity a)
2190+--addIdentity = fmap Identity
2191+addIdentity = unsafeCoerce
2193+instance R.MonadHold (SpiderEnv x) (SpiderHostFrame x) where
2194+ {-# INLINABLE hold #-}
2195+ hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . BehaviorHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2196+ {-# INLINABLE holdDyn #-}
2197+ holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . DynamicHoldIdentity) $ hold v0 $ addIdentity $ unSpiderEvent e
2198+ {-# INLINABLE holdIncremental #-}
2199+ holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . DynamicHold) $ hold v0 $ unSpiderEvent e
2201+newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2202+newEventWithTriggerIO f = do
2203+ es <- newFanEventWithTriggerIO $ \Refl -> f
2204+ return $ select es Refl
2206+newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2207+newFanEventWithTriggerIO f = do
2208+ occRef <- newIORef DMap.empty
2209+ subscribedRef <- newIORef DMap.empty
2211+ { rootOccurrence = occRef
2212+ , rootSubscribed = subscribedRef
2215+ return $ EventSelector $ \k -> eventRoot k r
2217+instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHost x) where
2218+ newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2219+ newFanEventWithTrigger f = SpiderHost $ lift $ do
2220+ es <- newFanEventWithTriggerIO f
2221+ return $ R.EventSelector $ SpiderEvent . select es
2223+instance R.MonadReflexCreateTrigger (SpiderEnv x) (SpiderHostFrame x) where
2224+ newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2225+ newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2226+ es <- newFanEventWithTriggerIO f
2227+ return $ R.EventSelector $ SpiderEvent . select es
2229+instance R.MonadSubscribeEvent (SpiderEnv x) (SpiderHost x) where
2230+ {-# INLINABLE subscribeEvent #-}
2231+ subscribeEvent = subscribeEventSpiderHost
2233+subscribeEventSpiderHost :: R.Event (SpiderEnv x) a -> SpiderHost x (R.EventHandle (SpiderEnv x) a)
2234+subscribeEventSpiderHost e = do
2235+ subscription <- runFrame $ subscribe (unSpiderEvent e) emptySubscriber --TODO: Unsubscribe eventually (manually and/or with weak ref)
2236+ return $ SpiderEventHandle subscription
2238+newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2240+instance R.MonadSample (SpiderEnv x) (ReadPhase x) where
2241+ {-# INLINABLE sample #-}
2242+ sample = ReadPhase . R.sample
2244+instance R.MonadHold (SpiderEnv x) (ReadPhase x) where
2245+ {-# INLINABLE hold #-}
2246+ hold v0 e = ReadPhase $ R.hold v0 e
2247+ {-# INLINABLE holdDyn #-}
2248+ holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2249+ {-# INLINABLE holdIncremental #-}
2250+ holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2252+instance R.MonadReflexHost (SpiderEnv x) (SpiderHost x) where
2253+ type ReadPhase (SpiderHost x) = ReadPhase x
2254+ fireEventsAndRead es (ReadPhase a) = run es a
2255+ runHostFrame = runFrame . runSpiderHostFrame
2257+instance MonadRef (SpiderHost x) where
2258+ type Ref (SpiderHost x) = Ref IO
2259+ newRef = SpiderHost . newRef
2260+ readRef = SpiderHost . readRef
2261+ writeRef r = SpiderHost . writeRef r
2263+instance MonadAtomicRef (SpiderHost x) where
2264+ atomicModifyRef r = SpiderHost . atomicModifyRef r
2266+instance MonadRef (SpiderHostFrame x) where
2267+ type Ref (SpiderHostFrame x) = Ref IO
2268+ newRef = SpiderHostFrame . newRef
2269+ readRef = SpiderHostFrame . readRef
2270+ writeRef r = SpiderHostFrame . writeRef r
2272+instance MonadAtomicRef (SpiderHostFrame x) where
2273+ atomicModifyRef r = SpiderHostFrame . atomicModifyRef r