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