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