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