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