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