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