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