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