@@ -1,2260 +0,0 @@
1−{-# LANGUAGE BangPatterns #-}
2−{-# LANGUAGE CPP #-}
3−{-# LANGUAGE ConstraintKinds #-}
4−{-# LANGUAGE EmptyDataDecls #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE FlexibleInstances #-}
7−{-# LANGUAGE FunctionalDependencies #-}
8−{-# LANGUAGE GADTs #-}
9−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
10−{-# LANGUAGE LambdaCase #-}
11−{-# LANGUAGE MagicHash #-}
12−{-# LANGUAGE MultiParamTypeClasses #-}
13−{-# LANGUAGE MultiWayIf #-}
14−{-# LANGUAGE RankNTypes #-}
15−{-# LANGUAGE RoleAnnotations #-}
16−{-# LANGUAGE ScopedTypeVariables #-}
17−{-# LANGUAGE TypeFamilies #-}
18−{-# LANGUAGE TypeOperators #-}
19−{-# LANGUAGE UndecidableInstances #-}
20−-- | This module is the implementation of the 'Spider' 'Reflex' engine. It uses
21−-- a graph traversal algorithm to propagate 'Event's and 'Behavior's.
22−module Reflex.Spider.Internal where
23−
24−import Control.Applicative
25−import Control.Concurrent
26−import Control.Exception
27−import Control.Monad hiding (forM, forM_, mapM, mapM_, sequence)
28−import Control.Monad.Exception
29−import Control.Monad.Identity hiding (forM, forM_, mapM, mapM_, sequence)
30−import Control.Monad.Primitive
31−import Control.Monad.Reader hiding (forM, forM_, mapM, mapM_, sequence)
32−import Control.Monad.Ref
33−import Data.Align
34−import Data.Coerce
35−import Data.Dependent.Map (DMap, DSum (..))
36−import qualified Data.Dependent.Map as DMap
37−import Data.Foldable hiding (concat, elem, sequence_)
38−import Data.Function
39−import Data.Functor.Constant
40−import Data.Functor.Product
41−import Data.GADT.Compare
42−import Data.IntMap.Strict (IntMap)
43−import qualified Data.IntMap.Strict as IntMap
44−import Data.IORef
45−import Data.List hiding (foldl')
46−import Data.Maybe
47−import Data.Monoid ((<>))
48−import Data.Some (Some)
49−import qualified Data.Some as Some
50−import Data.These
51−import Data.Traversable
52−import Data.Type.Coercion
53−import Data.Word
54−import GHC.Exts
55−import GHC.IORef (IORef (..))
56−import GHC.Stack
57−import System.IO.Unsafe
58−import System.Mem.Weak
59−import Unsafe.Coerce
60−
61−#ifdef DEBUG_CYCLES
62−import Control.Monad.State hiding (forM, forM_, mapM, mapM_, sequence)
63−import Data.List.NonEmpty (NonEmpty (..), nonEmpty)
64−import qualified Data.List.NonEmpty as NonEmpty
65−import Data.Monoid (mempty)
66−import Data.Tree (Forest, Tree (..), drawForest)
67−#endif
68−
69−import Data.WeakBag (WeakBag, WeakBagTicket)
70−import qualified Data.WeakBag as WeakBag
71−import qualified Reflex.Class as R
72−import qualified Reflex.Host.Class as R
73−
74−-- Note: must come last to silence warnings due to AMP on GHC < 7.10
75−import Prelude hiding (any, concat, mapM, mapM_, sequence)
76−
77−debugPropagate :: Bool
78−
79−debugInvalidateHeight :: Bool
80−
81−debugInvalidate :: Bool
82−
83−#ifdef DEBUG
84−
85−#define DEBUG_NODEIDS
86−
87−debugPropagate = True
88−
89−debugInvalidateHeight = False
90−
91−debugInvalidate = True
92−
93−class HasNodeId a where
94− getNodeId :: a -> Int
95−
96−instance HasNodeId (Hold x p a) where
97− getNodeId = holdNodeId
98−
99−instance HasNodeId (PushSubscribed x a b) where
100− getNodeId = pushSubscribedNodeId
101−
102−instance HasNodeId (SwitchSubscribed x a) where
103− getNodeId = switchSubscribedNodeId
104−
105−instance HasNodeId (MergeSubscribed x a) where
106− getNodeId = mergeSubscribedNodeId
107−
108−instance HasNodeId (FanSubscribed x a) where
109− getNodeId = fanSubscribedNodeId
110−
111−instance HasNodeId (CoincidenceSubscribed x a) where
112− getNodeId = coincidenceSubscribedNodeId
113−
114−instance HasNodeId (RootSubscribed x a) where
115− getNodeId = rootSubscribedNodeId
116−
117−instance HasNodeId (Pull x a) where
118− getNodeId = pullNodeId
119−
120−{-# INLINE showNodeId #-}
121−showNodeId :: HasNodeId a => a -> String
122−showNodeId = ("#"<>) . show . getNodeId
123−
124−showSubscriberType :: Subscriber x a -> String
125−showSubscriberType = \case
126− SubscriberPush _ _ -> "SubscriberPush"
127− SubscriberMerge _ _ -> "SubscriberMerge"
128− SubscriberFan _ -> "SubscriberFan"
129− SubscriberMergeChange _ -> "SubscriberMergeChange"
130− SubscriberHold _ -> "SubscriberHold"
131− SubscriberHoldIdentity _ -> "SubscriberHoldIdentity"
132− SubscriberSwitch _ -> "SubscriberSwitch"
133− SubscriberCoincidenceOuter _ -> "SubscriberCoincidenceOuter"
134− SubscriberCoincidenceInner _ -> "SubscriberCoincidenceInner"
135− SubscriberHandle -> "SubscriberHandle"
136−
137−showEventType :: Event x a -> String
138−showEventType = \case
139− EventRoot _ _ -> "EventRoot"
140− EventNever -> "EventNever"
141− EventPush _ -> "EventPush"
142− EventMerge _ -> "EventMerge"
143− EventFan _ _ -> "EventFan"
144− EventSwitch _ -> "EventSwitch"
145− EventCoincidence _ -> "EventCoincidence"
146− EventHold _ -> "EventHold"
147− EventDyn _ -> "EventDyn"
148− EventHoldIdentity _ -> "EventHoldIdentity"
149− EventDynIdentity _ -> "EventDynIdentity"
150−
151−#else
152−
153−debugPropagate = False
154−
155−debugInvalidateHeight = False
156−
157−debugInvalidate = False
158−
159−-- This must be inline, or error messages will cause memory leaks due to retaining the node in question
160−{-# INLINE showNodeId #-}
161−showNodeId :: a -> String
162−showNodeId _ = ""
163−
164−#endif
165−
166−#ifdef DEBUG_NODEIDS
167−{-# NOINLINE nextNodeIdRef #-}
168−nextNodeIdRef :: IORef Int
169−nextNodeIdRef = unsafePerformIO $ newIORef 1
170−
171−newNodeId :: IO Int
172−newNodeId = atomicModifyIORef' nextNodeIdRef $ \n -> (succ n, n)
173−
174−{-# NOINLINE unsafeNodeId #-}
175−unsafeNodeId :: a -> Int
176−unsafeNodeId a = unsafePerformIO $ do
177− touch a
178− newNodeId
179−#endif
180−
181−--------------------------------------------------------------------------------
182−-- Event
183−--------------------------------------------------------------------------------
184−
185−newtype Event x a = Event { subscribeAndRead :: Subscriber x a -> EventM x (EventSubscription x, Maybe a) }
186−
187−-- | Construct an 'Event' equivalent to that constructed by 'push', but with no
188−-- caching; if the computation function is very cheap, this is (much) more
189−-- efficient than 'push'
190−{-# INLINABLE pushCheap #-}
191−pushCheap :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
192−pushCheap f e = Event $ \sub -> do
193− (subscription, occ) <- subscribeAndRead e $ sub
194− { subscriberPropagate = \a -> do
195− mb <- runComputeM $ f a
196− mapM_ (subscriberPropagate sub) mb
197− }
198− occ' <- join <$> mapM (runComputeM . f) occ
199− return (subscription, occ')
200−
201−data CacheSubscribed x a
202− = CacheSubscribed { _cacheSubscribed_subscribers :: {-# UNPACK #-} !(WeakBag (Subscriber x a))
203− , _cacheSubscribed_weakSelf :: {-# UNPACK #-} !(IORef (Weak (CacheSubscribed x a)))
204− , _cacheSubscribed_parent :: {-# UNPACK #-} !(EventSubscription x)
205− , _cacheSubscribed_cached :: {-# UNPACK #-} !(IORef (Maybe (CacheSubscribed x a)))
206− , _cacheSubscribed_occurrence :: {-# UNPACK #-} !(IORef (Maybe a))
207− }
208−
209−-- | Construct an 'Event' whose value is guaranteed not to be recomputed
210−-- repeatedly
211−--
212−--TODO: Try a caching strategy where we subscribe directly to the parent when
213−--there's only one subscriber, and then build our own WeakBag only when a second
214−--subscriber joins
215−{-# INLINABLE cacheEvent #-}
216−cacheEvent :: Event x a -> Event x a
217−cacheEvent e = Event $ \sub -> do
218− let !mSubscribedRef = unsafeNewIORef e Nothing
219− mSubscribed <- liftIO $ readIORef mSubscribedRef
220− case mSubscribed of
221− Just subscribed -> liftIO $ do
222− ticket <- WeakBag.insert sub (_cacheSubscribed_subscribers subscribed) (_cacheSubscribed_weakSelf subscribed) cleanupCacheSubscribed
223− occ <- readIORef $ _cacheSubscribed_occurrence subscribed
224− let es = EventSubscribed
225− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ _cacheSubscribed_parent subscribed
226− , eventSubscribedRetained = toAny subscribed
227− }
228− return (EventSubscription (Just ticket) es, occ)
229− Nothing -> do
230− weakSelf <- liftIO $ newIORef $ error "cacheEvent: weakSelf not yet intialized"
231− (subscribers, ticket) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCacheSubscribed
232− occRef <- liftIO $ newIORef undefined
233− (parentSub, occ) <- subscribeAndRead e $ Subscriber
234− { subscriberPropagate = \a -> do
235− liftIO $ writeIORef occRef $ Just a
236− scheduleClear occRef
237− propagate a subscribers
238− , subscriberInvalidateHeight = \old -> do
239− WeakBag.traverse subscribers $ invalidateSubscriberHeight old
240− , subscriberRecalculateHeight = \new -> do
241− WeakBag.traverse subscribers $ recalculateSubscriberHeight new
242− }
243− liftIO $ writeIORef occRef occ
244− when (isJust occ) $ scheduleClear occRef
245− let !subscribed = CacheSubscribed
246− { _cacheSubscribed_subscribers = subscribers
247− , _cacheSubscribed_weakSelf = weakSelf
248− , _cacheSubscribed_parent = parentSub
249− , _cacheSubscribed_cached = mSubscribedRef
250− , _cacheSubscribed_occurrence = occRef
251− }
252− liftIO $ writeIORef mSubscribedRef $ Just subscribed
253− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "PushSubscribed"
254− return (EventSubscription (Just ticket) (EventSubscribed (eventSubscribedHeightRef $ _eventSubscription_subscribed parentSub) (toAny subscribed)), occ)
255−
256−cleanupCacheSubscribed :: CacheSubscribed x a -> IO ()
257−cleanupCacheSubscribed self = do
258− unsubscribe $ _cacheSubscribed_parent self
259− writeIORef (_cacheSubscribed_cached self) Nothing
260−
261−subscribe :: Event x a -> Subscriber x a -> EventM x (EventSubscription x)
262−subscribe e s = fst <$> subscribeAndRead e s
263−
264−{-# INLINE wrap #-}
265−wrap :: MonadIO m => (t -> EventSubscribed x) -> (Subscriber x a -> m (WeakBagTicket, t, Maybe a)) -> Subscriber x a -> m (EventSubscription x, Maybe a)
266−wrap tag getSpecificSubscribed sub = do
267− (sln, subd, occ) <- getSpecificSubscribed sub
268− let es = tag subd
269− return (EventSubscription (Just sln) es, occ)
270−
271−eventRoot :: GCompare k => k a -> Root x k -> Event x a
272−eventRoot !k !r = Event $ wrap eventSubscribedRoot $ liftIO . getRootSubscribed k r
273−
274−eventNever :: Event x a
275−eventNever = Event $ \_ -> return (EventSubscription Nothing eventSubscribedNever, Nothing)
276−
277−eventMerge :: GCompare k => Merge x k -> Event x (DMap k Identity)
278−eventMerge !m = Event $ wrap eventSubscribedMerge $ getMergeSubscribed m
279−
280−eventFan :: GCompare k => k a -> Fan x k -> Event x a
281−eventFan !k !f = Event $ wrap eventSubscribedFan $ getFanSubscribed k f
282−
283−eventSwitch :: Switch x a -> Event x a
284−eventSwitch !s = Event $ wrap eventSubscribedSwitch $ getSwitchSubscribed s
285−
286−eventCoincidence :: Coincidence x a -> Event x a
287−eventCoincidence !c = Event $ wrap eventSubscribedCoincidence $ getCoincidenceSubscribed c
288−
289−eventHold :: Hold x p -> Event x p
290−eventHold !h = Event $ subscribeHoldEvent h
291−
292−eventDyn :: R.Patch p => Dyn x p -> Event x p
293−eventDyn !j = Event $ \sub -> getDynHold j >>= \h -> subscribeHoldEvent h sub
294−
295−{-# INLINE subscribeCoincidenceInner #-}
296−subscribeCoincidenceInner :: CanSubscribe x m => Event x a -> Height -> CoincidenceSubscribed x a -> m (Maybe a, Height, EventSubscribed x)
297−subscribeCoincidenceInner inner outerHeight subscribedUnsafe = do
298− subInner <- liftIO $ newSubscriberCoincidenceInner subscribedUnsafe
299− (subscription@(EventSubscription _ innerSubd), innerOcc) <- subscribeAndRead inner subInner
300− innerHeight <- liftIO $ getEventSubscribedHeight innerSubd
301− let height = max innerHeight outerHeight
302− defer $ SomeResetCoincidence subscription $ if height > outerHeight then Just subscribedUnsafe else Nothing
303− return (innerOcc, height, innerSubd)
304−
305−--------------------------------------------------------------------------------
306−-- Subscriber
307−--------------------------------------------------------------------------------
308−
309−data Subscriber x a = Subscriber
310− { subscriberPropagate :: !(a -> EventM x ())
311− , subscriberInvalidateHeight :: !(Height -> IO ())
312− , subscriberRecalculateHeight :: !(Height -> IO ())
313− }
314−
315−--TODO: Move this comment to WeakBag
316−-- These function are constructor functions that are marked NOINLINE so they are
317−-- opaque to GHC. If we do not do this, then GHC will sometimes fuse the constructor away
318−-- so any weak references that are attached to the constructors will have their
319−-- finalizer run. Using the opaque constructor, does not see the
320−-- constructor application, so it behaves like an IORef and cannot be fused away.
321−--
322−-- The result is also evaluated to WHNF, since forcing a thunk invalidates
323−-- the weak pointer to it in some cases.
324−
325−newSubscriberHold :: R.Patch p => Hold x p -> IO (Subscriber x p)
326−newSubscriberHold h = return $ Subscriber
327− { subscriberPropagate = {-# SCC "traverseHold" #-} propagateSubscriberHold h
328− , subscriberInvalidateHeight = \_ -> return ()
329− , subscriberRecalculateHeight = \_ -> return ()
330− }
331−
332−newSubscriberMerge :: GCompare k => k a -> MergeSubscribed x k -> IO (Subscriber x a)
333−newSubscriberMerge k subscribed = return $ Subscriber
334− { subscriberPropagate = \a -> {-# SCC "traverseMerge" #-} do
335− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
336− oldM <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
337− let newM = DMap.insertWith (error $ "Same key fired multiple times for Merge" <> showNodeId subscribed) k (Identity a) oldM
338− tracePropagate $ " DMap.size oldM = " <> show (DMap.size oldM) <> "; DMap.size newM = " <> show (DMap.size newM)
339− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! newM
340− when (DMap.null oldM) $ do -- Only schedule the firing once
341− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
342− --TODO: assertions about height
343− currentHeight <- getCurrentHeight
344− when (height <= currentHeight) $ do
345− if height /= invalidHeight
346− then do
347− myStack <- liftIO $ whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
348− error $ "Height (" ++ show height ++ ") is not greater than current height (" ++ show currentHeight ++ ")\n" ++ unlines (reverse myStack)
349− else liftIO $ do
350−#ifdef DEBUG_CYCLES
351− nodesInvolvedInCycle <- walkInvalidHeightParents $ eventSubscribedMerge subscribed
352− stacks <- forM nodesInvolvedInCycle $ \(Some.This es) -> whoCreatedEventSubscribed es
353− let cycleInfo = ":\n" <> drawForest (listsToForest stacks)
354−#else
355− let cycleInfo = ""
356−#endif
357− error $ "Causality loop found" <> cycleInfo
358− scheduleMerge height subscribed
359− , subscriberInvalidateHeight = \old -> do
360− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
361− removeMergeHeight old subscribed
362− invalidateMergeHeight subscribed
363− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
364− , subscriberRecalculateHeight = \new -> do
365− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed
366− addMergeHeight new subscribed
367− revalidateMergeHeight subscribed
368− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberMerge" <> showNodeId subscribed <> " done"
369− }
370−
371−newSubscriberMergeChange :: GCompare k => MergeSubscribed x k -> IO (Subscriber x (R.PatchDMap k (Event x)))
372−newSubscriberMergeChange subscribed = return $ Subscriber
373− { subscriberPropagate = \a -> {-# SCC "traverseMergeChange" #-} do
374− tracePropagate $ "SubscriberMerge" <> showNodeId subscribed
375− defer $ SomeMergeUpdate (mkUpdateMerge a subscribed) (invalidateMergeHeight subscribed) (revalidateMergeHeight subscribed)
376− , subscriberInvalidateHeight = \_ -> return ()
377− , subscriberRecalculateHeight = \_ -> return ()
378− }
379−
380−newSubscriberFan :: GCompare k => FanSubscribed x k -> IO (Subscriber x (DMap k Identity))
381−newSubscriberFan subscribed = return $ Subscriber
382− { subscriberPropagate = \a -> {-# SCC "traverseFan" #-} do
383− subs <- liftIO $ readIORef $ fanSubscribedSubscribers subscribed
384− tracePropagate $ "SubscriberFan" <> showNodeId subscribed <> ": " ++ show (DMap.size subs) ++ " keys subscribed, " ++ show (DMap.size a) ++ " keys firing"
385− liftIO $ writeIORef (fanSubscribedOccurrence subscribed) $ Just a
386− scheduleClear $ fanSubscribedOccurrence subscribed
387− let f _ (Pair (Identity v) subsubs) = do
388− propagate v $ _fanSubscribedChildren_list subsubs
389− return $ Constant ()
390− _ <- DMap.traverseWithKey f $ DMap.intersectionWithKey (\_ -> Pair) a subs --TODO: Would be nice to have DMap.traverse_
391− return ()
392− , subscriberInvalidateHeight = \old -> do
393− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
394− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
395− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ invalidateSubscriberHeight old
396− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
397− , subscriberRecalculateHeight = \new -> do
398− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed
399− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
400− forM_ (DMap.toList subscribers) $ \(_ :=> v) -> WeakBag.traverse (_fanSubscribedChildren_list v) $ recalculateSubscriberHeight new
401− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberFan" <> showNodeId subscribed <> " done"
402− }
403−
404−newSubscriberSwitch :: SwitchSubscribed x a -> IO (Subscriber x a)
405−newSubscriberSwitch subscribed = return $ Subscriber
406− { subscriberPropagate = \a -> {-# SCC "traverseSwitch" #-} do
407− tracePropagate $ "SubscriberSwitch" <> showNodeId subscribed
408− liftIO $ writeIORef (switchSubscribedOccurrence subscribed) $ Just a
409− scheduleClear $ switchSubscribedOccurrence subscribed
410− propagate a $ switchSubscribedSubscribers subscribed
411− , subscriberInvalidateHeight = \_ -> do
412− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
413− oldHeight <- readIORef $ switchSubscribedHeight subscribed
414− when (oldHeight /= invalidHeight) $ do
415− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
416− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
417− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
418− , subscriberRecalculateHeight = \new -> do
419− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed
420− updateSwitchHeight new subscribed
421− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberSwitch" <> showNodeId subscribed <> " done"
422− }
423−
424−newSubscriberCoincidenceOuter :: CoincidenceSubscribed x b -> IO (Subscriber x (Event x b))
425−newSubscriberCoincidenceOuter subscribed = return $ Subscriber
426− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceOuter" #-} do
427− tracePropagate $ "SubscriberCoincidenceOuter" <> showNodeId subscribed
428− outerHeight <- liftIO $ readIORef $ coincidenceSubscribedHeight subscribed
429− tracePropagate $ " outerHeight = " <> show outerHeight
430− (occ, innerHeight, innerSubd) <- subscribeCoincidenceInner a outerHeight subscribed
431− tracePropagate $ " isJust occ = " <> show (isJust occ)
432− tracePropagate $ " innerHeight = " <> show innerHeight
433− liftIO $ writeIORef (coincidenceSubscribedInnerParent subscribed) $ Just innerSubd
434− scheduleClear $ coincidenceSubscribedInnerParent subscribed
435− case occ of
436− Nothing -> do
437− when (innerHeight > outerHeight) $ liftIO $ do -- If the event fires, it will fire at a later height
438− writeIORef (coincidenceSubscribedHeight subscribed) $! innerHeight
439− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight outerHeight
440− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight innerHeight
441− Just o -> do -- Since it's already firing, no need to adjust height
442− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) occ
443− scheduleClear $ coincidenceSubscribedOccurrence subscribed
444− propagate o $ coincidenceSubscribedSubscribers subscribed
445− , subscriberInvalidateHeight = \_ -> do
446− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
447− invalidateCoincidenceHeight subscribed
448− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
449− , subscriberRecalculateHeight = \_ -> do
450− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed
451− recalculateCoincidenceHeight subscribed
452− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceOuter" <> showNodeId subscribed <> " done"
453− }
454−
455−newSubscriberCoincidenceInner :: CoincidenceSubscribed x a -> IO (Subscriber x a)
456−newSubscriberCoincidenceInner subscribed = return $ Subscriber
457− { subscriberPropagate = \a -> {-# SCC "traverseCoincidenceInner" #-} do
458− tracePropagate $ "SubscriberCoincidenceInner" <> showNodeId subscribed
459− occ <- liftIO $ readIORef $ coincidenceSubscribedOccurrence subscribed
460− case occ of
461− Just _ -> return () -- SubscriberCoincidenceOuter must have already propagated this event
462− Nothing -> do
463− liftIO $ writeIORef (coincidenceSubscribedOccurrence subscribed) $ Just a
464− scheduleClear $ coincidenceSubscribedOccurrence subscribed
465− propagate a $ coincidenceSubscribedSubscribers subscribed
466− , subscriberInvalidateHeight = \_ -> do
467− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
468− invalidateCoincidenceHeight subscribed
469− when debugInvalidateHeight $ putStrLn $ "invalidateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
470− , subscriberRecalculateHeight = \_ -> do
471− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed
472− recalculateCoincidenceHeight subscribed
473− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: SubscriberCoincidenceInner" <> showNodeId subscribed <> " done"
474− }
475−
476−invalidateSubscriberHeight :: Height -> Subscriber x a -> IO ()
477−invalidateSubscriberHeight = flip subscriberInvalidateHeight
478−
479−recalculateSubscriberHeight :: Height -> Subscriber x a -> IO ()
480−recalculateSubscriberHeight = flip subscriberRecalculateHeight
481−
482−-- | Propagate everything at the current height
483−propagate :: a -> WeakBag (Subscriber x a) -> EventM x ()
484−propagate a subscribers = withIncreasedDepth $ do
485− -- 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
486− --TODO: Should we check if nodes already have their values before propagating? Maybe we're re-doing work
487− WeakBag.traverse subscribers $ \s -> subscriberPropagate s a
488−
489−--------------------------------------------------------------------------------
490−-- EventSubscribed
491−--------------------------------------------------------------------------------
492−
493−toAny :: a -> Any
494−toAny = unsafeCoerce
495−
496−data EventSubscribed x = EventSubscribed
497− { eventSubscribedHeightRef :: {-# UNPACK #-} !(IORef Height)
498− , eventSubscribedRetained :: {-# NOUNPACK #-} !Any
499−#ifdef DEBUG_CYCLES
500− , eventSubscribedGetParents :: !(IO [Some (EventSubscribed x)]) -- For debugging loops
501− , eventSubscribedHasOwnHeightRef :: !Bool
502− , eventSubscribedWhoCreated :: !(IO [String])
503−#endif
504− }
505−
506−eventSubscribedRoot :: RootSubscribed x a -> EventSubscribed x
507−eventSubscribedRoot !r = EventSubscribed
508− { eventSubscribedHeightRef = zeroRef
509− , eventSubscribedRetained = toAny r
510−#ifdef DEBUG_CYCLES
511− , eventSubscribedGetParents = return []
512− , eventSubscribedHasOwnHeightRef = False
513− , eventSubscribedWhoCreated = return ["root"]
514−#endif
515− }
516−
517−eventSubscribedNever :: EventSubscribed x
518−eventSubscribedNever = EventSubscribed
519− { eventSubscribedHeightRef = zeroRef
520− , eventSubscribedRetained = toAny ()
521−#ifdef DEBUG_CYCLES
522− , eventSubscribedGetParents = return []
523− , eventSubscribedHasOwnHeightRef = False
524− , eventSubscribedWhoCreated = return ["never"]
525−#endif
526− }
527−
528−eventSubscribedMerge :: MergeSubscribed x k -> EventSubscribed x
529−eventSubscribedMerge !subscribed = EventSubscribed
530− { eventSubscribedHeightRef = mergeSubscribedHeight subscribed
531− , eventSubscribedRetained = toAny subscribed
532−#ifdef DEBUG_CYCLES
533− , eventSubscribedGetParents = do
534− ps <- readIORef $ mergeSubscribedParents subscribed
535− return $ R.ffor (DMap.toList ps) $ \(_ :=> v) -> Some.This $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription v
536− , eventSubscribedHasOwnHeightRef = True
537− , eventSubscribedWhoCreated = whoCreatedIORef $ mergeSubscribedCachedSubscribed subscribed
538−#endif
539− }
540−
541−eventSubscribedFan :: FanSubscribed x k -> EventSubscribed x
542−eventSubscribedFan !subscribed = EventSubscribed
543− { eventSubscribedHeightRef = eventSubscribedHeightRef $ _eventSubscription_subscribed $ fanSubscribedParent subscribed
544− , eventSubscribedRetained = toAny subscribed
545−#ifdef DEBUG_CYCLES
546− , eventSubscribedGetParents = return [Some.This $ _eventSubscription_subscribed $ fanSubscribedParent subscribed]
547− , eventSubscribedHasOwnHeightRef = False
548− , eventSubscribedWhoCreated = whoCreatedIORef $ fanSubscribedCachedSubscribed subscribed
549−#endif
550− }
551−
552−eventSubscribedSwitch :: SwitchSubscribed x a -> EventSubscribed x
553−eventSubscribedSwitch !subscribed = EventSubscribed
554− { eventSubscribedHeightRef = switchSubscribedHeight subscribed
555− , eventSubscribedRetained = toAny subscribed
556−#ifdef DEBUG_CYCLES
557− , eventSubscribedGetParents = do
558− s <- readIORef $ switchSubscribedCurrentParent subscribed
559− return [Some.This $ _eventSubscription_subscribed s]
560− , eventSubscribedHasOwnHeightRef = True
561− , eventSubscribedWhoCreated = whoCreatedIORef $ switchSubscribedCachedSubscribed subscribed
562−#endif
563− }
564−
565−eventSubscribedCoincidence :: CoincidenceSubscribed x a -> EventSubscribed x
566−eventSubscribedCoincidence !subscribed = EventSubscribed
567− { eventSubscribedHeightRef = coincidenceSubscribedHeight subscribed
568− , eventSubscribedRetained = toAny subscribed
569−#ifdef DEBUG_CYCLES
570− , eventSubscribedGetParents = do
571− innerSubscription <- readIORef $ coincidenceSubscribedInnerParent subscribed
572− let outerParent = Some.This $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
573− innerParents = maybeToList $ fmap Some.This innerSubscription
574− return $ outerParent : innerParents
575− , eventSubscribedHasOwnHeightRef = True
576− , eventSubscribedWhoCreated = whoCreatedIORef $ coincidenceSubscribedCachedSubscribed subscribed
577−#endif
578− }
579−
580−getEventSubscribedHeight :: EventSubscribed x -> IO Height
581−getEventSubscribedHeight es = readIORef $ eventSubscribedHeightRef es
582−
583−#ifdef DEBUG_CYCLES
584−whoCreatedEventSubscribed :: EventSubscribed x -> IO [String]
585−whoCreatedEventSubscribed = eventSubscribedWhoCreated
586−
587−walkInvalidHeightParents :: EventSubscribed x -> IO [Some (EventSubscribed x)]
588−walkInvalidHeightParents s0 = do
589− subscribers <- flip execStateT mempty $ ($ Some.This s0) $ fix $ \loop (Some.This s) -> do
590− h <- liftIO $ readIORef $ eventSubscribedHeightRef s
591− when (h == invalidHeight) $ do
592− when (eventSubscribedHasOwnHeightRef s) $ liftIO $ writeIORef (eventSubscribedHeightRef s) $! invalidHeightBeingTraversed
593− modify (Some.This s :)
594− mapM_ loop =<< liftIO (eventSubscribedGetParents s)
595− forM_ subscribers $ \(Some.This s) -> writeIORef (eventSubscribedHeightRef s) $! invalidHeight
596− return subscribers
597−#endif
598−
599−{-# INLINE subscribeHoldEvent #-}
600−subscribeHoldEvent :: CanSubscribe x m => Hold x p -> Subscriber x p -> m (EventSubscription x, Maybe p)
601−subscribeHoldEvent = subscribeAndRead . holdEvent
602−
603−--------------------------------------------------------------------------------
604−-- EventSubscription
605−--------------------------------------------------------------------------------
606−
607−data EventSubscription x = EventSubscription
608− { _eventSubscription_ticket :: !(Maybe WeakBagTicket)
609− , _eventSubscription_subscribed :: {-# UNPACK #-} !(EventSubscribed x)
610− }
611−
612−unsubscribe :: EventSubscription x -> IO ()
613−unsubscribe (EventSubscription msln _) = forM_ msln $ \sln -> WeakBag.remove sln
614−
615−--------------------------------------------------------------------------------
616−-- Behavior
617−--------------------------------------------------------------------------------
618−
619−newtype Behavior x a = Behavior { readBehaviorTracked :: BehaviorM x a }
620−
621−behaviorHold :: Hold x p -> Behavior x (R.PatchTarget p)
622−behaviorHold !h = Behavior $ readHoldTracked h
623−
624−behaviorHoldIdentity :: Hold x (Identity a) -> Behavior x a
625−behaviorHoldIdentity = behaviorHold
626−
627−behaviorConst :: a -> Behavior x a
628−behaviorConst !a = Behavior $ return a
629−
630−behaviorPull :: Pull x a -> Behavior x a
631−behaviorPull !p = Behavior $ do
632− val <- liftIO $ readIORef $ pullValue p
633− case val of
634− Just subscribed -> do
635− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
636− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (pullSubscribedInvalidators subscribed) (wi:))
637− liftIO $ touch $ pullSubscribedOwnInvalidator subscribed
638− return $ pullSubscribedValue subscribed
639− Nothing -> do
640− i <- liftIO $ newInvalidatorPull p
641− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorPull"
642− parentsRef <- liftIO $ newIORef []
643− holdInits <- askBehaviorHoldInits
644− a <- liftIO $ runReaderT (unBehaviorM $ pullCompute p) (Just (wi, parentsRef), holdInits)
645− invsRef <- liftIO . newIORef . maybeToList =<< askInvalidator
646− parents <- liftIO $ readIORef parentsRef
647− let subscribed = PullSubscribed
648− { pullSubscribedValue = a
649− , pullSubscribedInvalidators = invsRef
650− , pullSubscribedOwnInvalidator = i
651− , pullSubscribedParents = parents
652− }
653− liftIO $ writeIORef (pullValue p) $ Just subscribed
654− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedPull subscribed) :))
655− return a
656−
657−behaviorDyn :: R.Patch p => Dyn x p -> Behavior x (R.PatchTarget p)
658−behaviorDyn !d = Behavior $ readHoldTracked =<< getDynHold d
659−
660−{-# INLINE readHoldTracked #-}
661−readHoldTracked :: Hold x p -> BehaviorM x (R.PatchTarget p)
662−readHoldTracked h = do
663− result <- liftIO $ readIORef $ holdValue h
664− askInvalidator >>= mapM_ (\wi -> liftIO $ modifyIORef' (holdInvalidators h) (wi:))
665− askParentsRef >>= mapM_ (\r -> liftIO $ modifyIORef' r (SomeBehaviorSubscribed (BehaviorSubscribedHold h) :))
666− return result
667−
668−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> BehaviorM x a #-}
669−{-# SPECIALIZE readBehaviorUntracked :: Behavior x a -> EventM x a #-}
670−readBehaviorUntracked :: Defer (SomeHoldInit x) m => Behavior x a -> m a
671−readBehaviorUntracked b = do
672− holdInits <- getDeferralQueue
673− liftIO $ runBehaviorM (readBehaviorTracked b) Nothing holdInits --TODO: Specialize readBehaviorTracked to the Nothing and Just cases
674−
675−--------------------------------------------------------------------------------
676−-- Dynamic
677−--------------------------------------------------------------------------------
678−
679−data Dynamic x p = Dynamic
680− { dynamicCurrent :: !(Behavior x (R.PatchTarget p))
681− , dynamicUpdated :: !(Event x p)
682− }
683−
684−dynamicHold :: Hold x p -> Dynamic x p
685−dynamicHold !h = Dynamic
686− { dynamicCurrent = behaviorHold h
687− , dynamicUpdated = eventHold h
688− }
689−
690−dynamicHoldIdentity :: Hold x (Identity a) -> Dynamic x (Identity a)
691−dynamicHoldIdentity = dynamicHold
692−
693−dynamicConst :: R.PatchTarget p -> Dynamic x p
694−dynamicConst !a = Dynamic
695− { dynamicCurrent = behaviorConst a
696− , dynamicUpdated = eventNever
697− }
698−
699−dynamicDyn :: R.Patch p => Dyn x p -> Dynamic x p
700−dynamicDyn !d = Dynamic
701− { dynamicCurrent = behaviorDyn d
702− , dynamicUpdated = eventDyn d
703− }
704−
705−dynamicDynIdentity :: Dyn x (Identity a) -> Dynamic x (Identity a)
706−dynamicDynIdentity = dynamicDyn
707−
708−--------------------------------------------------------------------------------
709−-- Combinators
710−--------------------------------------------------------------------------------
711−
712−--TODO: Figure out why certain things are not 'representational', then make them
713−--representational so we can use coerce
714−
715−--type role Hold representational
716−data Hold x p
717− = Hold { holdValue :: !(IORef (R.PatchTarget p))
718− , holdInvalidators :: !(IORef [Weak (Invalidator x)])
719− , holdEvent :: Event x p -- This must be lazy, or holds cannot be defined before their input Events
720− , holdParent :: !(IORef (Maybe (EventSubscription x))) -- Keeps its parent alive (will be undefined until the hold is initialized) --TODO: Probably shouldn't be an IORef
721−#ifdef DEBUG_NODEIDS
722− , holdNodeId :: Int
723−#endif
724− }
725−
726−data EventEnv x
727− = EventEnv { eventEnvSpiderTimeline :: !(SpiderTimeline x)
728− , eventEnvAssignments :: !(IORef [SomeAssignment x]) -- Needed for Subscribe
729− , eventEnvHoldInits :: !(IORef [SomeHoldInit x]) -- Needed for Subscribe
730− , eventEnvMergeUpdates :: !(IORef [SomeMergeUpdate x])
731− , eventEnvMergeInits :: !(IORef [SomeMergeInit x]) -- Needed for Subscribe
732− , eventEnvClears :: !(IORef [SomeClear]) -- Needed for Subscribe
733− , eventEnvRootClears :: !(IORef [SomeRootClear])
734− , eventEnvCurrentHeight :: !(IORef Height) -- Needed for Subscribe
735− , eventEnvResetCoincidences :: !(IORef [SomeResetCoincidence x]) -- Needed for Subscribe
736− , eventEnvDelayedMerges :: !(IORef (IntMap [DelayedMerge x]))
737− }
738−
739−{-# INLINE runEventM #-}
740−runEventM :: EventM x a -> EventEnv x -> IO a
741−runEventM = runReaderT . unEventM
742−
743−class MonadIO m => Defer a m where
744− getDeferralQueue :: m (IORef [a])
745−
746−{-# INLINE defer #-}
747−defer :: Defer a m => a -> m ()
748−defer a = do
749− q <- getDeferralQueue
750− liftIO $ modifyIORef' q (a:)
751−
752−instance Defer (SomeAssignment x) (EventM x) where
753− {-# INLINE getDeferralQueue #-}
754− getDeferralQueue = EventM $ asks eventEnvAssignments
755−
756−instance Defer (SomeHoldInit x) (EventM x) where
757− {-# INLINE getDeferralQueue #-}
758− getDeferralQueue = EventM $ asks eventEnvHoldInits
759−
760−instance Defer (SomeHoldInit x) (BehaviorM x) where
761− {-# INLINE getDeferralQueue #-}
762− getDeferralQueue = BehaviorM $ asks snd
763−
764−instance Defer (SomeMergeUpdate x) (EventM x) where
765− {-# INLINE getDeferralQueue #-}
766− getDeferralQueue = EventM $ asks eventEnvMergeUpdates
767−
768−instance Defer (SomeMergeInit x) (EventM x) where
769− {-# INLINE getDeferralQueue #-}
770− getDeferralQueue = EventM $ asks eventEnvMergeInits
771−
772−class HasCurrentHeight x m | m -> x where
773− getCurrentHeight :: m Height
774− scheduleMerge :: Height -> MergeSubscribed x a -> m ()
775−
776−instance HasCurrentHeight x (EventM x) where
777− {-# INLINE getCurrentHeight #-}
778− getCurrentHeight = EventM $ do
779− heightRef <- asks eventEnvCurrentHeight
780− liftIO $ readIORef heightRef
781− {-# INLINE scheduleMerge #-}
782− scheduleMerge height subscribed = EventM $ do
783− delayedRef <- asks eventEnvDelayedMerges
784− liftIO $ modifyIORef' delayedRef $ IntMap.insertWith (++) (unHeight height) [DelayedMerge subscribed]
785−
786−class HasSpiderTimeline x m | m -> x where
787− -- | Retrieve the current SpiderTimeline
788− askSpiderTimeline :: m (SpiderTimeline x)
789−
790−instance HasSpiderTimeline x (EventM x) where
791− {-# INLINE askSpiderTimeline #-}
792− askSpiderTimeline = EventM $ asks eventEnvSpiderTimeline
793−
794−instance HasSpiderTimeline x (SpiderHost x) where
795− {-# INLINE askSpiderTimeline #-}
796− askSpiderTimeline = SpiderHost ask
797−
798−putCurrentHeight :: Height -> EventM x ()
799−putCurrentHeight h = EventM $ do
800− heightRef <- asks eventEnvCurrentHeight
801− liftIO $ writeIORef heightRef $! h
802−
803−instance Defer SomeClear (EventM x) where
804− {-# INLINE getDeferralQueue #-}
805− getDeferralQueue = EventM $ asks eventEnvClears
806−
807−{-# INLINE scheduleClear #-}
808−scheduleClear :: Defer SomeClear m => IORef (Maybe a) -> m ()
809−scheduleClear r = defer $ SomeClear r
810−
811−instance Defer SomeRootClear (EventM x) where
812− {-# INLINE getDeferralQueue #-}
813− getDeferralQueue = EventM $ asks eventEnvRootClears
814−
815−{-# INLINE scheduleRootClear #-}
816−scheduleRootClear :: Defer SomeRootClear m => IORef (DMap k Identity) -> m ()
817−scheduleRootClear r = defer $ SomeRootClear r
818−
819−instance Defer (SomeResetCoincidence x) (EventM x) where
820− {-# INLINE getDeferralQueue #-}
821− getDeferralQueue = EventM $ asks eventEnvResetCoincidences
822−
823−-- Note: hold cannot examine its event until after the phase is over
824−{-# SPECIALIZE hold :: R.Patch p => R.PatchTarget p -> Event x p -> EventM x (Hold x p) #-}
825−{-# SPECIALIZE hold :: R.Patch p => R.PatchTarget p -> Event x p -> ComputeM x (Hold x p) #-}
826−hold :: (R.Patch p, Defer (SomeHoldInit x) m) => R.PatchTarget p -> Event x p -> m (Hold x p)
827−hold v0 e = do
828− valRef <- liftIO $ newIORef v0
829− invsRef <- liftIO $ newIORef []
830− parentRef <- liftIO $ newIORef Nothing
831−#ifdef DEBUG_NODEIDS
832− nodeId <- liftIO newNodeId
833−#endif
834− let h = Hold
835− { holdValue = valRef
836− , holdInvalidators = invsRef
837− , holdEvent = e
838− , holdParent = parentRef
839−#ifdef DEBUG_NODEIDS
840− , holdNodeId = nodeId
841−#endif
842− }
843− defer $ SomeHoldInit h
844− return h
845−
846−{-# INLINE getHoldEventSubscription #-}
847−getHoldEventSubscription :: forall m p 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, HasSpiderTimeline x m, m ~ EventM x) => Hold x p -> m (EventSubscription x)
848−getHoldEventSubscription h = do
849− ep <- liftIO $ readIORef $ holdParent h
850− case ep of
851− Just subd -> return subd
852− Nothing -> do
853− let e = holdEvent h
854− subscriptionRef <- liftIO $ newIORef $ error "getHoldEventSubscription: subdRef uninitialized"
855− (subscription@(EventSubscription _ _), occ) <- subscribeAndRead e =<< liftIO (newSubscriberHold h)
856− liftIO $ writeIORef subscriptionRef $! subscription
857− case occ of
858− Nothing -> return ()
859− Just o -> do
860− old <- liftIO $ readIORef $ holdValue h
861− case R.apply o old of
862− Nothing -> return ()
863− Just new -> do
864− -- Need to evaluate these so that we don't retain the Hold itself
865− v <- liftIO $ evaluate $ holdValue h
866− i <- liftIO $ evaluate $ holdInvalidators h
867− defer $ SomeAssignment v i new
868− liftIO $ writeIORef (holdParent h) $ Just subscription
869− return subscription
870−
871−type BehaviorEnv x = (Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]), IORef [SomeHoldInit x])
872−
873−--type role BehaviorM representational
874−-- BehaviorM can sample behaviors
875−newtype BehaviorM x a = BehaviorM { unBehaviorM :: ReaderT (BehaviorEnv x) IO a } deriving (Functor, Applicative, MonadIO, MonadFix)
876−
877−instance Monad (BehaviorM x) where
878− {-# INLINE (>>=) #-}
879− BehaviorM x >>= f = BehaviorM $ x >>= unBehaviorM . f
880− {-# INLINE (>>) #-}
881− BehaviorM x >> BehaviorM y = BehaviorM $ x >> y
882− {-# INLINE return #-}
883− return x = BehaviorM $ return x
884− {-# INLINE fail #-}
885− fail s = BehaviorM $ fail s
886−
887−data BehaviorSubscribed x a
888− = forall p. BehaviorSubscribedHold (Hold x p)
889− | BehaviorSubscribedPull (PullSubscribed x a)
890−
891−data SomeBehaviorSubscribed x = forall a. SomeBehaviorSubscribed (BehaviorSubscribed x a)
892−
893−--type role PullSubscribed representational
894−data PullSubscribed x a
895− = PullSubscribed { pullSubscribedValue :: !a
896− , pullSubscribedInvalidators :: !(IORef [Weak (Invalidator x)])
897− , pullSubscribedOwnInvalidator :: !(Invalidator x)
898− , pullSubscribedParents :: ![SomeBehaviorSubscribed x] -- Need to keep parent behaviors alive, or they won't let us know when they're invalidated
899− }
900−
901−--type role Pull representational
902−data Pull x a
903− = Pull { pullValue :: !(IORef (Maybe (PullSubscribed x a)))
904− , pullCompute :: !(BehaviorM x a)
905−#ifdef DEBUG_NODEIDS
906− , pullNodeId :: Int
907−#endif
908− }
909−
910−data Invalidator x
911− = forall a. InvalidatorPull (Pull x a)
912− | forall a. InvalidatorSwitch (SwitchSubscribed x a)
913−
914−data RootSubscribed x a = forall k. GCompare k => RootSubscribed
915− { rootSubscribedKey :: !(k a)
916− , rootSubscribedCachedSubscribed :: !(IORef (DMap k (RootSubscribed x))) -- From the original Root
917− , rootSubscribedSubscribers :: !(WeakBag (Subscriber x a))
918− , rootSubscribedOccurrence :: !(IO (Maybe a)) -- Lookup from rootOccurrence
919− , rootSubscribedUninit :: IO ()
920− , 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?
921−#ifdef DEBUG_NODEIDS
922− , rootSubscribedNodeId :: Int
923−#endif
924− }
925−
926−data Root x (k :: * -> *)
927− = Root { rootOccurrence :: !(IORef (DMap k Identity)) -- The currently-firing occurrence of this event
928− , rootSubscribed :: !(IORef (DMap k (RootSubscribed x)))
929− , rootInit :: !(forall a. k a -> RootTrigger x a -> IO (IO ()))
930− }
931−
932−data SomeHoldInit x = forall p. R.Patch p => SomeHoldInit !(Hold x p)
933−
934−data SomeMergeUpdate x = SomeMergeUpdate
935− { _someMergeUpdate_update :: !(EventM x [EventSubscription x])
936− , _someMergeUpdate_invalidateHeight :: !(IO ())
937− , _someMergeUpdate_recalculateHeight :: !(IO ())
938− }
939−
940−newtype SomeMergeInit x = SomeMergeInit { unSomeMergeInit :: EventM x () }
941−
942−-- EventM can do everything BehaviorM can, plus create holds
943−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
944−
945−newtype ComputeM x a = ComputeM (ReaderT (IORef [SomeHoldInit x]) IO a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
946−
947−instance Defer (SomeHoldInit x) (ComputeM x) where
948− getDeferralQueue = ComputeM ask
949−
950−{-# SPECIALIZE runComputeM :: ComputeM x a -> EventM x a #-}
951−runComputeM :: Defer (SomeHoldInit x) m => ComputeM x a -> m a
952−runComputeM (ComputeM a) = liftIO . runReaderT a =<< getDeferralQueue
953−
954−data MergeSubscribedParent (x :: *) k a = MergeSubscribedParent !(EventSubscription x) !(Subscriber x a)
955−
956−mergeSubscribedParentSubscription :: MergeSubscribedParent x k a -> EventSubscription x
957−mergeSubscribedParentSubscription (MergeSubscribedParent es _) = es
958−
959−data HeightBag = HeightBag
960− { _heightBag_size :: {-# UNPACK #-} !Int
961− , _heightBag_contents :: !(IntMap Word) -- Number of excess in each bucket
962− }
963− deriving (Show, Read, Eq, Ord)
964−
965−heightBagEmpty :: HeightBag
966−heightBagEmpty = heightBagVerify $ HeightBag 0 IntMap.empty
967−
968−heightBagSize :: HeightBag -> Int
969−heightBagSize = _heightBag_size
970−
971−heightBagFromList :: [Height] -> HeightBag
972−heightBagFromList heights = heightBagVerify $ foldl' (flip heightBagAdd) heightBagEmpty heights
973−
974−heightBagAdd :: Height -> HeightBag -> HeightBag
975−heightBagAdd (Height h) (HeightBag s c) = heightBagVerify $ HeightBag (succ s) $ IntMap.insertWithKey (\_ _ old -> succ old) h 0 c
976−
977−heightBagRemove :: Height -> HeightBag -> HeightBag
978−heightBagRemove (Height h) b@(HeightBag s c) = heightBagVerify $ case IntMap.lookup h c of
979− Nothing -> error $ "heightBagRemove: Height " <> show h <> " not present in bag " <> show b
980− Just old -> HeightBag (pred s) $ case old of
981− 0 -> IntMap.delete h c
982− _ -> IntMap.insert h (pred old) c
983−
984−heightBagMax :: HeightBag -> Height
985−heightBagMax (HeightBag _ c) = case IntMap.maxViewWithKey c of
986− Just ((h, _), _) -> Height h
987− Nothing -> zeroHeight
988−
989−heightBagVerify :: HeightBag -> HeightBag
990−#ifdef DEBUG
991−heightBagVerify b@(HeightBag s c) = if
992− | s /= IntMap.size c + fromIntegral (sum (IntMap.elems c))
993− -> error $ "heightBagVerify: size doesn't match: " <> show b
994− | unHeight invalidHeight `IntMap.member` c
995− -> error $ "heightBagVerify: contains invalid height: " <> show b
996− | otherwise -> b
997−#else
998−heightBagVerify = id
999−#endif
1000−
1001−data MergeSubscribed x k
1002− = MergeSubscribed { mergeSubscribedCachedSubscribed :: !(IORef (Maybe (MergeSubscribed x k))) -- From the original merge
1003− , mergeSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1004− , mergeSubscribedAccum :: !(IORef (DMap k Identity)) -- This will accumulate occurrences until our height is reached, at which point it will be transferred to mergeSubscribedOccurrence
1005− , mergeSubscribedHeight :: !(IORef Height)
1006− , mergeSubscribedHeightBag :: !(IORef HeightBag)
1007− , mergeSubscribedSubscribers :: !(WeakBag (Subscriber x (DMap k Identity)))
1008− , mergeSubscribedChange :: !(IORef (Subscriber x (R.PatchDMap k (Event x)), EventSubscribed x))
1009− , mergeSubscribedParents :: !(IORef (DMap k (MergeSubscribedParent x k)))
1010− , mergeSubscribedWeakSelf :: !(IORef (Weak (MergeSubscribed x k)))
1011−#ifdef DEBUG_NODEIDS
1012− , mergeSubscribedNodeId :: Int
1013−#endif
1014− }
1015−
1016−--TODO: DMap sucks; we should really write something better (with a functor for the value as well as the key)
1017−data Merge x k
1018− = Merge { mergeParents :: !(Dynamic x (R.PatchDMap k (Event x)))
1019− , mergeSubscribed :: !(IORef (Maybe (MergeSubscribed x k)))
1020− }
1021−
1022−data FanSubscribedChildren (x :: *) k a = FanSubscribedChildren
1023− { _fanSubscribedChildren_list :: !(WeakBag (Subscriber x a))
1024− , _fanSubscribedChildren_self :: {-# NOUNPACK #-} !(k a, FanSubscribed x k)
1025− , _fanSubscribedChildren_weakSelf :: !(IORef (Weak (k a, FanSubscribed x k)))
1026− }
1027−
1028−data FanSubscribed (x :: *) k
1029− = FanSubscribed { fanSubscribedCachedSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1030− , fanSubscribedOccurrence :: !(IORef (Maybe (DMap k Identity)))
1031− , fanSubscribedSubscribers :: !(IORef (DMap k (FanSubscribedChildren x k))) -- This DMap should never be empty
1032− , fanSubscribedParent :: !(EventSubscription x)
1033−#ifdef DEBUG_NODEIDS
1034− , fanSubscribedNodeId :: Int
1035−#endif
1036− }
1037−
1038−data Fan x k
1039− = Fan { fanParent :: !(Event x (DMap k Identity))
1040− , fanSubscribed :: !(IORef (Maybe (FanSubscribed x k)))
1041− }
1042−
1043−data SwitchSubscribed x a
1044− = SwitchSubscribed { switchSubscribedCachedSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1045− , switchSubscribedOccurrence :: !(IORef (Maybe a))
1046− , switchSubscribedHeight :: !(IORef Height)
1047− , switchSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1048− , switchSubscribedOwnInvalidator :: {-# NOUNPACK #-} !(Invalidator x)
1049− , switchSubscribedOwnWeakInvalidator :: !(IORef (Weak (Invalidator x)))
1050− , switchSubscribedBehaviorParents :: !(IORef [SomeBehaviorSubscribed x])
1051− , switchSubscribedParent :: !(Behavior x (Event x a))
1052− , switchSubscribedCurrentParent :: !(IORef (EventSubscription x))
1053− , switchSubscribedWeakSelf :: !(IORef (Weak (SwitchSubscribed x a)))
1054−#ifdef DEBUG_NODEIDS
1055− , switchSubscribedNodeId :: Int
1056−#endif
1057− }
1058−
1059−data Switch x a
1060− = Switch { switchParent :: !(Behavior x (Event x a))
1061− , switchSubscribed :: !(IORef (Maybe (SwitchSubscribed x a)))
1062− }
1063−
1064−{-# ANN CoincidenceSubscribed "HLint: ignore Redundant bracket" #-}
1065−data CoincidenceSubscribed x a
1066− = CoincidenceSubscribed { coincidenceSubscribedCachedSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1067− , coincidenceSubscribedOccurrence :: !(IORef (Maybe a))
1068− , coincidenceSubscribedSubscribers :: !(WeakBag (Subscriber x a))
1069− , coincidenceSubscribedHeight :: !(IORef Height)
1070− , coincidenceSubscribedOuter :: {-# NOUNPACK #-} (Subscriber x (Event x a))
1071− , coincidenceSubscribedOuterParent :: !(EventSubscription x)
1072− , coincidenceSubscribedInnerParent :: !(IORef (Maybe (EventSubscribed x)))
1073− , coincidenceSubscribedWeakSelf :: !(IORef (Weak (CoincidenceSubscribed x a)))
1074−#ifdef DEBUG_NODEIDS
1075− , coincidenceSubscribedNodeId :: Int
1076−#endif
1077− }
1078−
1079−data Coincidence x a
1080− = Coincidence { coincidenceParent :: !(Event x (Event x a))
1081− , coincidenceSubscribed :: !(IORef (Maybe (CoincidenceSubscribed x a)))
1082− }
1083−
1084−{-# NOINLINE newInvalidatorSwitch #-}
1085−newInvalidatorSwitch :: SwitchSubscribed x a -> IO (Invalidator x)
1086−newInvalidatorSwitch subd = return $! InvalidatorSwitch subd
1087−
1088−{-# NOINLINE newInvalidatorPull #-}
1089−newInvalidatorPull :: Pull x a -> IO (Invalidator x)
1090−newInvalidatorPull p = return $! InvalidatorPull p
1091−
1092−instance R.FunctorMaybe (Event x) where
1093− fmapMaybe f = push $ return . f
1094−
1095−instance Align (Event x) where
1096− nil = eventNever
1097− align ea eb = R.fmapMaybe R.dmapToThese $ merge $ dynamicConst $ DMap.fromList [R.LeftTag :=> ea, R.RightTag :=> eb]
1098−
1099−newtype Dyn x p = Dyn { unDyn :: IORef (Either (BehaviorM x (R.PatchTarget p), Event x p) (Hold x p)) }
1100−
1101−newMapDyn :: (a -> b) -> Dynamic x (Identity a) -> Dynamic x (Identity b)
1102−newMapDyn f d = dynamicDynIdentity $ unsafeDyn (fmap f $ readBehaviorTracked $ dynamicCurrent d) (Identity . f . runIdentity <$> dynamicUpdated d)
1103−
1104−--TODO: Avoid the duplication between this and R.zipDynWith
1105−zipDynWith :: (a -> b -> c) -> Dynamic x (Identity a) -> Dynamic x (Identity b) -> Dynamic x (Identity c)
1106−zipDynWith f da db =
1107− let eab = align (dynamicUpdated da) (dynamicUpdated db)
1108− ec = flip push eab $ \o -> do
1109− (a, b) <- case o of
1110− This (Identity a) -> do
1111− b <- readBehaviorUntracked $ dynamicCurrent db
1112− return (a, b)
1113− That (Identity b) -> do
1114− a <- readBehaviorUntracked $ dynamicCurrent da
1115− return (a, b)
1116− These (Identity a) (Identity b) -> return (a, b)
1117− return $ Just $ Identity $ f a b
1118− in dynamicDynIdentity $ unsafeDyn (f <$> readBehaviorUntracked (dynamicCurrent da) <*> readBehaviorUntracked (dynamicCurrent db)) ec
1119−
1120−unsafeDyn :: BehaviorM x (R.PatchTarget p) -> Event x p -> Dyn x p
1121−unsafeDyn readV0 v' = Dyn $ unsafeNewIORef x $ Left x
1122− where x = (readV0, v')
1123−
1124−newJoinDyn :: Dynamic x (Identity (Dynamic x (Identity a))) -> Dyn x (Identity a)
1125−newJoinDyn d =
1126− let readV0 = readBehaviorTracked . dynamicCurrent =<< readBehaviorTracked (dynamicCurrent d)
1127− eOuter = push (fmap (Just . Identity) . readBehaviorUntracked . dynamicCurrent . runIdentity) $ dynamicUpdated d
1128− eInner = switch $ dynamicUpdated <$> dynamicCurrent d
1129− eBoth = coincidence $ dynamicUpdated . runIdentity <$> dynamicUpdated d
1130− v' = unSpiderEvent $ R.leftmost $ map SpiderEvent [eBoth, eOuter, eInner]
1131− in unsafeDyn readV0 v'
1132−
1133−-- ResultM can read behaviors and events
1134−type ResultM = EventM
1135−
1136−{-# NOINLINE unsafeNewIORef #-}
1137−unsafeNewIORef :: a -> b -> IORef b
1138−unsafeNewIORef _ b = unsafePerformIO $ newIORef b
1139−
1140−instance Functor (Event x) where
1141− fmap f = push $ return . Just . f
1142−
1143−instance Functor (Behavior x) where
1144− fmap f = pull . fmap f . readBehaviorTracked
1145−
1146−{-# INLINABLE push #-} --TODO: If this is helpful, we can get rid of the unsafeNewIORef and use unsafePerformIO directly
1147−push :: (a -> ComputeM x (Maybe b)) -> Event x a -> Event x b
1148−push f e = cacheEvent (pushCheap f e)
1149−{-
1150−push f e = eventPush $ Push
1151− { pushCompute = f
1152− , pushParent = e
1153− , pushSubscribed = unsafeNewIORef (f, e) Nothing --TODO: Does the use of the tuple here create unnecessary overhead?
1154− }
1155−-- DISABLED: {- RULES "push/push" forall f g e. push f (push g e) = push (maybe (return Nothing) f <=< g) e #-}
1156−-}
1157−
1158−{-# INLINABLE pull #-}
1159−pull :: BehaviorM x a -> Behavior x a
1160−pull a = behaviorPull $ Pull
1161− { pullCompute = a
1162− , pullValue = unsafeNewIORef a Nothing
1163−#ifdef DEBUG_NODEIDS
1164− , pullNodeId = unsafeNodeId a
1165−#endif
1166− }
1167−
1168−{-# INLINABLE switch #-}
1169−switch :: Behavior x (Event x a) -> Event x a
1170−switch a = eventSwitch $ Switch
1171− { switchParent = a
1172− , switchSubscribed = unsafeNewIORef a Nothing
1173− }
1174−
1175−coincidence :: Event x (Event x a) -> Event x a
1176−coincidence a = eventCoincidence $ Coincidence
1177− { coincidenceParent = a
1178− , coincidenceSubscribed = unsafeNewIORef a Nothing
1179− }
1180−
1181−-- Propagate the given event occurrence; before cleaning up, run the given action, which may read the state of events and behaviors
1182−run :: [DSum (RootTrigger x) Identity] -> ResultM x b -> SpiderHost x b
1183−run roots after = do
1184− tracePropagate $ "Running an event frame with " <> show (length roots) <> " events"
1185− spiderTimeline <- SpiderHost ask
1186− result <- SpiderHost $ lift $ withMVar (_spiderTimeline_lock spiderTimeline) $ \_ -> flip runReaderT spiderTimeline $ unSpiderHost $ runFrame $ do
1187− rootsToPropagate <- forM roots $ \r@(RootTrigger (_, occRef, k) :=> a) -> do
1188− occBefore <- liftIO $ do
1189− occBefore <- readIORef occRef
1190− writeIORef occRef $! DMap.insert k a occBefore
1191− return occBefore
1192− if DMap.null occBefore
1193− then do scheduleRootClear occRef
1194− return $ Just r
1195− else return Nothing
1196− forM_ (catMaybes rootsToPropagate) $ \(RootTrigger (subscribersRef, _, _) :=> Identity a) -> do
1197− propagate a subscribersRef
1198− delayedRef <- EventM $ asks eventEnvDelayedMerges
1199− let go = do
1200− delayed <- liftIO $ readIORef delayedRef
1201− case IntMap.minViewWithKey delayed of
1202− Nothing -> return ()
1203− Just ((currentHeight, cur), future) -> do
1204− tracePropagate $ "Running height " ++ show currentHeight
1205− putCurrentHeight $ Height currentHeight
1206− liftIO $ writeIORef delayedRef $! future
1207− forM_ cur $ \d -> case d of
1208− DelayedMerge subscribed -> do
1209− height <- liftIO $ readIORef $ mergeSubscribedHeight subscribed
1210− case height `compare` Height currentHeight of
1211− LT -> error "Somehow a merge's height has been decreased after it was scheduled"
1212− GT -> scheduleMerge height subscribed -- The height has been increased (by a coincidence event; TODO: is this the only way?)
1213− EQ -> do
1214− m <- liftIO $ readIORef $ mergeSubscribedAccum subscribed
1215− liftIO $ writeIORef (mergeSubscribedAccum subscribed) $! DMap.empty
1216− --TODO: Assert that m is not empty
1217− liftIO $ writeIORef (mergeSubscribedOccurrence subscribed) $ Just m
1218− scheduleClear $ mergeSubscribedOccurrence subscribed
1219− propagate m $ mergeSubscribedSubscribers subscribed
1220− go
1221− go
1222− putCurrentHeight maxBound
1223− after
1224− tracePropagate "Done running an event frame"
1225− return result
1226−
1227−data SomeClear = forall a. SomeClear (IORef (Maybe a))
1228−
1229−data SomeRootClear = forall k. SomeRootClear (IORef (DMap k Identity))
1230−
1231−data SomeAssignment x = forall a. SomeAssignment {-# UNPACK #-} !(IORef a) {-# UNPACK #-} !(IORef [Weak (Invalidator x)]) a
1232−
1233−data DelayedMerge x = forall k. DelayedMerge (MergeSubscribed x k)
1234−
1235−debugFinalize :: Bool
1236−debugFinalize = False
1237−
1238−mkWeakPtrWithDebug :: a -> String -> IO (Weak a)
1239−mkWeakPtrWithDebug x debugNote = do
1240− x' <- evaluate x
1241− mkWeakPtr x' $
1242− if debugFinalize
1243− then Just $ putStrLn $ "finalizing: " ++ debugNote
1244− else Nothing
1245−
1246−type WeakList a = [Weak a]
1247−
1248−{-# INLINE withIncreasedDepth #-}
1249−#ifdef DEBUG
1250−withIncreasedDepth :: CanTrace x m => m a -> m a
1251−withIncreasedDepth a = do
1252− spiderTimeline <- askSpiderTimeline
1253− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) succ
1254− result <- a
1255− liftIO $ modifyIORef' (_spiderTimeline_depth spiderTimeline) pred
1256− return result
1257−#else
1258−withIncreasedDepth :: m a -> m a
1259−withIncreasedDepth = id
1260−#endif
1261−
1262−type CanTrace x m = (HasSpiderTimeline x m, MonadIO m)
1263−
1264−{-# INLINE tracePropagate #-}
1265−tracePropagate :: (CanTrace x m) => String -> m ()
1266−tracePropagate = traceWhen debugPropagate
1267−
1268−{-# INLINE traceInvalidate #-}
1269−traceInvalidate :: String -> IO ()
1270−traceInvalidate = when debugInvalidate . liftIO . putStrLn
1271−
1272−{-# INLINE traceWhen #-}
1273−traceWhen :: (CanTrace x m) => Bool -> String -> m ()
1274−traceWhen b message = traceMWhen b $ return message
1275−
1276−{-# INLINE traceMWhen #-}
1277−traceMWhen :: (CanTrace x m) => Bool -> m String -> m ()
1278−traceMWhen b getMessage = when b $ do
1279− message <- getMessage
1280−#ifdef DEBUG
1281− spiderTimeline <- askSpiderTimeline
1282− d <- liftIO $ readIORef $ _spiderTimeline_depth spiderTimeline
1283−#else
1284− let d = 0
1285−#endif
1286− liftIO $ putStrLn $ replicate d ' ' <> message
1287−
1288−whoCreatedIORef :: IORef a -> IO [String]
1289−whoCreatedIORef (IORef a) = whoCreated $! a
1290−
1291−#ifdef DEBUG_CYCLES
1292−groupByHead :: Eq a => [NonEmpty a] -> [(a, NonEmpty [a])]
1293−groupByHead = \case
1294− [] -> []
1295− (x :| xs) : t -> case groupByHead t of
1296− [] -> [(x, xs :| [])]
1297− l@((y, yss) : t')
1298− | x == y -> (x, xs `NonEmpty.cons` yss) : t'
1299− | otherwise -> (x, xs :| []) : l
1300−
1301−listsToForest :: Eq a => [[a]] -> Forest a
1302−listsToForest l = fmap (\(a, l') -> Node a $ listsToForest $ toList l') $ groupByHead $ catMaybes $ fmap nonEmpty l
1303−#endif
1304−
1305−{-# INLINE propagateSubscriberHold #-}
1306−propagateSubscriberHold :: R.Patch p => Hold x p -> p -> EventM x ()
1307−propagateSubscriberHold h a = do
1308− {-# SCC "trace" #-} traceMWhen debugPropagate $ liftIO $ do
1309− invalidators <- liftIO $ readIORef $ holdInvalidators h
1310− return $ "SubscriberHold" <> showNodeId h <> ": " ++ show (length invalidators)
1311− v <- {-# SCC "read" #-} liftIO $ readIORef $ holdValue h
1312− case {-# SCC "apply" #-} R.apply a v of
1313− Nothing -> return ()
1314− Just v' -> do
1315− {-# SCC "trace2" #-} withIncreasedDepth $ tracePropagate $ "propagateSubscriberHold: assigning Hold" <> showNodeId h
1316− vRef <- {-# SCC "vRef" #-} liftIO $ evaluate $ holdValue h
1317− iRef <- {-# SCC "iRef" #-} liftIO $ evaluate $ holdInvalidators h
1318− defer $ {-# SCC "assignment" #-} SomeAssignment vRef iRef v'
1319−
1320−data SomeResetCoincidence x = forall a. SomeResetCoincidence !(EventSubscription x) !(Maybe (CoincidenceSubscribed x a)) -- The CoincidenceSubscriber will be present only if heights need to be reset
1321−
1322−runBehaviorM :: BehaviorM x a -> Maybe (Weak (Invalidator x), IORef [SomeBehaviorSubscribed x]) -> IORef [SomeHoldInit x] -> IO a
1323−runBehaviorM a mwi holdInits = runReaderT (unBehaviorM a) (mwi, holdInits)
1324−
1325−askInvalidator :: BehaviorM x (Maybe (Weak (Invalidator x)))
1326−askInvalidator = do
1327− (!m, _) <- BehaviorM ask
1328− case m of
1329− Nothing -> return Nothing
1330− Just (!wi, _) -> return $ Just wi
1331−
1332−askParentsRef :: BehaviorM x (Maybe (IORef [SomeBehaviorSubscribed x]))
1333−askParentsRef = do
1334− (!m, _) <- BehaviorM ask
1335− case m of
1336− Nothing -> return Nothing
1337− Just (_, !p) -> return $ Just p
1338−
1339−askBehaviorHoldInits :: BehaviorM x (IORef [SomeHoldInit x])
1340−askBehaviorHoldInits = do
1341− (_, !his) <- BehaviorM ask
1342− return his
1343−
1344−{-# INLINE getDynHold #-}
1345−getDynHold :: (Defer (SomeHoldInit x) m, R.Patch p) => Dyn x p -> m (Hold x p)
1346−getDynHold d = do
1347− mh <- liftIO $ readIORef $ unDyn d
1348− case mh of
1349− Right h -> return h
1350− Left (readV0, v') -> do
1351− holdInits <- getDeferralQueue
1352− v0 <- liftIO $ runBehaviorM readV0 Nothing holdInits
1353− h <- hold v0 v'
1354− liftIO $ writeIORef (unDyn d) $ Right h
1355− return h
1356−
1357−-- Always refers to 0
1358−{-# NOINLINE zeroRef #-}
1359−zeroRef :: IORef Height
1360−zeroRef = unsafePerformIO $ newIORef zeroHeight
1361−
1362−type CanSubscribe x m =
1363− ( HasSpiderTimeline x m
1364− , HasCurrentHeight x m
1365− , Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m -- The things we need to lazily initialize state
1366− , Defer SomeClear m -- Wiping out event firings
1367− , Defer (SomeAssignment x) m -- Updating state
1368− , Defer (SomeResetCoincidence x) m
1369− , m ~ EventM x
1370− )
1371−
1372−getRootSubscribed :: GCompare k => k a -> Root x k -> Subscriber x a -> IO (WeakBagTicket, RootSubscribed x a, Maybe a)
1373−getRootSubscribed k r sub = do
1374− mSubscribed <- readIORef $ rootSubscribed r
1375− let getOcc = fmap (coerce . DMap.lookup k) $ readIORef $ rootOccurrence r
1376− case DMap.lookup k mSubscribed of
1377− Just subscribed -> {-# SCC "hitRoot" #-} do
1378− sln <- subscribeRootSubscribed subscribed sub
1379− occ <- getOcc
1380− return (sln, subscribed, occ)
1381− Nothing -> {-# SCC "missRoot" #-} do
1382− weakSelf <- newIORef $ error "getRootSubscribed: weakSelfRef not initialized"
1383− let !cached = rootSubscribed r
1384− uninitRef <- newIORef $ error "getRootsubscribed: uninitRef not initialized"
1385− (subs, sln) <- WeakBag.singleton sub weakSelf cleanupRootSubscribed
1386− when debugPropagate $ putStrLn $ "getRootSubscribed: calling rootInit"
1387− uninit <- rootInit r k $ RootTrigger (subs, rootOccurrence r, k)
1388− writeIORef uninitRef $! uninit
1389− let subscribed = RootSubscribed
1390− { rootSubscribedKey = k
1391− , rootSubscribedCachedSubscribed = cached
1392− , rootSubscribedOccurrence = getOcc
1393− , rootSubscribedSubscribers = subs
1394− , rootSubscribedUninit = uninit
1395− , rootSubscribedWeakSelf = weakSelf
1396−#ifdef DEBUG_NODEIDS
1397− , rootSubscribedNodeId = unsafeNodeId (k, r, subs)
1398−#endif
1399− }
1400− writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "RootSubscribed"
1401− modifyIORef' (rootSubscribed r) $ DMap.insertWith (error $ "getRootSubscribed: duplicate key inserted into Root") k subscribed --TODO: I think we can just write back mSubscribed rather than re-reading it
1402− occ <- getOcc
1403− return (sln, subscribed, occ)
1404−
1405−{-# ANN cleanupRootSubscribed "HLint: ignore Redundant bracket" #-}
1406−cleanupRootSubscribed :: RootSubscribed x a -> IO ()
1407−cleanupRootSubscribed self@(RootSubscribed { rootSubscribedKey = k, rootSubscribedCachedSubscribed = cached }) = do
1408− rootSubscribedUninit self
1409− modifyIORef' cached $ DMap.delete k
1410−
1411−{-# INLINE subscribeRootSubscribed #-}
1412−subscribeRootSubscribed :: RootSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1413−subscribeRootSubscribed subscribed sub = WeakBag.insert sub (rootSubscribedSubscribers subscribed) (rootSubscribedWeakSelf subscribed) cleanupRootSubscribed
1414−
1415−{-# SPECIALIZE getMergeSubscribed :: GCompare k => Merge x k -> Subscriber x (DMap k Identity) -> EventM x (WeakBagTicket, MergeSubscribed x k, Maybe (DMap k Identity)) #-}
1416−getMergeSubscribed :: forall x k m. (CanSubscribe x m, GCompare k) => Merge x k -> Subscriber x (DMap k Identity) -> m (WeakBagTicket, MergeSubscribed x k, Maybe (DMap k Identity))
1417−getMergeSubscribed m sub = do
1418− mSubscribed <- liftIO $ readIORef $ mergeSubscribed m
1419− case mSubscribed of
1420− Just subscribed -> {-# SCC "hitMerge" #-} liftIO $ do
1421− sln <- subscribeMergeSubscribed subscribed sub
1422− occ <- readIORef $ mergeSubscribedOccurrence subscribed
1423− return (sln, subscribed, occ)
1424− Nothing -> {-# SCC "missMerge" #-} do
1425− subscribedRef <- liftIO $ newIORef $ error "getMergeSubscribed: subscribedRef not yet initialized"
1426− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1427− initialParents <- readBehaviorUntracked $ dynamicCurrent $ mergeParents m
1428− subscribers :: [(Maybe (DSum k Identity), Height, DSum k (MergeSubscribedParent x k))] <- forM (DMap.toList initialParents) $ \(k :=> e) -> do
1429− s <- liftIO $ newSubscriberMerge k subscribedUnsafe
1430− (subscription@(EventSubscription _ parentSubd), parentOcc) <- subscribeAndRead e s
1431− height <- liftIO $ getEventSubscribedHeight parentSubd
1432− return $ (fmap (\x -> k :=> Identity x) parentOcc, height, k :=> MergeSubscribedParent subscription s)
1433− let dm = DMap.fromDistinctAscList $ mapMaybe (\(x, _, _) -> x) subscribers
1434− heights = fmap (\(_, h, _) -> h) subscribers --TODO: Assert that there's no invalidHeight in here
1435− myHeightBag = heightBagFromList $ filter (/= invalidHeight) heights
1436− myHeight = if invalidHeight `elem` heights
1437− then invalidHeight
1438− else succHeight $ heightBagMax myHeightBag
1439− currentHeight <- getCurrentHeight
1440− let (occ, accum) = if currentHeight >= myHeight -- If we should have fired by now
1441− then (if DMap.null dm then Nothing else Just dm, DMap.empty)
1442− else (Nothing, dm)
1443− unless (DMap.null accum) $ do
1444− scheduleMerge myHeight subscribedUnsafe
1445− occRef <- liftIO $ newIORef occ
1446− when (isJust occ) $ scheduleClear occRef
1447− accumRef <- liftIO $ newIORef accum
1448− heightRef <- liftIO $ newIORef myHeight
1449− heightMapRef <- liftIO $ newIORef myHeightBag
1450− weakSelf <- liftIO $ newIORef $ error "getMergeSubscribed: weakSelf not yet initialized"
1451− (subs, sln) <- liftIO $ WeakBag.singleton sub weakSelf cleanupMergeSubscribed
1452− changeSubdRef <- liftIO $ newIORef $ error "getMergeSubscribed: changeSubdRef not yet initialized"
1453− parentsRef <- liftIO $ newIORef $ DMap.fromDistinctAscList $ map (\(_, _, x) -> x) subscribers
1454− let !subscribed = MergeSubscribed
1455− { mergeSubscribedCachedSubscribed = mergeSubscribed m
1456− , mergeSubscribedOccurrence = occRef
1457− , mergeSubscribedAccum = accumRef
1458− , mergeSubscribedHeight = heightRef
1459− , mergeSubscribedHeightBag = heightMapRef
1460− , mergeSubscribedSubscribers = subs
1461− , mergeSubscribedChange = changeSubdRef
1462− , mergeSubscribedParents = parentsRef
1463− , mergeSubscribedWeakSelf = weakSelf
1464−#ifdef DEBUG_NODEIDS
1465− , mergeSubscribedNodeId = unsafeNodeId m
1466−#endif
1467− }
1468− defer $ SomeMergeInit $ mkInitMerge subscribed $ dynamicUpdated $ mergeParents m
1469− liftIO $ writeIORef subscribedRef $! subscribed
1470− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "MergeSubscribed"
1471− liftIO $ writeIORef (mergeSubscribed m) $ Just subscribed
1472− return (sln, subscribed, occ)
1473−
1474−cleanupMergeSubscribed :: MergeSubscribed x k -> IO ()
1475−cleanupMergeSubscribed subscribed = do
1476− parents <- readIORef $ mergeSubscribedParents subscribed
1477− forM_ (DMap.toList parents) $ \(_ :=> msp) -> unsubscribe $ mergeSubscribedParentSubscription msp
1478− -- Not necessary, because this whole MergeSubscribed is dead: writeIORef (mergeSubscribedParents subscribed) DMap.empty
1479− writeIORef (mergeSubscribedCachedSubscribed subscribed) $ Nothing -- Get rid of the cached subscribed
1480−
1481−{-# INLINE subscribeMergeSubscribed #-}
1482−subscribeMergeSubscribed :: MergeSubscribed x k -> Subscriber x (DMap k Identity) -> IO WeakBagTicket
1483−subscribeMergeSubscribed subscribed sub = WeakBag.insert sub (mergeSubscribedSubscribers subscribed) (mergeSubscribedWeakSelf subscribed) cleanupMergeSubscribed
1484−
1485−{-# SPECIALIZE getFanSubscribed :: GCompare k => k a -> Fan x k -> Subscriber x a -> EventM x (WeakBagTicket, FanSubscribed x k, Maybe a) #-}
1486−getFanSubscribed :: (Defer (SomeAssignment x) m, Defer (SomeHoldInit x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, HasCurrentHeight x m, Defer (SomeResetCoincidence x) m, HasSpiderTimeline x m, m ~ EventM x, GCompare k) => k a -> Fan x k -> Subscriber x a -> m (WeakBagTicket, FanSubscribed x k, Maybe a)
1487−getFanSubscribed k f sub = do
1488− mSubscribed <- liftIO $ readIORef $ fanSubscribed f
1489− case mSubscribed of
1490− Just subscribed -> {-# SCC "hitFan" #-} liftIO $ do
1491− sln <- subscribeFanSubscribed k subscribed sub
1492− occ <- readIORef $ fanSubscribedOccurrence subscribed
1493− return (sln, subscribed, coerce $ DMap.lookup k =<< occ)
1494− Nothing -> {-# SCC "missFan" #-} do
1495− subscribedRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribedRef not yet initialized"
1496− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1497− s <- liftIO $ newSubscriberFan subscribedUnsafe
1498− (subscription, parentOcc) <- subscribeAndRead (fanParent f) s
1499− weakSelf <- liftIO $ newIORef $ error "getFanSubscribed: weakSelf not yet initialized"
1500− (subsForK, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupFanSubscribed
1501− subscribersRef <- liftIO $ newIORef $ error "getFanSubscribed: subscribersRef not yet initialized"
1502− occRef <- liftIO $ newIORef parentOcc
1503− when (isJust parentOcc) $ scheduleClear occRef
1504− let subscribed = FanSubscribed
1505− { fanSubscribedCachedSubscribed = fanSubscribed f
1506− , fanSubscribedOccurrence = occRef
1507− , fanSubscribedParent = subscription
1508− , fanSubscribedSubscribers = subscribersRef
1509−#ifdef DEBUG_NODEIDS
1510− , fanSubscribedNodeId = unsafeNodeId f
1511−#endif
1512− }
1513− let !self = (k, subscribed)
1514− liftIO $ writeIORef subscribersRef $! DMap.singleton k $ FanSubscribedChildren subsForK self weakSelf
1515− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug self "FanSubscribed"
1516− liftIO $ writeIORef subscribedRef $! subscribed
1517− liftIO $ writeIORef (fanSubscribed f) $ Just subscribed
1518− return (slnForSub, subscribed, coerce $ DMap.lookup k =<< parentOcc)
1519−
1520−cleanupFanSubscribed :: GCompare k => (k a, FanSubscribed x k) -> IO ()
1521−cleanupFanSubscribed (k, subscribed) = do
1522− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1523− let reducedSubscribers = DMap.delete k subscribers
1524− if DMap.null reducedSubscribers
1525− then do
1526− unsubscribe $ fanSubscribedParent subscribed
1527− -- Not necessary in this case, because this whole FanSubscribed is dead: writeIORef (fanSubscribedSubscribers subscribed) reducedSubscribers
1528− writeIORef (fanSubscribedCachedSubscribed subscribed) Nothing
1529− else writeIORef (fanSubscribedSubscribers subscribed) $! reducedSubscribers
1530−
1531−{-# INLINE subscribeFanSubscribed #-}
1532−subscribeFanSubscribed :: GCompare k => k a -> FanSubscribed x k -> Subscriber x a -> IO WeakBagTicket
1533−subscribeFanSubscribed k subscribed sub = do
1534− subscribers <- readIORef $ fanSubscribedSubscribers subscribed
1535− case DMap.lookup k subscribers of
1536− Nothing -> {-# SCC "missSubscribeFanSubscribed" #-} do
1537− let !self = (k, subscribed)
1538− weakSelf <- newIORef =<< mkWeakPtrWithDebug self "FanSubscribed"
1539− (list, sln) <- WeakBag.singleton sub weakSelf cleanupFanSubscribed
1540− writeIORef (fanSubscribedSubscribers subscribed) $! DMap.insertWith (error "subscribeFanSubscribed: key that we just failed to find is present - should be impossible") k (FanSubscribedChildren list self weakSelf) subscribers
1541− return sln
1542− Just (FanSubscribedChildren list _ weakSelf) -> {-# SCC "hitSubscribeFanSubscribed" #-} WeakBag.insert sub list weakSelf cleanupFanSubscribed
1543−
1544−{-# SPECIALIZE getSwitchSubscribed :: Switch x a -> Subscriber x a -> EventM x (WeakBagTicket, SwitchSubscribed x a, Maybe a) #-}
1545−getSwitchSubscribed :: (Defer (SomeHoldInit x) m, Defer (SomeAssignment x) m, Defer (SomeMergeInit x) m, Defer SomeClear m, Defer (SomeResetCoincidence x) m, HasCurrentHeight x m, HasSpiderTimeline x m, m ~ EventM x) => Switch x a -> Subscriber x a -> m (WeakBagTicket, SwitchSubscribed x a, Maybe a)
1546−getSwitchSubscribed s sub = do
1547− mSubscribed <- liftIO $ readIORef $ switchSubscribed s
1548− case mSubscribed of
1549− Just subscribed -> {-# SCC "hitSwitch" #-} liftIO $ do
1550− sln <- subscribeSwitchSubscribed subscribed sub
1551− occ <- readIORef $ switchSubscribedOccurrence subscribed
1552− return (sln, subscribed, occ)
1553− Nothing -> {-# SCC "missSwitch" #-} do
1554− subscribedRef <- liftIO $ newIORef $ error "getSwitchSubscribed: subscribed has not yet been created"
1555− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1556− i <- liftIO $ newInvalidatorSwitch subscribedUnsafe
1557− mySub <- liftIO $ newSubscriberSwitch subscribedUnsafe
1558− wi <- liftIO $ mkWeakPtrWithDebug i "InvalidatorSwitch"
1559− wiRef <- liftIO $ newIORef wi
1560− parentsRef <- liftIO $ newIORef [] --TODO: This should be unnecessary, because it will always be filled with just the single parent behavior
1561− holdInits <- getDeferralQueue
1562− e <- liftIO $ runBehaviorM (readBehaviorTracked (switchParent s)) (Just (wi, parentsRef)) holdInits
1563− (subscription@(EventSubscription _ subd), parentOcc) <- subscribeAndRead e mySub
1564− heightRef <- liftIO $ newIORef =<< getEventSubscribedHeight subd
1565− subscriptionRef <- liftIO $ newIORef subscription
1566− occRef <- liftIO $ newIORef parentOcc
1567− when (isJust parentOcc) $ scheduleClear occRef
1568− weakSelf <- liftIO $ newIORef $ error "getSwitchSubscribed: weakSelf not yet initialized"
1569− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupSwitchSubscribed
1570− let !subscribed = SwitchSubscribed
1571− { switchSubscribedCachedSubscribed = switchSubscribed s
1572− , switchSubscribedOccurrence = occRef
1573− , switchSubscribedHeight = heightRef
1574− , switchSubscribedSubscribers = subs
1575− , switchSubscribedOwnInvalidator = i
1576− , switchSubscribedOwnWeakInvalidator = wiRef
1577− , switchSubscribedBehaviorParents = parentsRef
1578− , switchSubscribedParent = switchParent s
1579− , switchSubscribedCurrentParent = subscriptionRef
1580− , switchSubscribedWeakSelf = weakSelf
1581−#ifdef DEBUG_NODEIDS
1582− , switchSubscribedNodeId = unsafeNodeId s
1583−#endif
1584− }
1585− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "switchSubscribedWeakSelf"
1586− liftIO $ writeIORef subscribedRef $! subscribed
1587− liftIO $ writeIORef (switchSubscribed s) $ Just subscribed
1588− return (slnForSub, subscribed, parentOcc)
1589−
1590−cleanupSwitchSubscribed :: SwitchSubscribed x a -> IO ()
1591−cleanupSwitchSubscribed subscribed = do
1592− unsubscribe =<< readIORef (switchSubscribedCurrentParent subscribed)
1593− finalize =<< readIORef (switchSubscribedOwnWeakInvalidator subscribed) -- We don't need to get invalidated if we're dead
1594− writeIORef (switchSubscribedCachedSubscribed subscribed) Nothing
1595−
1596−{-# INLINE subscribeSwitchSubscribed #-}
1597−subscribeSwitchSubscribed :: SwitchSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1598−subscribeSwitchSubscribed subscribed sub = WeakBag.insert sub (switchSubscribedSubscribers subscribed) (switchSubscribedWeakSelf subscribed) cleanupSwitchSubscribed
1599−
1600−{-# SPECIALIZE getCoincidenceSubscribed :: Coincidence x a -> Subscriber x a -> EventM x (WeakBagTicket, CoincidenceSubscribed x a, Maybe a) #-}
1601−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, HasSpiderTimeline x m, m ~ EventM x) => Coincidence x a -> Subscriber x a -> m (WeakBagTicket, CoincidenceSubscribed x a, Maybe a)
1602−getCoincidenceSubscribed c sub = do
1603− mSubscribed <- liftIO $ readIORef $ coincidenceSubscribed c
1604− case mSubscribed of
1605− Just subscribed -> {-# SCC "hitCoincidence" #-} liftIO $ do
1606− sln <- subscribeCoincidenceSubscribed subscribed sub
1607− occ <- readIORef $ coincidenceSubscribedOccurrence subscribed
1608− return (sln, subscribed, occ)
1609− Nothing -> {-# SCC "missCoincidence" #-} do
1610− subscribedRef <- liftIO $ newIORef $ error "getCoincidenceSubscribed: subscribed has not yet been created"
1611− subscribedUnsafe <- liftIO $ unsafeInterleaveIO $ readIORef subscribedRef
1612− subOuter <- liftIO $ newSubscriberCoincidenceOuter subscribedUnsafe
1613− (outerSubscription@(EventSubscription _ outerSubd), outerOcc) <- subscribeAndRead (coincidenceParent c) subOuter
1614− outerHeight <- liftIO $ getEventSubscribedHeight outerSubd
1615− (occ, height, mInnerSubd) <- case outerOcc of
1616− Nothing -> return (Nothing, outerHeight, Nothing)
1617− Just o -> do
1618− (occ, height, innerSubd) <- subscribeCoincidenceInner o outerHeight subscribedUnsafe
1619− return (occ, height, Just innerSubd)
1620− occRef <- liftIO $ newIORef occ
1621− when (isJust occ) $ scheduleClear occRef
1622− heightRef <- liftIO $ newIORef height
1623− innerSubdRef <- liftIO $ newIORef mInnerSubd
1624− scheduleClear innerSubdRef
1625− weakSelf <- liftIO $ newIORef $ error "getCoincidenceSubscribed: weakSelf not yet implemented"
1626− (subs, slnForSub) <- liftIO $ WeakBag.singleton sub weakSelf cleanupCoincidenceSubscribed
1627− let subscribed = CoincidenceSubscribed
1628− { coincidenceSubscribedCachedSubscribed = coincidenceSubscribed c
1629− , coincidenceSubscribedOccurrence = occRef
1630− , coincidenceSubscribedHeight = heightRef
1631− , coincidenceSubscribedSubscribers = subs
1632− , coincidenceSubscribedOuter = subOuter
1633− , coincidenceSubscribedOuterParent = outerSubscription
1634− , coincidenceSubscribedInnerParent = innerSubdRef
1635− , coincidenceSubscribedWeakSelf = weakSelf
1636−#ifdef DEBUG_NODEIDS
1637− , coincidenceSubscribedNodeId = unsafeNodeId c
1638−#endif
1639− }
1640− liftIO $ writeIORef weakSelf =<< evaluate =<< mkWeakPtrWithDebug subscribed "CoincidenceSubscribed"
1641− liftIO $ writeIORef subscribedRef $! subscribed
1642− liftIO $ writeIORef (coincidenceSubscribed c) $ Just subscribed
1643− return (slnForSub, subscribed, occ)
1644−
1645−cleanupCoincidenceSubscribed :: CoincidenceSubscribed x a -> IO ()
1646−cleanupCoincidenceSubscribed subscribed = do
1647− unsubscribe $ coincidenceSubscribedOuterParent subscribed
1648− writeIORef (coincidenceSubscribedCachedSubscribed subscribed) Nothing
1649−
1650−{-# INLINE subscribeCoincidenceSubscribed #-}
1651−subscribeCoincidenceSubscribed :: CoincidenceSubscribed x a -> Subscriber x a -> IO WeakBagTicket
1652−subscribeCoincidenceSubscribed subscribed sub = WeakBag.insert sub (coincidenceSubscribedSubscribers subscribed) (coincidenceSubscribedWeakSelf subscribed) cleanupCoincidenceSubscribed
1653−
1654−{-# INLINE merge #-}
1655−merge :: GCompare k => Dynamic x (R.PatchDMap k (Event x)) -> Event x (DMap k Identity)
1656−merge m = eventMerge $ Merge
1657− { mergeParents = m
1658− , mergeSubscribed = unsafeNewIORef m Nothing
1659− }
1660−
1661−newtype EventSelector x k = EventSelector { select :: forall a. k a -> Event x a }
1662−
1663−fan :: GCompare k => Event x (DMap k Identity) -> EventSelector x k
1664−fan e =
1665− let f = Fan
1666− { fanParent = e
1667− , fanSubscribed = unsafeNewIORef e Nothing
1668− }
1669− in EventSelector $ \k -> eventFan k f
1670−
1671−runHoldInits :: IORef [SomeHoldInit x] -> IORef [SomeMergeInit x] -> EventM x ()
1672−runHoldInits holdInitRef mergeInitRef = do
1673− holdInits <- liftIO $ readIORef holdInitRef
1674− mergeInits <- liftIO $ readIORef mergeInitRef
1675− unless (null holdInits && null mergeInits) $ do
1676− liftIO $ writeIORef holdInitRef []
1677− liftIO $ writeIORef mergeInitRef []
1678− mapM_ initHold holdInits
1679− mapM_ unSomeMergeInit mergeInits
1680− runHoldInits holdInitRef mergeInitRef
1681−
1682−initHold :: SomeHoldInit x -> EventM x ()
1683−initHold (SomeHoldInit h) = void $ getHoldEventSubscription h
1684−
1685−mkInitMerge :: GCompare k => MergeSubscribed x k -> Event x (R.PatchDMap k (Event x)) -> EventM x ()
1686−mkInitMerge subscribed changed = do
1687− changeSub <- liftIO $ newSubscriberMergeChange subscribed
1688− (EventSubscription _ changeSubd, change) <- subscribeAndRead changed changeSub
1689− forM_ change $ \c -> defer $ SomeMergeUpdate (mkUpdateMerge c subscribed) (invalidateMergeHeight subscribed) (revalidateMergeHeight subscribed)
1690− liftIO $ writeIORef (mergeSubscribedChange subscribed) (changeSub, changeSubd)
1691−
1692−mkUpdateMerge :: forall k x. GCompare k => R.PatchDMap k (Event x) -> MergeSubscribed x k -> EventM x [EventSubscription x]
1693−mkUpdateMerge (R.PatchDMap p) m = do
1694− oldParents <- liftIO $ readIORef $ mergeSubscribedParents m
1695− let f (subscriptionsToKill, ps) (k :=> R.ComposeMaybe me) = do
1696− (mOldSubd, newPs) <- case me of
1697− Nothing -> return $ DMap.updateLookupWithKey (\_ _ -> Nothing) k ps
1698− Just e -> do
1699− s <- liftIO $ newSubscriberMerge k m
1700− subscription@(EventSubscription _ subd) <- subscribe e s
1701− newParentHeight <- liftIO $ getEventSubscribedHeight subd
1702− let newParent = MergeSubscribedParent subscription s
1703− liftIO $ addMergeHeight newParentHeight m
1704− return $ DMap.insertLookupWithKey' (\_ new _ -> new) k newParent ps
1705− forM_ mOldSubd $ \oldSubd -> do
1706− oldHeight <- liftIO $ getEventSubscribedHeight $ _eventSubscription_subscribed $ mergeSubscribedParentSubscription oldSubd
1707− liftIO $ removeMergeHeight oldHeight m
1708− return (maybeToList (mergeSubscribedParentSubscription <$> mOldSubd) ++ subscriptionsToKill, newPs)
1709− (subscriptionsToKill, newParents) <- 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
1710− liftIO $ writeIORef (mergeSubscribedParents m) $! newParents
1711− return subscriptionsToKill
1712−
1713−-- | Run an event action outside of a frame
1714−runFrame :: forall x a. EventM x a -> SpiderHost x a --TODO: This function also needs to hold the mutex
1715−runFrame a = SpiderHost $ ask >>= \spiderTimeline -> lift $ do
1716− -- 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
1717− pendingCleanups <- atomicModifyIORef (_spiderTimeline_cleanups spiderTimeline) $ \x -> ([], x)
1718− {-# SCC "cleanups" #-} sequence_ pendingCleanups
1719− toAssignRef <- newIORef [] -- This should only actually get used when events are firing
1720− holdInitRef <- newIORef []
1721− mergeUpdateRef <- newIORef []
1722− mergeInitRef <- newIORef []
1723− heightRef <- newIORef zeroHeight
1724− toClearRef <- newIORef []
1725− toClearRootRef <- newIORef []
1726− coincidenceInfosRef <- newIORef []
1727− delayedRef <- liftIO $ newIORef IntMap.empty
1728− let env = EventEnv spiderTimeline toAssignRef holdInitRef mergeUpdateRef mergeInitRef toClearRef toClearRootRef heightRef coincidenceInfosRef delayedRef
1729− let go = do
1730− result <- a
1731− 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
1732− return result
1733− result <- runEventM go env
1734− toClear <- readIORef toClearRef
1735− forM_ toClear $ \(SomeClear ref) -> {-# SCC "clear" #-} writeIORef ref Nothing
1736− toClearRoot <- readIORef toClearRootRef
1737− forM_ toClearRoot $ \(SomeRootClear ref) -> {-# SCC "rootClear" #-} writeIORef ref $! DMap.empty
1738− toAssign <- readIORef toAssignRef
1739− toReconnectRef <- newIORef []
1740− coincidenceInfos <- readIORef coincidenceInfosRef
1741− forM_ toAssign $ \(SomeAssignment vRef iRef v) -> {-# SCC "assignment" #-} do
1742− writeIORef vRef v
1743− when debugInvalidate $ putStrLn $ "Invalidating Hold"
1744− writeIORef iRef =<< evaluate =<< invalidate toReconnectRef =<< readIORef iRef
1745− mergeUpdates <- readIORef mergeUpdateRef
1746− writeIORef mergeUpdateRef []
1747− when debugPropagate $ putStrLn "Updating merges"
1748− mergeSubscriptionsToKill <- flip runEventM env $ concat <$> mapM _someMergeUpdate_update mergeUpdates
1749− when debugPropagate $ putStrLn "Updating merges done"
1750− toReconnect <- readIORef toReconnectRef
1751− switchSubscriptionsToKill <- forM toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1752− oldSubscription <- readIORef $ switchSubscribedCurrentParent subscribed
1753− wi <- readIORef $ switchSubscribedOwnWeakInvalidator subscribed
1754− when debugInvalidate $ putStrLn $ "Finalizing invalidator for Switch" <> showNodeId subscribed
1755− finalize wi
1756− i <- evaluate $ switchSubscribedOwnInvalidator subscribed
1757− wi' <- mkWeakPtrWithDebug i "wi'"
1758− writeIORef (switchSubscribedOwnWeakInvalidator subscribed) $! wi'
1759− writeIORef (switchSubscribedBehaviorParents subscribed) []
1760− writeIORef holdInitRef [] --TODO: Should we reuse this?
1761− e <- runBehaviorM (readBehaviorTracked (switchSubscribedParent subscribed)) (Just (wi', switchSubscribedBehaviorParents subscribed)) holdInitRef
1762− 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
1763− --TODO: Make sure we touch the pieces of the SwitchSubscribed at the appropriate times
1764− sub <- newSubscriberSwitch subscribed
1765− subscription <- runReaderT (unSpiderHost (runFrame ({-# SCC "subscribeSwitch" #-} subscribe e sub))) spiderTimeline --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
1766− {-
1767− stackTrace <- liftIO $ fmap renderStack $ ccsToStrings =<< (getCCSOf $! switchSubscribedParent subscribed)
1768− liftIO $ putStrLn $ (++stackTrace) $ "subd' subscribed to " ++ case e of
1769− EventRoot _ -> "EventRoot"
1770− EventNever -> "EventNever"
1771− _ -> "something else"
1772− -}
1773− writeIORef (switchSubscribedCurrentParent subscribed) $! subscription
1774− return oldSubscription
1775− liftIO $ mapM_ unsubscribe mergeSubscriptionsToKill
1776− liftIO $ mapM_ unsubscribe switchSubscriptionsToKill
1777− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> {-# SCC "switchSubscribed" #-} do
1778− EventSubscription _ subd' <- readIORef $ switchSubscribedCurrentParent subscribed
1779− parentHeight <- getEventSubscribedHeight subd'
1780− myHeight <- readIORef $ switchSubscribedHeight subscribed
1781− when (parentHeight /= myHeight) $ do
1782− writeIORef (switchSubscribedHeight subscribed) $! invalidHeight
1783− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ invalidateSubscriberHeight myHeight
1784− mapM_ _someMergeUpdate_invalidateHeight mergeUpdates --TODO: In addition to when the patch is completely empty, we should also not run this if it has some Nothing values, but none of them have actually had any effect; potentially, we could even check for Just values with no effect (e.g. by comparing their IORefs and ignoring them if they are unchanged); actually, we could just check if the new height is different
1785− forM_ coincidenceInfos $ \(SomeResetCoincidence subscription mcs) -> do
1786− unsubscribe subscription
1787− mapM_ invalidateCoincidenceHeight mcs
1788− forM_ coincidenceInfos $ \(SomeResetCoincidence _ mcs) -> mapM_ recalculateCoincidenceHeight mcs
1789− mapM_ _someMergeUpdate_recalculateHeight mergeUpdates
1790− forM_ toReconnect $ \(SomeSwitchSubscribed subscribed) -> do
1791− height <- calculateSwitchHeight subscribed
1792− updateSwitchHeight height subscribed
1793− return result
1794−
1795−newtype Height = Height { unHeight :: Int } deriving (Show, Read, Eq, Ord, Bounded)
1796−
1797−{-# INLINE zeroHeight #-}
1798−zeroHeight :: Height
1799−zeroHeight = Height 0
1800−
1801−{-# INLINE invalidHeight #-}
1802−invalidHeight :: Height
1803−invalidHeight = Height (-1000)
1804−
1805−#ifdef DEBUG_CYCLES
1806−-- | An invalid height that is currently being traversed, e.g. by walkInvalidHeightParents
1807−{-# INLINE invalidHeightBeingTraversed #-}
1808−invalidHeightBeingTraversed :: Height
1809−invalidHeightBeingTraversed = Height (-1001)
1810−#endif
1811−
1812−{-# INLINE succHeight #-}
1813−succHeight :: Height -> Height
1814−succHeight h@(Height a) =
1815− if h == invalidHeight
1816− then invalidHeight
1817− else Height $ succ a
1818−
1819−removeMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1820−removeMergeHeight oldParentHeight subscribed = do
1821− when debugInvalidateHeight $ putStrLn $ "removeMergeHeight: " <> show oldParentHeight <> " Merge" <> showNodeId subscribed
1822− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1823− let newHeights = heightBagRemove oldParentHeight oldHeights
1824− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1825−
1826−invalidateMergeHeight :: MergeSubscribed x k -> IO ()
1827−invalidateMergeHeight subscribed = do
1828− oldHeight <- readIORef $ mergeSubscribedHeight subscribed
1829− -- If the height used to be valid, it must be invalid now; we should never have *more* heights than we have parents
1830− when (oldHeight /= invalidHeight) $ do
1831− writeIORef (mergeSubscribedHeight subscribed) $! invalidHeight
1832− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1833−
1834−addMergeHeight :: Height -> MergeSubscribed x k -> IO ()
1835−addMergeHeight newParentHeight subscribed = do
1836− when debugInvalidateHeight $ putStrLn $ "addMergeHeight: " <> show newParentHeight <> " Merge" <> showNodeId subscribed
1837− oldHeights <- readIORef $ mergeSubscribedHeightBag subscribed
1838− let newHeights = heightBagAdd newParentHeight oldHeights
1839− writeIORef (mergeSubscribedHeightBag subscribed) $! newHeights
1840−
1841−revalidateMergeHeight :: MergeSubscribed x k -> IO ()
1842−revalidateMergeHeight subscribed = do
1843− currentHeight <- readIORef $ mergeSubscribedHeight subscribed
1844− when (currentHeight == invalidHeight) $ do -- revalidateMergeHeight may be called multiple times; perhaps the's a way to finesse it to avoid this check
1845− heights <- readIORef $ mergeSubscribedHeightBag subscribed
1846− parents <- readIORef $ mergeSubscribedParents subscribed
1847− -- When the number of heights in the bag reaches the number of parents, we should have a valid height
1848− case heightBagSize heights `compare` DMap.size parents of
1849− LT -> return ()
1850− EQ -> do
1851− let height = succHeight $ heightBagMax heights
1852− when debugInvalidateHeight $ putStrLn $ "recalculateSubscriberHeight: height: " <> show height
1853− writeIORef (mergeSubscribedHeight subscribed) $! height
1854− WeakBag.traverse (mergeSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1855− GT -> error $ "revalidateMergeHeight: more heights than parents for Merge" <> showNodeId subscribed
1856−
1857−invalidateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1858−invalidateCoincidenceHeight subscribed = do
1859− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1860− when (oldHeight /= invalidHeight) $ do
1861− writeIORef (coincidenceSubscribedHeight subscribed) $! invalidHeight
1862− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ invalidateSubscriberHeight oldHeight
1863−
1864−updateSwitchHeight :: Height -> SwitchSubscribed x a -> IO ()
1865−updateSwitchHeight new subscribed = do
1866− oldHeight <- readIORef $ switchSubscribedHeight subscribed
1867− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1868− when (new /= invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1869− writeIORef (switchSubscribedHeight subscribed) $! new
1870− WeakBag.traverse (switchSubscribedSubscribers subscribed) $ recalculateSubscriberHeight new
1871−
1872−recalculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO ()
1873−recalculateCoincidenceHeight subscribed = do
1874− oldHeight <- readIORef $ coincidenceSubscribedHeight subscribed
1875− when (oldHeight == invalidHeight) $ do --TODO: This 'when' should probably be an assertion
1876− height <- calculateCoincidenceHeight subscribed
1877− when (height /= invalidHeight) $ do
1878− writeIORef (coincidenceSubscribedHeight subscribed) $! height
1879− WeakBag.traverse (coincidenceSubscribedSubscribers subscribed) $ recalculateSubscriberHeight height
1880−
1881−calculateSwitchHeight :: SwitchSubscribed x a -> IO Height
1882−calculateSwitchHeight subscribed = getEventSubscribedHeight . _eventSubscription_subscribed =<< readIORef (switchSubscribedCurrentParent subscribed)
1883−
1884−calculateCoincidenceHeight :: CoincidenceSubscribed x a -> IO Height
1885−calculateCoincidenceHeight subscribed = do
1886− outerHeight <- getEventSubscribedHeight $ _eventSubscription_subscribed $ coincidenceSubscribedOuterParent subscribed
1887− innerHeight <- maybe (return zeroHeight) getEventSubscribedHeight =<< readIORef (coincidenceSubscribedInnerParent subscribed)
1888− return $ if outerHeight == invalidHeight || innerHeight == invalidHeight then invalidHeight else max outerHeight innerHeight
1889−
1890−data SomeSwitchSubscribed x = forall a. SomeSwitchSubscribed {-# NOUNPACK #-} (SwitchSubscribed x a)
1891−
1892−invalidate :: IORef [SomeSwitchSubscribed x] -> WeakList (Invalidator x) -> IO (WeakList (Invalidator x))
1893−invalidate toReconnectRef wis = do
1894− forM_ wis $ \wi -> do
1895− mi <- deRefWeak wi
1896− case mi of
1897− Nothing -> do
1898− traceInvalidate "invalidate Dead"
1899− return () --TODO: Should we clean this up here?
1900− Just i -> do
1901− finalize wi -- Once something's invalidated, it doesn't need to hang around; this will change when some things are strict
1902− case i of
1903− InvalidatorPull p -> do
1904− traceInvalidate $ "invalidate: Pull" <> showNodeId p
1905− mVal <- readIORef $ pullValue p
1906− forM_ mVal $ \val -> do
1907− writeIORef (pullValue p) Nothing
1908− writeIORef (pullSubscribedInvalidators val) =<< evaluate =<< invalidate toReconnectRef =<< readIORef (pullSubscribedInvalidators val)
1909− InvalidatorSwitch subscribed -> do
1910− traceInvalidate $ "invalidate: Switch" <> showNodeId subscribed
1911− modifyIORef' toReconnectRef (SomeSwitchSubscribed subscribed :)
1912− 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
1913−
1914−--------------------------------------------------------------------------------
1915−-- Reflex integration
1916−--------------------------------------------------------------------------------
1917−
1918−-- | The default, global Spider environment
1919−type Spider = SpiderTimeline Global
1920−
1921−-- | Designates the default, global Spider timeline
1922−data Global
1923−
1924−{-# NOINLINE globalSpiderTimeline #-}
1925−globalSpiderTimeline :: SpiderTimeline Global
1926−globalSpiderTimeline = unsafePerformIO unsafeNewSpiderTimeline
1927−
1928−-- | Stores all global data relevant to a particular Spider timeline; only one
1929−-- value should exist for each type @x@
1930−data SpiderTimeline x = SpiderTimeline
1931− { _spiderTimeline_toUnsubscribe :: !(IORef [EventSubscription x])
1932− , _spiderTimeline_lock :: !(MVar ())
1933− , _spiderTimeline_cleanups :: !(IORef [IO ()])
1934−#ifdef DEBUG
1935− , _spiderTimeline_depth :: !(IORef Int)
1936−#endif
1937− }
1938−type role SpiderTimeline nominal
1939−
1940−instance GEq SpiderTimeline where
1941− a `geq` b = if _spiderTimeline_lock a == _spiderTimeline_lock b
1942− then Just $ unsafeCoerce Refl -- This unsafeCoerce is safe because the same SpiderTimeline can't have two different 'x' arguments
1943− else Nothing
1944−
1945−unsafeNewSpiderTimeline :: forall x. IO (SpiderTimeline x)
1946−unsafeNewSpiderTimeline = do
1947− toUnsubscribe <- newIORef []
1948− lock <- newMVar ()
1949− cleanups <- newIORef []
1950−#ifdef DEBUG
1951− depthRef <- newIORef 0
1952−#endif
1953− return $ SpiderTimeline
1954− { _spiderTimeline_toUnsubscribe = toUnsubscribe
1955− , _spiderTimeline_lock = lock
1956− , _spiderTimeline_cleanups = cleanups
1957−#ifdef DEBUG
1958− , _spiderTimeline_depth = depthRef
1959−#endif
1960− }
1961−
1962−-- | Create a new SpiderTimeline
1963−newSpiderTimeline :: IO (Some SpiderTimeline)
1964−newSpiderTimeline = withSpiderTimeline (pure . Some.This)
1965−
1966−-- | Pass a new timeline to the given function.
1967−withSpiderTimeline :: (forall x. SpiderTimeline x -> IO r) -> IO r
1968−withSpiderTimeline k = unsafeNewSpiderTimeline >>= k
1969−
1970−newtype SpiderPullM x a = SpiderPullM (BehaviorM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1971−
1972−newtype SpiderPushM x a = SpiderPushM (ComputeM x a) deriving (Functor, Applicative, Monad, MonadIO, MonadFix)
1973−
1974−instance Functor (R.Dynamic (SpiderTimeline x)) where
1975− fmap f = SpiderDynamic . newMapDyn f . unSpiderDynamic
1976−
1977−instance Applicative (R.Dynamic (SpiderTimeline x)) where
1978− pure = SpiderDynamic . dynamicConst
1979− SpiderDynamic a <*> SpiderDynamic b = SpiderDynamic $ zipDynWith ($) a b
1980− _ *> b = b
1981− a <* _ = a
1982−
1983−instance Monad (R.Dynamic (SpiderTimeline x)) where
1984− {-# INLINE return #-}
1985− return = pure
1986− {-# INLINE (>>=) #-}
1987− x >>= f = SpiderDynamic $ dynamicDynIdentity $ newJoinDyn $ newMapDyn (unSpiderDynamic . f) $ unSpiderDynamic x
1988− {-# INLINE (>>) #-}
1989− _ >> y = y
1990− {-# INLINE fail #-}
1991− fail _ = error "Dynamic does not support 'fail'"
1992−
1993−instance R.Reflex (SpiderTimeline x) where
1994− newtype Behavior (SpiderTimeline x) a = SpiderBehavior { unSpiderBehavior :: Behavior x a }
1995− newtype Event (SpiderTimeline x) a = SpiderEvent { unSpiderEvent :: Event x a }
1996− newtype Dynamic (SpiderTimeline x) a = SpiderDynamic { unSpiderDynamic :: Dynamic x (Identity a) } -- deriving (Functor, Applicative, Monad)
1997− newtype Incremental (SpiderTimeline x) p = SpiderIncremental { unSpiderIncremental :: Dynamic x p }
1998− type PullM (SpiderTimeline x) = SpiderPullM x
1999− type PushM (SpiderTimeline x) = SpiderPushM x
2000− {-# INLINABLE never #-}
2001− never = SpiderEvent eventNever
2002− {-# INLINABLE constant #-}
2003− constant = SpiderBehavior . behaviorConst
2004− {-# INLINABLE push #-}
2005− push f = SpiderEvent . push (coerce f) . unSpiderEvent
2006− {-# INLINABLE pull #-}
2007− pull = SpiderBehavior . pull . coerce
2008− {-# INLINABLE merge #-}
2009− merge = SpiderEvent . merge . dynamicConst . (coerce :: DMap k (R.Event (SpiderTimeline x)) -> DMap k (Event x))
2010− {-# INLINABLE fan #-}
2011− fan e = R.EventSelector $ SpiderEvent . select (fan (unSpiderEvent e))
2012− {-# INLINABLE switch #-}
2013− switch = SpiderEvent . switch . (coerce :: Behavior x (R.Event (SpiderTimeline x) a) -> Behavior x (Event x a)) . unSpiderBehavior
2014− {-# INLINABLE coincidence #-}
2015− coincidence = SpiderEvent . coincidence . (coerce :: Event x (R.Event (SpiderTimeline x) a) -> Event x (Event x a)) . unSpiderEvent
2016− {-# INLINABLE current #-}
2017− current = SpiderBehavior . dynamicCurrent . unSpiderDynamic
2018− {-# INLINABLE updated #-}
2019− updated = SpiderEvent . fmap runIdentity . dynamicUpdated . unSpiderDynamic
2020− {-# INLINABLE unsafeBuildDynamic #-}
2021− unsafeBuildDynamic readV0 v' = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (coerce readV0) $ coerce $ unSpiderEvent v'
2022− {-# INLINABLE unsafeBuildIncremental #-}
2023− unsafeBuildIncremental readV0 dv = SpiderIncremental $ dynamicDyn $ unsafeDyn (coerce readV0) $ unSpiderEvent dv
2024− {-# INLINABLE mergeIncremental #-}
2025− mergeIncremental = SpiderEvent . merge . (unsafeCoerce :: Dynamic x (R.PatchDMap k (R.Event (SpiderTimeline x))) -> Dynamic x (R.PatchDMap k (Event x))) . unSpiderIncremental
2026− {-# INLINABLE currentIncremental #-}
2027− currentIncremental = SpiderBehavior . dynamicCurrent . unSpiderIncremental
2028− {-# INLINABLE updatedIncremental #-}
2029− updatedIncremental = SpiderEvent . dynamicUpdated . unSpiderIncremental
2030− {-# INLINABLE incrementalToDynamic #-}
2031− incrementalToDynamic (SpiderIncremental i) = SpiderDynamic $ dynamicDynIdentity $ unsafeDyn (readBehaviorUntracked $ dynamicCurrent i) $ flip push (dynamicUpdated i) $ \p -> do
2032− c <- readBehaviorUntracked $ dynamicCurrent i
2033− return $ Identity <$> R.apply p c --TODO: Avoid the redundant 'apply'
2034− eventCoercion Coercion = Coercion
2035− behaviorCoercion Coercion = Coercion
2036− dynamicCoercion = unsafeCoerce --TODO: How can we avoid this unsafeCoerce? This is safe only because we know how Identity works as a Patch instance
2037−
2038−instance R.MonadSample (SpiderTimeline x) (EventM x) where
2039− {-# INLINABLE sample #-}
2040− sample (SpiderBehavior b) = readBehaviorUntracked b
2041−
2042−instance R.MonadHold (SpiderTimeline x) (EventM x) where
2043− {-# INLINABLE hold #-}
2044− hold = holdSpiderEventM
2045− {-# INLINABLE holdDyn #-}
2046− holdDyn = holdDynSpiderEventM
2047− {-# INLINABLE holdIncremental #-}
2048− holdIncremental = holdIncrementalSpiderEventM
2049−
2050−holdSpiderEventM :: a -> R.Event (SpiderTimeline x) a -> EventM x (R.Behavior (SpiderTimeline x) a)
2051−holdSpiderEventM v0 e = fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2052−
2053−holdDynSpiderEventM :: a -> R.Event (SpiderTimeline x) a -> EventM x (R.Dynamic (SpiderTimeline x) a)
2054−holdDynSpiderEventM v0 e = fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2055−
2056−holdIncrementalSpiderEventM :: R.Patch p => R.PatchTarget p -> R.Event (SpiderTimeline x) p -> EventM x (R.Incremental (SpiderTimeline x) p)
2057−holdIncrementalSpiderEventM v0 e = fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2058−
2059−instance R.MonadHold (SpiderTimeline x) (SpiderHost x) where
2060− {-# INLINABLE hold #-}
2061− hold v0 e = R.runHostFrame $ R.hold v0 e
2062− {-# INLINABLE holdDyn #-}
2063− holdDyn v0 e = R.runHostFrame $ R.holdDyn v0 e
2064− {-# INLINABLE holdIncremental #-}
2065− holdIncremental v0 e = R.runHostFrame $ R.holdIncremental v0 e
2066−
2067−instance R.MonadSample (SpiderTimeline x) (SpiderHost x) where
2068− {-# INLINABLE sample #-}
2069− sample = runFrame . readBehaviorUntracked . unSpiderBehavior
2070−
2071−instance R.MonadSample (SpiderTimeline x) (SpiderPullM x) where
2072− {-# INLINABLE sample #-}
2073− sample = coerce . readBehaviorTracked . unSpiderBehavior
2074−
2075−instance R.MonadSample (SpiderTimeline x) (SpiderPushM x) where
2076− {-# INLINABLE sample #-}
2077− sample (SpiderBehavior b) = SpiderPushM $ readBehaviorUntracked b
2078−
2079−instance R.MonadHold (SpiderTimeline x) (SpiderPushM x) where
2080− {-# INLINABLE hold #-}
2081− hold v0 e = R.current <$> R.holdDyn v0 e
2082− {-# INLINABLE holdDyn #-}
2083− holdDyn v0 (SpiderEvent e) = SpiderPushM $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce e
2084− {-# INLINABLE holdIncremental #-}
2085− holdIncremental v0 (SpiderEvent e) = SpiderPushM $ SpiderIncremental . dynamicHold <$> hold v0 e
2086−
2087−data RootTrigger x a = forall k. GCompare k => RootTrigger (WeakBag (Subscriber x a), IORef (DMap k Identity), k a)
2088−
2089−data SpiderEventHandle x a = SpiderEventHandle
2090− { spiderEventHandleSubscription :: EventSubscription x
2091− , spiderEventHandleValue :: IORef (Maybe a)
2092− }
2093−
2094−instance R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHostFrame x) where
2095− {-# INLINABLE subscribeEvent #-}
2096− subscribeEvent e = SpiderHostFrame $ do
2097− --TODO: Unsubscribe eventually (manually and/or with weak ref)
2098− val <- liftIO $ newIORef Nothing
2099− subscription <- subscribe (unSpiderEvent e) $ Subscriber
2100− { subscriberPropagate = \a -> do
2101− liftIO $ writeIORef val $ Just a
2102− scheduleClear val
2103− , subscriberInvalidateHeight = \_ -> return ()
2104− , subscriberRecalculateHeight = \_ -> return ()
2105− }
2106− return $ SpiderEventHandle
2107− { spiderEventHandleSubscription = subscription
2108− , spiderEventHandleValue = val
2109− }
2110−
2111−instance R.ReflexHost (SpiderTimeline x) where
2112− type EventTrigger (SpiderTimeline x) = RootTrigger x
2113− type EventHandle (SpiderTimeline x) = SpiderEventHandle x
2114− type HostFrame (SpiderTimeline x) = SpiderHostFrame x
2115−
2116−instance R.MonadReadEvent (SpiderTimeline x) (ReadPhase x) where
2117− {-# NOINLINE readEvent #-}
2118− readEvent h = ReadPhase $ fmap (fmap return) $ liftIO $ do
2119− result <- readIORef $ spiderEventHandleValue h
2120− touch h
2121− return result
2122−
2123−instance MonadRef (EventM x) where
2124− type Ref (EventM x) = Ref IO
2125− {-# INLINABLE newRef #-}
2126− {-# INLINABLE readRef #-}
2127− {-# INLINABLE writeRef #-}
2128− newRef = liftIO . newRef
2129− readRef = liftIO . readRef
2130− writeRef r a = liftIO $ writeRef r a
2131−
2132−instance MonadAtomicRef (EventM x) where
2133− {-# INLINABLE atomicModifyRef #-}
2134− atomicModifyRef r f = liftIO $ atomicModifyRef r f
2135−
2136−-- | The monad for actions that manipulate a Spider timeline identified by @x@
2137−newtype SpiderHost x a = SpiderHost { unSpiderHost :: ReaderT (SpiderTimeline x) IO a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2138−
2139−instance Monad (SpiderHost x) where
2140− {-# INLINABLE (>>=) #-}
2141− SpiderHost x >>= f = SpiderHost $ x >>= unSpiderHost . f
2142− {-# INLINABLE (>>) #-}
2143− SpiderHost x >> SpiderHost y = SpiderHost $ x >> y
2144− {-# INLINABLE return #-}
2145− return x = SpiderHost $ return x
2146− {-# INLINABLE fail #-}
2147− fail s = SpiderHost $ fail s
2148−
2149−-- | Run an action affecting the global Spider timeline; this will be guarded by
2150−-- a mutex for that timeline
2151−runSpiderHost :: SpiderHost Global a -> IO a
2152−runSpiderHost (SpiderHost a) = runReaderT a globalSpiderTimeline
2153−
2154−-- | Run an action affecting a given Spider timeline; this will be guarded by a
2155−-- mutex for that timeline
2156−runSpiderHostForTimeline :: SpiderHost x a -> SpiderTimeline x -> IO a
2157−runSpiderHostForTimeline (SpiderHost a) = runReaderT a
2158−
2159−newtype SpiderHostFrame x a = SpiderHostFrame { runSpiderHostFrame :: EventM x a } deriving (Functor, Applicative, MonadFix, MonadIO, MonadException, MonadAsyncException)
2160−
2161−instance Monad (SpiderHostFrame x) where
2162− {-# INLINABLE (>>=) #-}
2163− SpiderHostFrame x >>= f = SpiderHostFrame $ x >>= runSpiderHostFrame . f
2164− {-# INLINABLE (>>) #-}
2165− SpiderHostFrame x >> SpiderHostFrame y = SpiderHostFrame $ x >> y
2166− {-# INLINABLE return #-}
2167− return x = SpiderHostFrame $ return x
2168− {-# INLINABLE fail #-}
2169− fail s = SpiderHostFrame $ fail s
2170−
2171−instance R.MonadSample (SpiderTimeline x) (SpiderHostFrame x) where
2172− sample = SpiderHostFrame . readBehaviorUntracked . unSpiderBehavior --TODO: This can cause problems with laziness, so we should get rid of it if we can
2173−
2174−instance R.MonadHold (SpiderTimeline x) (SpiderHostFrame x) where
2175− {-# INLINABLE hold #-}
2176− hold v0 e = SpiderHostFrame $ fmap (SpiderBehavior . behaviorHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2177− {-# INLINABLE holdDyn #-}
2178− holdDyn v0 e = SpiderHostFrame $ fmap (SpiderDynamic . dynamicHoldIdentity) $ hold v0 $ coerce $ unSpiderEvent e
2179− {-# INLINABLE holdIncremental #-}
2180− holdIncremental v0 e = SpiderHostFrame $ fmap (SpiderIncremental . dynamicHold) $ hold v0 $ unSpiderEvent e
2181−
2182−newEventWithTriggerIO :: (RootTrigger x a -> IO (IO ())) -> IO (Event x a)
2183−newEventWithTriggerIO f = do
2184− es <- newFanEventWithTriggerIO $ \Refl -> f
2185− return $ select es Refl
2186−
2187−newFanEventWithTriggerIO :: GCompare k => (forall a. k a -> RootTrigger x a -> IO (IO ())) -> IO (EventSelector x k)
2188−newFanEventWithTriggerIO f = do
2189− occRef <- newIORef DMap.empty
2190− subscribedRef <- newIORef DMap.empty
2191− let !r = Root
2192− { rootOccurrence = occRef
2193− , rootSubscribed = subscribedRef
2194− , rootInit = f
2195− }
2196− return $ EventSelector $ \k -> eventRoot k r
2197−
2198−instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHost x) where
2199− newEventWithTrigger = SpiderHost . lift . fmap SpiderEvent . newEventWithTriggerIO
2200− newFanEventWithTrigger f = SpiderHost $ lift $ do
2201− es <- newFanEventWithTriggerIO f
2202− return $ R.EventSelector $ SpiderEvent . select es
2203−
2204−instance R.MonadReflexCreateTrigger (SpiderTimeline x) (SpiderHostFrame x) where
2205− newEventWithTrigger = SpiderHostFrame . EventM . liftIO . fmap SpiderEvent . newEventWithTriggerIO
2206− newFanEventWithTrigger f = SpiderHostFrame $ EventM $ liftIO $ do
2207− es <- newFanEventWithTriggerIO f
2208− return $ R.EventSelector $ SpiderEvent . select es
2209−
2210−instance R.MonadSubscribeEvent (SpiderTimeline x) (SpiderHost x) where
2211− {-# INLINABLE subscribeEvent #-}
2212− subscribeEvent = runFrame . runSpiderHostFrame . R.subscribeEvent
2213−
2214−newtype ReadPhase x a = ReadPhase (ResultM x a) deriving (Functor, Applicative, Monad, MonadFix)
2215−
2216−instance R.MonadSample (SpiderTimeline x) (ReadPhase x) where
2217− {-# INLINABLE sample #-}
2218− sample = ReadPhase . R.sample
2219−
2220−instance R.MonadHold (SpiderTimeline x) (ReadPhase x) where
2221− {-# INLINABLE hold #-}
2222− hold v0 e = ReadPhase $ R.hold v0 e
2223− {-# INLINABLE holdDyn #-}
2224− holdDyn v0 e = ReadPhase $ R.holdDyn v0 e
2225− {-# INLINABLE holdIncremental #-}
2226− holdIncremental v0 e = ReadPhase $ R.holdIncremental v0 e
2227−
2228−instance R.MonadReflexHost (SpiderTimeline x) (SpiderHost x) where
2229− type ReadPhase (SpiderHost x) = ReadPhase x
2230− fireEventsAndRead es (ReadPhase a) = run es a
2231− runHostFrame = runFrame . runSpiderHostFrame
2232−
2233−instance MonadRef (SpiderHost x) where
2234− type Ref (SpiderHost x) = Ref IO
2235− newRef = SpiderHost . newRef
2236− readRef = SpiderHost . readRef
2237− writeRef r = SpiderHost . writeRef r
2238−
2239−instance MonadAtomicRef (SpiderHost x) where
2240− atomicModifyRef r = SpiderHost . atomicModifyRef r
2241−
2242−instance MonadRef (SpiderHostFrame x) where
2243− type Ref (SpiderHostFrame x) = Ref IO
2244− newRef = SpiderHostFrame . newRef
2245− readRef = SpiderHostFrame . readRef
2246− writeRef r = SpiderHostFrame . writeRef r
2247−
2248−instance MonadAtomicRef (SpiderHostFrame x) where
2249− atomicModifyRef r = SpiderHostFrame . atomicModifyRef r
2250−
2251−instance PrimMonad (SpiderHostFrame x) where
2252− type PrimState (SpiderHostFrame x) = PrimState IO
2253− primitive = SpiderHostFrame . EventM . primitive
2254−
2255−--------------------------------------------------------------------------------
2256−-- Deprecated items
2257−--------------------------------------------------------------------------------
2258−
2259−{-# DEPRECATED SpiderEnv "Use 'SpiderTimeline' instead" #-}
2260−type SpiderEnv = SpiderTimeline