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