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