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